import { Button, Checkbox, Input, Popconfirm, Space } from 'antd'
import React, { useCallback, useEffect, useMemo, useReducer, useState } from 'react'
import { useModel } from 'umi'
import moment from 'moment'
import style from './index.less'
import filePng from '../../../public/file.png'

/**
 * 模板消息 模板预览
 * 高级群发 新增预览 编辑预览 详情预览
 */

type Props = {
    data: any,
    del?: boolean,
    newsDispatch?: (type: any) => void,
    isShowEdit?: boolean,
    showDrawer?: (props?: any) => void,//图文素材弹窗事件
    isShowEditBtn?: boolean,//是否开启编辑内容按钮
    actionId?: number,
    linsFn?: (params: any) => void
}
interface State {
    mediaIds: number[],
    checked: boolean,
    indeterminate: boolean,
    links?: string[],//当前图文中的原文链接数组
    linksSR?: any
}
interface Action {
    type: 'pushData' | 'checked' | 'delData' | 'returnData' | 'setLinks' | 'setLinksSR',
    params?: any
}
function reducer(state: State, action: Action) {
    let { type, params } = action
    switch (type) {
        case 'pushData':
            return { ...state, mediaIds: [...state?.mediaIds, ...params?.mediaIds] }
        case 'delData':
            let mediaIds = [...state?.mediaIds]
            mediaIds = mediaIds.filter((mediaId: number) => {
                if (params?.mediaIds?.every((id: number) => id !== mediaId)) {
                    return mediaId
                }
                return
            })
            return { ...state, mediaIds }
        case 'returnData':
            return { ...state, mediaIds: params?.mediaIds }
        case 'checked':
            return { ...state, checked: params?.checked, indeterminate: params?.indeterminate }
        case 'setLinks':
            console.log('setLinks')
            return { ...state, links: params?.links }
        case 'setLinksSR':
            let newlinksSR = { ...state.linksSR }
            Object.keys(params?.links).forEach(key => {
                newlinksSR[key] = params?.links[key]
            })
            return { ...state, linksSR: newlinksSR }
        default:
            return { ...state }
    }
}
const initState = {
    mediaIds: [],
    checked: false,
    indeterminate: false,
    links: [],
    linksSR: {}
}
const WxDetailsBox = React.memo((props: Props) => {
    const { data, del = false, newsDispatch, isShowEdit = false, showDrawer, isShowEditBtn = true, actionId, linsFn } = props
    const [state, dispatch] = useReducer(reducer, initState)
    const { mediaIds, checked, indeterminate, links, linksSR } = state
    const [isEdit, setIsEdit] = useState<boolean>(false)
    const num = useMemo(() => { return data?.content?.news?.length }, [data])
    const { dispatch: dDispatch } = useModel('useOperating.useMaterialDrawer')//素材内容管理器
    // const { getWXInfo } = useModel('useOperating.useMaterialContent')//获取微信素材详情
    // const { get } = useModel('useOperating.useBdMediaPup')//获取本地素材详情
    const { delMsgGroup, getDetail } = useModel('useOperating.useNews', model => ({ delMsgGroup: model.delMsgGroup, getDetail: model.getDetail }))
    /**手动点击添加 */
    const handleAdd = useCallback((mediaId: number) => {
        dispatch({ type: 'pushData', params: { mediaIds: [mediaId] } })
    }, [num])
    /**手动点击删除 */
    const handleDel = useCallback((mediaId: number) => {
        dispatch({ type: 'delData', params: { mediaIds: [mediaId] } })
    }, [num])
    /**反选 */
    const handelReturn = useCallback(() => {
        let articles = data?.content?.news
        let newMediaIds = articles?.filter((item: { id: number, deleted: boolean }) => {
            if (mediaIds.every((mediaId: number) => mediaId !== item.id) && !item.deleted) {
                return item.id
            }
            return
        })
        let newArr: number[] = []
        newMediaIds.forEach((item: { id: number }) => {
            newArr.push(item.id)
        })
        dispatch({ type: 'returnData', params: { mediaIds: newArr } })
    }, [data, mediaIds])
    /**全选 */
    const handleAll = useCallback(() => {
        if (mediaIds?.length === num) {
            dispatch({ type: 'returnData', params: { mediaIds: [] } })
        } else {
            let newArr: number[] = []
            data?.content?.news?.forEach((item: { id: number, deleted: boolean }) => {
                if (!item.deleted) {
                    newArr.push(item.id)
                }
            })
            dispatch({ type: 'returnData', params: { mediaIds: newArr } })
        }

    }, [data, mediaIds, num])
    /**删除 */
    const deleteNews = useCallback(() => {
        if (mediaIds?.length > 0) {
            delMsgGroup.run({ id: data.id, list: mediaIds }).then((res) => {
                if (res) {
                    getDetail.refresh().then((res: any) => {
                        let { mediaInfo, msgType, mediaId } = res
                        let { name, url, title, } = mediaInfo
                        let theEdit = {
                            url: url,
                            title: name || title,
                            msgType,
                            mediaId,
                            content: mediaInfo,//NEWS使用
                        }
                        if (res) {
                            console.log(res)
                            newsDispatch && newsDispatch({ type: 'setDefaultData', params: { defaultData: { ...res, theEdit } } })
                            dispatch({ type: 'pushData', params: { mediaIds: [] } })
                            dispatch({ type: 'checked', params: { checked: false, indeterminate: false } })
                        }
                    })
                }
            })
        }
    }, [mediaIds, data])
    useEffect(() => {
        let len = mediaIds?.length
        if (len < num && len !== 0) {
            dispatch({ type: 'checked', params: { checked: true, indeterminate: true } })
        }
        if (len === num) {
            dispatch({ type: 'checked', params: { checked: true, indeterminate: false } })
        }
        if (len === 0) {
            dispatch({ type: 'checked', params: { checked: false, indeterminate: false } })
        }
    }, [mediaIds, num])
    //编辑链接
    const editLinks = useCallback(() => {
        if (data && data?.msgType === 'mpnews') {
            let links: string[] = []
            data?.content?.news?.forEach((item: { contentSourceUrl: string }) => {
                links.push(item?.contentSourceUrl || '')
            })
            dispatch({ type: 'setLinks', params: { links } })
        }
    }, [data])
    //编辑内容
    const editContent = useCallback(() => {
        dDispatch({ type: 'actionData', params: { data: { dataArr: data?.content?.news, actionId: 1 } } })//设置编辑器的内容
        showDrawer && showDrawer({ isEdit: true, editId: data?.id })//开启新建素材弹窗
    }, [showDrawer, data])
    //保存链接
    const saveLink = useCallback(() => {
        if (!actionId) {
            //替换文章中的链接
            let news = data?.content?.news?.map((item: { contentSourceUrl: string }, index: number) => {
                if (item.contentSourceUrl !== links[index]) {
                    item.contentSourceUrl = links[index]
                }
                return item
            })
            setIsEdit(false)
        }else{
            setIsEdit(false)
        }
    }, [links, data, actionId, linksSR])
    //默认全选
    useEffect(() => {
        handleAll()
    }, [])
    const Box = useCallback(() => {
        switch (data?.msgType) {
            case 'mpnews':
                return <>
                    {
                        del && <div className={style.details_header}>
                            <Space className={style.btn}>
                                <Checkbox indeterminate={indeterminate} onChange={handleAll} checked={checked}>全选</Checkbox>
                                <Button onClick={handelReturn} type='dashed' size='small'>反选</Button>
                            </Space>
                            <Popconfirm
                                title='确定要删除吗?'
                                onConfirm={deleteNews}
                                placement='left'
                            >
                                <Button type='primary' size='small'>删除</Button>
                            </Popconfirm>

                        </div>
                    }
                    <div className={style.box_card}>
                        {
                            data?.content?.news?.map((list: any, index: number) => {
                                let isAction = mediaIds?.length > 0 ? mediaIds.some((mediaId: number) => mediaId === list.id) : false
                                let isOne = data?.content?.news?.length === 1
                                // if (list.deleted) {
                                return (
                                    <div
                                        className={`${style.img_ScwxBox} ${del && isAction ? style.action : ''} `}
                                        key={(list.thumbMediaId || list.sysMediaId || list.id) + index + (list.menuId || '')}
                                        onClick={() => {
                                            if (!list.deleted) {
                                                if (isAction) {
                                                    handleDel(list.id)
                                                } else {
                                                    handleAdd(list.id)
                                                }
                                            }
                                        }
                                        }>
                                        {!isOne && <span><span>{list.title}</span></span>}
                                        <img src={list?.thumbMediaUrl || list?.thumbUrl} />
                                        {isOne && <div className={style.one}>
                                            <p>{list.title}</p>
                                            <p>{list.digest}</p>
                                        </div>}
                                        {
                                            list.deleted && <div className={style.deleted}>已删除</div>
                                        }
                                    </div>
                                )
                                // }
                                return
                            })
                        }
                    </div>
                </>
            case 'news':
                return <div className={style.box_card}>
                    {
                        data?.newsList?.map((list: any, index: number) => {
                            let isOne = data?.newsList?.length === 1
                            return <div className={`${style.img_ScwxBox} `} key={index}>
                                {!isOne && <span>{list?.title}</span>}
                                <img src={list?.knewsThumbUrl || (list?.knewsThumbId ? filePng : 'https://s.weituibao.com/static/1552098829922/bigfm.png')} />
                                {isOne && <div className={style.one}>
                                    <p>{list?.title}</p>
                                    <p>{list?.description}</p>
                                </div>}
                            </div>
                        })
                    }
                </div>
            case 'mpvideo':
                return <div className={style.mpvideo}>
                    <img src={require('../../../public/image/video.png')} />
                    <p>{data?.name || data?.title}</p>
                </div>
            case 'video':
                return <div className={style.mpvideo}>
                    <img src={require('../../../public/image/video.png')} />
                    <p>{data?.name || data?.title}</p>
                </div>
            case 'voice':
                return <div className={style.voice}>
                    <p>{data?.name || data?.title}</p>
                    <img src={require('../../../public/image/voice.png')} />
                </div>
            case 'image':
                return <div className={style.image}>
                    <img src='https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png' />
                    <img src={data?.url || data?.thumbUrl || data?.imageUrl} />
                </div>
            case 'text':
                let str = ''
                if (Array.isArray(data?.textContent)) {
                    data?.textContent?.forEach((key: string, index: number) => {
                        // if (key) {
                        str += `${key}${index !== data?.textContent.length - 1 ? '<br/>' : ''}`
                        // }
                    })
                } else {
                    str = data?.textContent
                }
                return <div className={style.text}>
                    <img src='https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png' />
                    <p dangerouslySetInnerHTML={{ __html: str }}></p>
                </div>
            case 'tem':
                let { title, dataTem } = data?.data
                let temStr = dataTem?.replace(/\n/g, '<br>')
                return <>
                    {
                        dataTem ? <div className={style.temCon}>
                            <div className={style.title}>{title}</div>
                            <div className={style.rq}>{moment(new Date()).format('MM月DD日')}</div>
                            <p dangerouslySetInnerHTML={{ __html: temStr }}></p>
                        </div> :
                            <div></div>
                    }
                </>
            case 'miniprogrampage':
                return <div className={style.miniprogrampage}>
                    <span className={style.miniprogrampage_title}>{data?.title}</span>
                    <img className={style.miniprogrampage_img} src={data?.imageUrl} />
                    <span className={style.miniprogrampage_bottom}>小程序</span>
                </div>
        }
        return <></>
    }, [data, del, mediaIds, indeterminate, checked])
    return <div className={style.box}>
        <div className={style.top} />
        <div className={style.content} >
            {
                isEdit ? actionId ? <div>
                    {//存在actionID表示私人定制多选批量
                        (linksSR[actionId] || links)?.map((url: string, index: number) => {//存在编辑过的链接使用编辑过的，没有就用默认
                            return <div key={index} style={{ marginBottom: 15 }}>
                                <span>第{index + 1}篇：</span>
                                <Input.TextArea value={url} onChange={(event: React.ChangeEvent<HTMLTextAreaElement>) => {
                                    let newLinks = JSON.parse(JSON.stringify(linksSR[actionId] || links))
                                    newLinks[index] = event.target.value
                                    let newlinksSR = { ...state.linksSR }
                                    newlinksSR[actionId] = newLinks
                                    console.log()
                                    linsFn && linsFn(newlinksSR)
                                    dispatch({ type: 'setLinksSR', params: { links: { [actionId]: newLinks } } })
                                }} disabled={!isShowEdit}/>
                            </div>
                        })
                    }
                </div> : <div>
                    {//常规操作没有批量
                        links?.map((url: string, index: number) => {
                            return <div key={index} style={{ marginBottom: 15 }}>
                                <span>第{index + 1}篇：</span>
                                <Input.TextArea value={url} onChange={(event: React.ChangeEvent<HTMLTextAreaElement>) => {
                                    let newLinks = JSON.parse(JSON.stringify(links))
                                    newLinks[index] = event.target.value
                                    console.log(3333, event.target.value)
                                    dispatch({ type: 'setLinks', params: { links: newLinks } })
                                }} disabled={!isShowEdit}/>
                            </div>
                        })
                    }
                </div> : <Box />
            }
            {
                data?.msgType === 'mpnews'  && <Space style={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
                    {
                        isEdit ?
                            <>
                                {isShowEdit && <Button onClick={saveLink}>保存</Button>}
                                <Button onClick={() => { setIsEdit(false) }}>取消</Button>
                            </>
                            :
                            <>
                                <Button onClick={() => { setIsEdit(true); editLinks() }}>{isShowEdit ? '编辑链接':'查看连接'}</Button>
                                {isShowEditBtn && <Button onClick={editContent}>编辑内容</Button>}
                            </>
                    }
                </Space>
            }
        </div>
    </div>
})
export default WxDetailsBox