import { EyeOutlined } from '@ant-design/icons'
import { Button, message, Modal, Select, Space, Tag, Tooltip } from 'antd'
import { SizeType } from 'antd/lib/config-provider/SizeContext';
import React, { useCallback, useState } from 'react'
import { useEffect } from 'react';
import { useModel } from 'umi'
const { Option } = Select;

/**预览数据弹窗 */
function PreviewModal(props: { data?: { msgType?: string, theEdit?: any, mpIds?: any[], msgContents?: any }, type?: 'text' | 'icon', isKf?: boolean, isYc?: boolean, isTem?: boolean, size?: SizeType, buttonType?: "text" | "primary" | "link" | "ghost" | "default" | "dashed" | undefined }) {
    const { data, type = 'text', isKf = false, isYc = false, isTem = false, size="middle", buttonType="primary" } = props
    const [ylVisible, setYlVisible] = useState<boolean>(false)//预览弹窗
    const [value, setValue] = useState<string>('')//微信号名称
    const { postPreview, kfPreview } = useModel('useOperating.useNews', model => ({ postPreview: model.postPreview, kfPreview: model.kfPreview }))
    const { postReplyStrategyPreview } = useModel('useOperating.useInteract', model => ({ postReplyStrategyPreview: model.postReplyStrategyPreview }))
    const { actionWX } = useModel('useOperating.useWxGroupList', model => ({ actionWX: model.state.actionWX }))
    const { searchFans } = useModel('useOperating.useFans', model => ({ searchFans: model.searchFans }))
    const { temPreview } = useModel('useOperating.useAtemplate', model => ({ temPreview: model.temPreviewAjax }))
    const [names, setNames] = useState<{ id: number, nickname: string, headimgurl: string }[]>([])
    /**存放昵称 */
    const PreviewChange = useCallback((value: string, option: any) => {
        setValue(value)
    }, [actionWX])
    const onSearch = useCallback((val: string) => {
        let mpId = ''
        if (isKf) {
            mpId = (data?.mpIds as any[])[0]?.id || '0'
        } else {
            mpId = actionWX?.id
        }
        searchFans.run({ mpId, nickname: val })
    }, [actionWX, data?.mpIds])
    useEffect(() => {
        let data = searchFans.data
        if (data?.length > 0) {
            setNames(data?.map((item: any) => { return { id: item?.id, nickname: item?.nickname, headimgurl: item?.headimgurl } }))
        }
    }, [searchFans.data])
    /**预览数据 */
    const handlePreview = useCallback(() => {
        if (isKf) {//客服消息预览逻辑
            let { mpIds, msgContents } = data as { mpIds: any[], msgContents: any }
            let newMsgContents = msgContents ? JSON.parse(JSON.stringify(msgContents)) : []
            let params: any = {}
            if (mpIds?.length > 0) {//mpid处理
                params['mpIds'] = []
                mpIds.forEach((wx: { id: number }) => {
                    params['mpIds'].push(wx.id)
                })
            }
            params['msgContents'] = newMsgContents?.map((item: { textContent: any, msgType: string, newsList: any[], platformMediaId?: any, mediaId?: any }) => {
                if (item?.msgType === 'text' && Array.isArray(item.textContent)) {
                    let textContent = ''
                    item?.textContent.forEach((key: string, index: number) => {
                        textContent += `${key.replace(/_href/ig, 'href')}${index !== item?.textContent.length - 1 ? '<br/>' : ''}`
                    })
                    item['textContent'] = textContent
                } else if (item?.msgType === 'news') {
                    let reg = new RegExp('&nbsp;', "g")
                    let newsList = item?.newsList?.map((nl: { title: string }) => {
                        return { ...nl, title: nl?.title.replace(reg, ' ') }
                    })
                    item['newsList'] = newsList
                }
                // platformMediaId
                if (!item?.platformMediaId) {
                    item['platformMediaId'] = item.mediaId
                }
                return item
            })
            names?.forEach((item: { id: number, nickname: string }) => {
                if (value === item?.nickname + '_' + item?.id) {
                    params['fansIds'] = item?.id
                    localStorage.setItem('fans', JSON.stringify(item))
                }
            })
            if (!params?.mpIds) {
                message.error('请添加公众号！')
                return
            }
            if (params?.msgContents?.length === 0) {
                message.error('请添加素材！')
                return
            }
            if (!params.fansIds) {
                message.error('请输入昵称')
                return
            }
            kfPreview.run(params)
        } else if (isYc) {//延迟消息预览
            let { mpIds, msgContents } = data as { mpIds: any[], msgContents: any }
            let params: any = {}
            if (mpIds?.length > 0) {//mpid处理
                params['mpIds'] = []
                mpIds.forEach((wx: { id: number }) => {
                    params['mpIds'].push(wx.id)
                })
            }
            let newMsgContents: any[] = []
            msgContents.forEach((item: any) => {
                let { webType, indexId, newsList } = item
                switch (webType) {
                    case 5:
                        let reg = new RegExp('&nbsp;', "g")
                        let data = newsList?.map((item: { title: string }) => {
                            return { ...item, title: item?.title.replace(reg, ' ') }
                        })
                        newMsgContents.push({ newsList: data, type: 3, msgType: "news", webType: 5, indexId })
                        break;
                    case 4:
                        let textContent: string = ''
                        item?.textContent?.forEach((key: string, index: number) => {
                            textContent += index !== item.textContent.length - 1 ? key.replace(/_href/ig, 'href') + `<br/>` : key.replace(/_href/ig, 'href')
                        })
                        newMsgContents.push({ msgType: "text", textContent, indexId, webType: 4, type: 2 })
                        break;
                    case 6:
                        if (!item?.platformMediaId) {
                            item['platformMediaId'] = item.mediaId
                        }
                        newMsgContents.push(item)
                        break;
                    default:
                        if (!item?.platformMediaId) {
                            item['platformMediaId'] = item.mediaId
                        }
                        newMsgContents.push(item)
                        break;
                }
            })
            params['msgContents'] = newMsgContents
            names?.forEach((item: { id: number, nickname: string }) => {
                if (value === item?.nickname + '_' + item?.id) {
                    params['fansIds'] = item?.id
                    localStorage.setItem('fans', JSON.stringify(item))
                }
            })
            if (params?.msgContents?.length === 0) {
                message.error('请添加素材！')
                return
            }
            if (!params.fansIds) {
                message.error('请输入昵称')
                return
            }
            postReplyStrategyPreview.run(params)
        } else if (isTem) {
            // 模板消息预览
            let { msgContents } = data as { msgContents: any }
            let { fields, queryForm, tagObj } = msgContents
            let dataQuery: any = {}
            let { taskName, fansAll, templateId, enabled, fansFilterSex, isUrl, url, miniprogramAppid, miniprogramPagepath, triggerType, sendTime } = queryForm
            dataQuery.mpId = actionWX?.id
            dataQuery.taskName = taskName
            dataQuery.fansAll = fansAll
            dataQuery.enabled = enabled === 1 ? true : false
            if (!fansAll) {
                if (fansFilterSex !== 'all') {
                    dataQuery.fansFilterSex = fansFilterSex  // 性别
                }
                if (tagObj.fansFilterTagids.length !== 0) {
                    dataQuery.fansFilterTagType = tagObj.fansFilterTagType
                    dataQuery.fansFilterTagids = tagObj.fansFilterTagids
                }
            }
            if (!templateId) { message.error('请选择模板'); return }
            // if(fields.findIndex((item: any) => item.value === '') !== -1) { message.error('模板内容空'); return }
            dataQuery.templateId = templateId
            dataQuery.contentFields = fields
            if (isUrl) {
                if (url) {
                    dataQuery.isUrl = isUrl
                    dataQuery.url = url
                }
            } else {
                if (!miniprogramAppid || !miniprogramPagepath) {
                } else {
                    dataQuery.isUrl = isUrl
                    dataQuery.miniprogramAppid = miniprogramAppid
                    dataQuery.miniprogramPagepath = miniprogramPagepath
                }
            }
            dataQuery.triggerType = triggerType
            if (triggerType === 1) {
                if (sendTime) {
                    dataQuery.sendTime = sendTime
                }
            }
            names?.forEach((item: { id: number, nickname: string }) => {
                if (value === item?.nickname + '_' + item?.id) {
                    dataQuery['fansIds'] = item?.id
                    localStorage.setItem('fans', JSON.stringify(item))
                }
            })
            temPreview.run(dataQuery)
        } else {//高级群发预览逻辑
            let { msgType, theEdit } = data as any
            let textContent = ''
            let obj: any = {}
            theEdit?.textContent?.forEach((key: string, index: number) => {
                textContent += `${key.replace(/_href/ig, 'href')}${index !== theEdit?.textContent.length - 1 ? '<br/>' : ''}`
            })
            if (theEdit?.content?.news) {//图文
                obj = { ...obj, news: theEdit?.content?.news }
            }
            if (theEdit?.content?.news && theEdit?.isWx) {
                obj = { ...obj, wxMediaId: theEdit?.mediaId }
            }
            if (theEdit?.fileType === 'video' || theEdit?.msgType === 'video' || theEdit?.msgType === 'mpvideo') {//视频
                obj = {
                    ...obj,
                    videoDescription: theEdit?.videoDescription,//视频描述
                    videoTitle: theEdit?.videoTitle,//视频标题
                    url: theEdit?.url,//链接  
                }
            }
            if (theEdit?.msgType === 'text' || theEdit?.fileType === 'text') {//文本
                obj = {
                    ...obj,
                    textContent
                }
            }
            if (theEdit?.fileType === 'image' || theEdit?.fileType === 'voice' || theEdit?.msgType === 'image' || theEdit?.msgType === 'voice') {//图片或音频
                obj = {
                    ...obj,
                    title: theEdit?.title,//标题
                    url: theEdit?.url,//链接
                }
            }
            obj = {
                ...obj,
                mediaType: theEdit?.fileType || theEdit?.msgType,//类型
            }
            if (theEdit?.mediaId && theEdit?.msgType !== "mpnews") {
                obj['wxMediaId'] = theEdit?.mediaId
            }
            if (!theEdit) {
                message.error('请选择素材')
                return
            }
            if (!actionWX) {
                message.error('没有选择公众号')
                return
            }
            if (!value) {
                message.error('请输入昵称')
                return
            }
            if (actionWX) {
                // let textContent = ''
                // theEdit?.textContent?.forEach((key: string, index: number) => {
                //     textContent += `${key.replace(/_href/ig, 'href')}${index !== (theEdit?.textContent as string[]).length - 1 ? '<br/>' : ''}`
                // })
                obj = {
                    ...obj,
                    mpId: actionWX?.id,
                    msgType,
                    // mediaId: theEdit?.mediaId,
                    // content: textContent,
                    // wxName: value?.split('_')[0],
                    fansId: value?.split('_')[1],
                }
                localStorage.setItem('fans', JSON.stringify({ nickname: value?.split('_')[0] }))
                postPreview.run(obj)
            }
        }
    }, [data, actionWX, value, postPreview, names, kfPreview])
    /**清空昵称 */
    useEffect(() => {
        if (Array.isArray(data?.mpIds) && ylVisible) {
            let fans = localStorage.getItem('fans') ? JSON.parse(localStorage.getItem('fans') as string) : ''
            let wx = data?.mpIds[0]
            if (fans && wx) {
                searchFans.run({ mpId: wx?.id, nickname: fans?.nickname })
            }
        }
    }, [data, ylVisible])
    useEffect(() => {
        if (!ylVisible) {
            setNames([])
            setValue('')
            searchFans.mutate([])
        } else {
            if (Array.isArray(data?.mpIds)) {
                let fans = localStorage.getItem('fans') ? JSON.parse(localStorage.getItem('fans') as string) : ''
                let wx = data?.mpIds[0]
                if (fans && wx) {
                    searchFans.run({ mpId: wx?.id, nickname: fans?.nickname })
                }
            }
        }
    }, [ylVisible])
    return <>
        {
            type === 'text' ?
                <Button onClick={() => { setYlVisible(true) }} type={buttonType} size={size}>预览</Button>
                :
                <Tooltip placement="top" title='预览'><EyeOutlined onClick={() => { setYlVisible(true) }} /></Tooltip >
        }
        <Modal
            width={500}
            visible={ylVisible}
            title="发送手机预览"
            onCancel={() => setYlVisible(false)}
            // onOk={handlePreview}
            okText='发送预览'
            confirmLoading={postPreview?.loading}
            destroyOnClose
            footer={<Space>
                <Button onClick={() => setYlVisible(false)}>取消</Button>
                <Button type='primary' onClick={handlePreview} loading={postReplyStrategyPreview?.loading || postPreview?.loading || kfPreview?.loading || temPreview?.loading}>发送预览</Button>
            </Space>}
        >
            <div>
                <p>默认预览选择的第一个公众号,关注公众号后，才能接收图文消息预览!</p>
                {
                    data?.mpIds?.map((item: { headImg: string, nickName: string }, index: number) => {
                        if (index === 0) {
                            return <span style={{ border: '1px dashed #d8d8d8', padding: 5, borderRadius: '3px', display: 'flex', justifyContent: 'space-between', width: 100 }} key={index}>
                                <img src={item?.headImg || localStorage?.bookImg} alt="头像" style={{ width: 20, height: 20 }} />
                                <span>{item?.nickName}</span>
                            </span>
                        }
                        return null
                    })
                }
            </div>
            {/* <Input placeholder='请输入微信号名称' style={{ marginBottom: 10 }} onChange={PreviewChange} /> */}
            <Select
                showSearch
                style={{ margin: '10px 0', width: '100%' }}
                placeholder="请输入微信号名称自动模糊搜索匹配"
                optionFilterProp="children"
                onChange={PreviewChange}
                onSearch={onSearch}
                allowClear={true}
            // filterOption={(input: any, option: any) =>
            //     option?.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            // }
            >
                {
                    names?.map((item: { id: number, nickname: string, headimgurl: string }) => {
                        return <Option key={item.id} value={item.nickname + '_' + item.id}>
                            <img src={item?.headimgurl} alt="" style={{ width: 20 }} />&nbsp;{item?.nickname}
                        </Option>
                    })
                }
            </Select>
            <Tag color='warning'>预览功能仅用于公众号查看文章效果，不适用于公众传播，预览链接会在短期内失效</Tag>
        </Modal>
    </>
}

export default React.memo(PreviewModal, (a, b) => {
    if (JSON.stringify(a) === JSON.stringify(b)) {
        return true
    }
    return false
})