import React, { useCallback, useState } from 'react'
import style from './index.less'
import { ArrowDownOutlined, ArrowUpOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons'
import { Avatar, Input, message, Modal, Space } from 'antd'
import { useModel } from 'umi'
import { exportMediaByUrl1 } from '@/services/operating/material'
const Left = React.memo((props: { isWx?: boolean }) => {
    const { isWx } = props
    const { drawerState: { dataArr, actionId }, dispatch } = useModel('useOperating.useMaterialDrawer', model => ({ drawerState: model.state, dispatch: model.dispatch }))
    const { actionWX } = useModel('useOperating.useWxGroupList', model => ({ actionWX: model.state.actionWX }))
    const { ueditorRef } = useModel('useOperating.useMaterialDrawer', model => ({ ueditorRef: model.state.ueditorRef }))
    const [showNews, setShowNews] = useState<boolean>(false)//导入文章
    const [newsUrl, setNewsUrl] = useState<string>('')//文章地址

    //导入文章
    const handleImportNews = useCallback(() => {
        let str = newsUrl
        if (str.indexOf(',') === -1) {
            str = str.replace(/\s/ig, ',')
        }
        let arr = str.split(/[,，]/)
        let newArr: string[] = []
        arr.forEach((url: string) => {
            url = url.replace(/\s*/g, '')
            if (url !== "" && url) {
                newArr.push(url)
            }
        })
        let isOk = newArr.every((url: string, index: number) => {
            if (url.search(/http[s]?:\/\/mp.weixin.qq.com/ig) === 0) {
                return true
            } else {
                message.error(`第${index + 1}的地址错误,请输入正确的文章地址!`)
            }
        })
        if (newArr.length > (9 - actionId)) {
            message.error('你输入的链接条数超过了当前剩余可新增的条数')
            return
        }
        if (isOk) {
            let promiseAll: any[] = []
            newArr.forEach((url: string, index: number) => {
                // promiseAll.push(exportMediaByUrl1(url).then((res) => { return res.json() }))
                promiseAll.push(exportMediaByUrl1(encodeURIComponent(url)).then((res) => { return res.json() }))
            })
            Promise.all(promiseAll).then((res: any) => {
                let arr: any[] = []
                if (res) {
                    res.forEach((r: { data: any, code: 200 }, index: number) => {
                        if (r.code === 200) {
                            let { content, contentSourceUrl, digest, thumbMediaUrl, title } = r.data
                            contentSourceUrl = contentSourceUrl.replace(/['"]*/g, '')
                            content = content.replace('data-src', 'src').replace(/\<mpvoice[\s\S]*\<\/mpvoice\>/ig, '')
                            index === 0 && ueditorRef?.setContent(content, false)
                            arr.push({ menuId: actionId + index, content, contentSourceUrl, digest, thumbMediaUrl, title })
                        }
                    })
                    arr = arr.sort((a: { menuId: number }, b: { menuId: number }) => { return a.menuId - b.menuId })
                    dispatch({ type: 'importNews', params: { data: { dataArrs: arr, actionId } } })
                }
            }).catch(err => { console.log(err) })
            setShowNews(false)
        }
    }, [newsUrl, actionId, ueditorRef])
    return <div className={style.left}>
        {
            isWx && <div className={style.left_top}>
                <Space>
                    <Avatar src={actionWX?.headImg || "https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png"} />
                    <span>{actionWX?.nickName}</span>
                </Space>
            </div>
        }
        <div className={style.left_ul}>
            <ul>
                {
                    dataArr?.map((item: any, index: number) => {
                        return index === 0
                            ?
                            <li
                                className={`${style.first} ${actionId === item.menuId && style.action}`}
                                key={item.menuId}
                                onClick={() => {
                                    dispatch({ type: 'action', params: { menuId: item.menuId } })
                                }}
                            >
                                <p>
                                    {/* <img src='https://mmbiz-qpic-cn.weituibao.com/mmbiz_png/o0slOoU0qk1qibibvCYeHB7tCwW6HGia7wntuqFtE7IYfqkp8lsCegVicBdRNQTFgZdQRLctqVIebWqu5EOib5ejHMQ/0?wx_fmt=png&wxb_id=4so7eVwgLV_RCXsMR1e4Y4hgYPtVj_qfNimo_frijeI' /> */}
                                    <img src={item.thumbMediaUrl || item.thumbUrl || 'https://s.weituibao.com/static/1552098829922/bigfm.png'} alt="" />
                                </p>
                                <span className={style.title}>{item.title || '标题'}</span>
                                <div>
                                    <span>
                                        <ArrowUpOutlined onClick={() => dispatch({ type: 'mobile', params: { eq: index, up: true } })} />
                                        <ArrowDownOutlined onClick={() => dispatch({ type: 'mobile', params: { eq: index } })} />
                                    </span>
                                    <DeleteOutlined onClick={() => dispatch({ type: 'delDataArr', params: { menuId: item.menuId } })} />
                                </div>
                            </li>
                            :
                            <li
                                className={`${index === dataArr.length - 1 && style.last} ${actionId === item.menuId && style.action}`}
                                key={item.menuId}
                                onClick={() => {
                                    dispatch({ type: 'action', params: { menuId: item.menuId } })
                                }
                                }
                            >
                                <p>
                                    <span className={style.title1}>{item.title || '标题'}</span> <img src={item.thumbMediaUrl || item.thumbUrl || 'https://s.weituibao.com/static/1552098829922/bigfm.png'} alt="" />
                                </p>
                                <span />
                                <div>
                                    <span>
                                        <ArrowUpOutlined onClick={() => dispatch({ type: 'mobile', params: { eq: index, up: true } })} />
                                        <ArrowDownOutlined onClick={() => dispatch({ type: 'mobile', params: { eq: index } })} />
                                    </span>
                                    <DeleteOutlined onClick={() => dispatch({ type: 'delDataArr', params: { menuId: item.menuId } })} />
                                </div>
                            </li>
                    })
                }
            </ul>
            {
                dataArr?.length < 8 && <span onClick={() => dispatch({ type: 'addDataArr' })} ><PlusOutlined />新建</span>
            }
            <span onClick={() => { setShowNews(true) }} style={{ marginTop: 10 }}><PlusOutlined />导入文章</span>
            <Modal
                visible={showNews}
                title='导入文章'
                onCancel={() => { setShowNews(false) }}
                onOk={handleImportNews}
                destroyOnClose
            >
                <Input.TextArea
                    placeholder={
                        ` 请填写文章url地址,支持批量，批量传入需要在每个链接后面加上逗号或者换行,从你当前选中的篇数开始导入替换，一次只能导入8篇，输入的链接地址不能超过可新建的篇数，假如你从第5篇开始导入那只能导入4篇
                        
方式1：支持末尾加，号分割导入                     https://mp.weixin.qq.com/s/C4qcDnPwfAlf4Y2P9qeThA,https://mp.weixin.qq.com/s/tVGyg6rxR6BoppjqIbKoGg
方式2：支持换行分割导入
https://mp.weixin.qq.com/s/C4qcDnPwfAlf4Y2P9qeThA
https://mp.weixin.qq.com/s/tVGyg6rxR6BoppjqIbKoGg
`
                    }
                    rows={10}
                    onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => {
                        let url = e.target.value
                        if (url) {
                            setNewsUrl(url)
                        }
                    }}

                />
            </Modal>
        </div>
    </div>
})
export default Left