import React, { useState, useCallback, useMemo, useEffect, useRef } from 'react'

import { Button, Input, message, Space, Spin } from 'antd'
import style from './index.less'

import { useModel, history } from 'umi'
import ActionModal from '@/components/ActionModal'
import TEditor from './TEditor'
import UEditor from './UEditor'


const Title = React.memo(() => {
    const [titleV, setTitleV] = useState<string>('') //title值
    const { state: { actionId, dataArr }, dispatch } = useModel('useOperating.useMaterialDrawer')
    //获取已有Title回写入
    const defaultTitle = useMemo(() => {
        let title = ''
        setTitleV('')
        dataArr.forEach((obj: any) => {
            if (obj.menuId === actionId) {
                if (obj.title) {
                    title = obj.title
                }
            }
        })
        return title
    }, [actionId, dataArr])
    //插入数据
    let titleValue = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
        let value = e.target.value
        console.log(3)
        dispatch({ type: 'pushData', params: { menuId: actionId, title: value } })
        setTitleV(value)
    }, [actionId])
    return <div className={style.ueditor_title}>
        <Input placeholder='输入文章标题（请勿输入特殊字符）' bordered={false} maxLength={64} onChange={titleValue} value={titleV || defaultTitle} />
    </div>
})
interface Props {
    onClose: () => void, //关闭
    editId: string,//编辑ID
    editData: any, //编辑初始内容
    syncNews?: boolean,//同步
    isWx?: boolean //是否是微信素材用来判断不同接口逻辑
    isShowWx?: boolean,
    isAll?: boolean,
    callback?: (data: any) => void //回调获取数据
}
// ======================== TEditor =========================
export default function Editor(props: Props) {
    let { syncNews = true, isWx, isShowWx, isAll = true, callback = null } = props
    const [showActionModal, setShowActionModal] = useState<boolean>(false)//选择公众号弹窗
    const [id, setId] = useState<string>('')
    const [loding, setLoding] = useState<boolean>(true)
    const { getWeData } = useModel('useOperating.useMaterialContent')
    const { dispatchNews } = useModel('useOperating.useNews', model => ({ dispatchNews: model.dispatch }))
    const { dispatch, state } = useModel('useOperating.useMaterialDrawer')
    const { dispatch: contentDispatch } = useModel('useOperating.useMaterialContent')
    const { actionId, actionIdold, dataArr, actionData, ueditorRef, sort = 0 } = state
    const { actionWX } = useModel('useOperating.useWxGroupList', model => ({ actionWX: model.state.actionWX }))
    //
    const { add, list, edit, syncId, addWx, state: { parentId, belongUser }, eidtWxlists } = useModel(isAll ? 'useOperating.useBdMedia' : 'useOperating.useBdMediaPup')
    const { state: { selectWx }, initSelectWx } = useModel('useOperating.useWxGroupList')//公众号筛选
    const [sid, setSid] = useState<number>(0)//已经切换设置过的ID
    const [content, setContent] = useState<string>('<p></p>')//内容
    const editorRef:any = useRef(null);
    //保存
    let seve = useCallback((isSaveNews?: boolean) => {
        let content = ueditorRef?.getContent()
        let menuId = actionIdold || actionId
        console.log('保存dataArr===>',dataArr)
        dispatch({ type: 'pushData', params: { content } })
        let isOk = dataArr.every((item: any) => {
            let img = item?.thumbMediaUrl || item?.thumbUrl
            if (!item.title) {
                message.error(`第${item.menuId}篇标题为空`)
                return false
            }
            if (!img) {
                message.error(`第${item.menuId}篇封面为空`)
                return false
            }
            if (item?.digest?.length > 54) {
                message.error(`第${item.menuId}摘要不能超过54个字`)
                return false
            }
            if (item.content === '<p></p>' || !item.content) {
                message.error(`第${item.menuId}篇内容为空`)
                return false
            }
            // if (!item.contentSourceUrl) {
            //     message.error(`第${item.menuId}原文链接为空`)
            //     return false
            // }
            return true
        })
        if (isOk) {
            let news = dataArr.map((item: any) => {
                return { ...item, showCoverPic: false, thumbUrl: item?.thumbUrl || item?.thumbMediaUrl }
            })
            let data: any = {
                news,
                folder: false,
                fileType: 'news',
                parentId,
                belongUser,
                sort
            }
            if (callback) {//假如有回调那么不请求接口保存直接执行回调函数
                callback && callback(data)
                dispatch({ type: 'initData' })
                props.onClose()
                return
            }
            if (isWx) {//执行微信接口
                console.log('微信素材', props?.editId);
                if (props?.editId) {//编辑走新建本地素材再同步到微信
                    add.run({ ...data, mpIds: selectWx }).then((res: any) => {
                        if (res) {
                            if (isSaveNews) {//走保存去群发逻辑
                                console.log('新建===》保存并群发', props)
                                syncId.run({ mpIds: [actionWX?.id], sysMediaId: res }).then((syncWxres: any) => {
                                    if (syncWxres) {
                                        dispatchNews({ type: 'theEdit', params: { theEdit: { content: { news }, mediaId: syncWxres, msgType: 'mpnews' } } })
                                        history.push(`/operatePage/news/advanced?show=true`)
                                        dispatch({ type: 'initData' })
                                        localStorage.setItem('collapsed', '0')
                                    }
                                })
                            } else {
                                syncId.run({ mpIds: [actionWX?.id], sysMediaId: res }).then((syncWxres: any) => {
                                    if (syncWxres) {
                                        console.log('新建==》保存')
                                        dispatch({ type: 'initData' })
                                        props.onClose()
                                        getWeData.refresh().then((res) => {//刷新页面
                                            contentDispatch({ type: 'initData', params: { data: res.records } })
                                        })
                                        localStorage.setItem('collapsed', '0')
                                    }
                                })
                            }
                        }
                    })
                } else {//新建
                    addWx.run({ mpId: actionWX?.id, mediaType: 'news', news }).then((res: any) => {
                        console.log(res)
                        if (res) {
                            if (isSaveNews) {//走保存去群发逻辑
                                console.log('新建===》保存并群发', props)
                                setId(res)
                                setShowActionModal(true)
                            } else {
                                dispatch({ type: 'initData' })
                                props.onClose()
                                getWeData.refresh().then((res) => {//刷新页面
                                    contentDispatch({ type: 'initData', params: { data: res.records } })
                                })
                                localStorage.setItem('collapsed', '0')
                            }
                        }
                    })
                }
            } else {//执行本地
                if (props?.editId) {//表示编辑
                    edit.run({ belongUser, fileType: 'news', folder: false, news, sysMediaId: props?.editId, sort }).then((res: any) => {
                        if (isSaveNews) {//走保存去群发逻辑
                            console.log('编辑==》保存并群发', news, dataArr)
                            setId(props?.editId)
                            setShowActionModal(true)
                        } else {
                            console.log('编辑===》保存')
                            dispatch({ type: 'initData' })
                            props.onClose()
                            list.refresh()
                            localStorage.setItem('collapsed', '0')
                        }
                    })
                    eidtWxlists.run({ sysMediaId: props?.editId, mpIds: selectWx || [] }).then((res) => {
                        console.log(res, 'eidtWxlists')
                        initSelectWx()
                    })
                } else {//新建
                    add.run({ ...data, mpIds: selectWx }).then((res: any) => {
                        if (res) {
                            if (isSaveNews) {//走保存去群发逻辑
                                console.log('新建===》保存并群发', props)
                                setId(res)
                                setShowActionModal(true)
                                initSelectWx()
                            } else {
                                console.log('新建==》保存')
                                dispatch({ type: 'initData' })
                                props.onClose()
                                list.refresh()
                                localStorage.setItem('collapsed', '0')
                                initSelectWx()
                            }

                        }
                    })
                }
            }

        }
    }, [dataArr, props?.editId, ueditorRef, actionWX, getWeData, isWx, parentId, belongUser, list, selectWx, sort])
    //保存并群发选择公众号后回调
    const saverNews = useCallback((cancel: boolean) => {
        setShowActionModal(false)
        if (!cancel) {//假如cancel为false就是保持并群发
            let news = dataArr.map((item: any) => { return { ...item, showCoverPic: false, thumbUrl: item?.thumbUrl || item?.thumbMediaUrl } })
            console.log(news, dataArr, 'dataArr,news')
            if (actionWX) {
                if (isWx) {
                    // dispatchNews({ type: 'theEdit', params: { theEdit: { content: { news }, mediaId: id, msgType: 'mpnews' } } })
                    // history.push(`/operatePage/news/advanced?show=true`)
                    // dispatch({ type: 'initData' })
                    // localStorage.setItem('collapsed', '0')
                } else {//本地素材先同步再群发
                    syncId.run({ mpIds: [actionWX?.id], sysMediaId: id }).then((syncWxres: any) => {
                        if (syncWxres) {
                            // dispatchNews({ type: 'theEdit', params: { theEdit: { content: { news }, mediaId: syncWxres, msgType: 'mpnews' } } })
                            // history.push(`/operatePage/news/advanced?show=true`)
                            // dispatch({ type: 'initData' })
                            // localStorage.setItem('collapsed', '0')
                        }
                    })
                }
            }
            dispatchNews({ type: 'theEdit', params: { theEdit: { content: { news }, mediaId: id, msgType: 'mpnews' } } })
            history.push(`/operatePage/news/advanced?show=true`)
            dispatch({ type: 'initData' })
            localStorage.setItem('collapsed', '0')
        }
    }, [actionWX, isWx, id, syncId, dataArr])
    // //切换文章
    useEffect(() => {
        console.log('切换文章=====>',{sid,actionId})
        if (sid !== actionId ) {
            setSid(actionId)
            let content = dataArr?.filter((item: { menuId: any }) => item.menuId === actionId)[0]?.content 
            content = content !== '' ? content :  '<p></p>'
            console.log('切换后的content====>',content)
            setContent(content)
        }
    }, [actionId, dataArr,  sid])
    //编辑回填
    const isOk = useCallback((ueditor) => {
        console.log('props?.editData===>',props?.editData)
        if (actionData) {
            let dataArr = actionData.dataArr?.map((item: any, index: number) => {
                item.menuId = index + 1
                return item
            })
            // 存放到数据中心
            dispatch({ type: 'initData', params: { data: { ...actionData, dataArr, actionId: 1 } } })
            setContent(dataArr[0].content)
        }
    }, [props?.editData])
    return <div >
        <h3 style={{ height: 43, lineHeight: '43px', textAlign: 'center' }}>素材编辑</h3>
        <Spin spinning={loding} tip='初始化中请稍等。。。'>
            <Title />
            {/* ================================ TEditor ============================== */}

            <TEditor dispatch={dispatch}  setLoding={setLoding} isOk={isOk} content={content} actionId={actionId} />

             {/* ================================ UEditor ============================== */}
            {/* <UEditor dispatch={dispatch}  setLoding={setLoding} isOk={isOk} setContent={setContent} isShowWx={isShowWx}/> */}
            <Space className={style.btn}>
                <Button onClick={() => { seve() }} type='primary' loading={add?.loading || edit?.loading || addWx?.loading}>保存素材</Button>
                {syncNews && !callback && <Button onClick={() => { seve(true) }} type='primary' loading={add?.loading || addWx?.loading || edit?.loading || syncId?.loading}>保存并群发</Button>}
                <Button onClick={() => { props.onClose(); initSelectWx() }} >取消</Button>
            </Space>
            <ActionModal visible={showActionModal} hideWx={saverNews} />
        </Spin>
    </div>
}

// ======================== UEditor =========================

// export default function Editor(props: Props) {
//     let { syncNews = true, isWx, isShowWx, isAll = true, callback = null } = props
//     const [showActionModal, setShowActionModal] = useState<boolean>(false)//选择公众号弹窗
//     const [id, setId] = useState<string>('')
//     const [loding, setLoding] = useState<boolean>(true)
//     const { getWeData } = useModel('useOperating.useMaterialContent')
//     const { dispatchNews } = useModel('useOperating.useNews', model => ({ dispatchNews: model.dispatch }))
//     const { dispatch, state } = useModel('useOperating.useMaterialDrawer')
//     const { dispatch: contentDispatch } = useModel('useOperating.useMaterialContent')
//     const { actionId, actionIdold, dataArr, actionData, ueditorRef, sort = 0 } = state
//     const { actionWX } = useModel('useOperating.useWxGroupList', model => ({ actionWX: model.state.actionWX }))
//     //
//     const { add, list, edit, syncId, addWx, state: { parentId, belongUser }, eidtWxlists } = useModel(isAll ? 'useOperating.useBdMedia' : 'useOperating.useBdMediaPup')
//     const { state: { selectWx }, initSelectWx } = useModel('useOperating.useWxGroupList')//公众号筛选
//     const [sid, setSid] = useState<number>(0)//已经切换设置过的ID
//     const [content, setContent] = useState<string>('<p></p>')//内容
//     const editorRef:any = useRef(null);

//     //保存
//     let seve = useCallback((isSaveNews?: boolean) => {
//         let content = ueditorRef?.getContent()
//         let menuId = actionIdold || actionId
//         dispatch({ type: 'pushData', params: { content } })
//         let isOk = dataArr.every((item: any) => {
//             let img = item?.thumbMediaUrl || item?.thumbUrl
//             if (!item.title) {
//                 message.error(`第${item.menuId}篇标题为空`)
//                 return false
//             }
//             if (!img) {
//                 message.error(`第${item.menuId}篇封面为空`)
//                 return false
//             }
//             if (item?.digest?.length > 54) {
//                 message.error(`第${item.menuId}摘要不能超过54个字`)
//                 return false
//             }
//             if (item.content === '<p></p>' || !item.content) {
//                 message.error(`第${item.menuId}篇内容为空`)
//                 return false
//             }
//             // if (!item.contentSourceUrl) {
//             //     message.error(`第${item.menuId}原文链接为空`)
//             //     return false
//             // }
//             return true
//         })
//         if (isOk) {
//             let news = dataArr.map((item: any) => {
//                 return { ...item, showCoverPic: false, thumbUrl: item?.thumbUrl || item?.thumbMediaUrl }
//             })
//             let data: any = {
//                 news,
//                 folder: false,
//                 fileType: 'news',
//                 parentId,
//                 belongUser,
//                 sort
//             }
//             if (callback) {//假如有回调那么不请求接口保存直接执行回调函数
//                 callback && callback(data)
//                 dispatch({ type: 'initData' })
//                 props.onClose()
//                 return
//             }
//             if (isWx) {//执行微信接口
//                 console.log('微信素材', props?.editId);
//                 if (props?.editId) {//编辑走新建本地素材再同步到微信
//                     add.run({ ...data, mpIds: selectWx }).then((res: any) => {
//                         if (res) {
//                             if (isSaveNews) {//走保存去群发逻辑
//                                 console.log('新建===》保存并群发', props)
//                                 syncId.run({ mpIds: [actionWX?.id], sysMediaId: res }).then((syncWxres: any) => {
//                                     if (syncWxres) {
//                                         dispatchNews({ type: 'theEdit', params: { theEdit: { content: { news }, mediaId: syncWxres, msgType: 'mpnews' } } })
//                                         history.push(`/operatePage/news/advanced?show=true`)
//                                         dispatch({ type: 'initData' })
//                                         localStorage.setItem('collapsed', '0')
//                                     }
//                                 })
//                             } else {
//                                 syncId.run({ mpIds: [actionWX?.id], sysMediaId: res }).then((syncWxres: any) => {
//                                     if (syncWxres) {
//                                         console.log('新建==》保存')
//                                         dispatch({ type: 'initData' })
//                                         props.onClose()
//                                         getWeData.refresh().then((res) => {//刷新页面
//                                             contentDispatch({ type: 'initData', params: { data: res.records } })
//                                         })
//                                         localStorage.setItem('collapsed', '0')
//                                     }
//                                 })
//                             }
//                         }
//                     })
//                 } else {//新建
//                     addWx.run({ mpId: actionWX?.id, mediaType: 'news', news }).then((res: any) => {
//                         console.log(res)
//                         if (res) {
//                             if (isSaveNews) {//走保存去群发逻辑
//                                 console.log('新建===》保存并群发', props)
//                                 setId(res)
//                                 setShowActionModal(true)
//                             } else {
//                                 dispatch({ type: 'initData' })
//                                 props.onClose()
//                                 getWeData.refresh().then((res) => {//刷新页面
//                                     contentDispatch({ type: 'initData', params: { data: res.records } })
//                                 })
//                                 localStorage.setItem('collapsed', '0')
//                             }
//                         }
//                     })
//                 }
//             } else {//执行本地
//                 if (props?.editId) {//表示编辑
//                     edit.run({ belongUser, fileType: 'news', folder: false, news, sysMediaId: props?.editId, sort }).then((res: any) => {
//                         if (isSaveNews) {//走保存去群发逻辑
//                             console.log('编辑==》保存并群发', news, dataArr)
//                             setId(props?.editId)
//                             setShowActionModal(true)
//                         } else {
//                             console.log('编辑===》保存')
//                             dispatch({ type: 'initData' })
//                             props.onClose()
//                             list.refresh()
//                             localStorage.setItem('collapsed', '0')
//                         }
//                     })
//                     eidtWxlists.run({ sysMediaId: props?.editId, mpIds: selectWx || [] }).then((res) => {
//                         console.log(res, 'eidtWxlists')
//                         initSelectWx()
//                     })
//                 } else {//新建
//                     add.run({ ...data, mpIds: selectWx }).then((res: any) => {
//                         if (res) {
//                             if (isSaveNews) {//走保存去群发逻辑
//                                 console.log('新建===》保存并群发', props)
//                                 setId(res)
//                                 setShowActionModal(true)
//                                 initSelectWx()
//                             } else {
//                                 console.log('新建==》保存')
//                                 dispatch({ type: 'initData' })
//                                 props.onClose()
//                                 list.refresh()
//                                 localStorage.setItem('collapsed', '0')
//                                 initSelectWx()
//                             }

//                         }
//                     })
//                 }
//             }

//         }
//     }, [dataArr, props?.editId, ueditorRef, actionWX, getWeData, isWx, parentId, belongUser, list, selectWx, sort])
//     //保存并群发选择公众号后回调
//     const saverNews = useCallback((cancel: boolean) => {
//         setShowActionModal(false)
//         if (!cancel) {//假如cancel为false就是保持并群发
//             let news = dataArr.map((item: any) => { return { ...item, showCoverPic: false, thumbUrl: item?.thumbUrl || item?.thumbMediaUrl } })
//             console.log(news, dataArr, 'dataArr,news')
//             if (actionWX) {
//                 if (isWx) {
//                     // dispatchNews({ type: 'theEdit', params: { theEdit: { content: { news }, mediaId: id, msgType: 'mpnews' } } })
//                     // history.push(`/operatePage/news/advanced?show=true`)
//                     // dispatch({ type: 'initData' })
//                     // localStorage.setItem('collapsed', '0')
//                 } else {//本地素材先同步再群发
//                     syncId.run({ mpIds: [actionWX?.id], sysMediaId: id }).then((syncWxres: any) => {
//                         if (syncWxres) {
//                             // dispatchNews({ type: 'theEdit', params: { theEdit: { content: { news }, mediaId: syncWxres, msgType: 'mpnews' } } })
//                             // history.push(`/operatePage/news/advanced?show=true`)
//                             // dispatch({ type: 'initData' })
//                             // localStorage.setItem('collapsed', '0')
//                         }
//                     })
//                 }
//             }
//             dispatchNews({ type: 'theEdit', params: { theEdit: { content: { news }, mediaId: id, msgType: 'mpnews' } } })
//             history.push(`/operatePage/news/advanced?show=true`)
//             dispatch({ type: 'initData' })
//             localStorage.setItem('collapsed', '0')
//         }
//     }, [actionWX, isWx, id, syncId, dataArr])
//     // //切换文章
//     useEffect(() => {
//         if (!ueditorRef?.body) {
//             return
//         }
//         if (sid !== actionId) {
//             setSid(actionId)
//             let content = dataArr?.filter((item: { menuId: any }) => item.menuId === actionId)[0]?.content || '<p></p>'
//             ueditorRef?.setContent(content, false)
//         }
//     }, [actionId, dataArr, ueditorRef?.body, sid])
//     // 内容变化设置
//     useEffect(() => {
//         if (ueditorRef?.body) {
//             dispatch({ type: 'pushData', params: { menuId: actionId, content: content || '<p></p>' } })
//         }

//     }, [ueditorRef?.body, content, actionId])
//     //编辑回填
//     const isOk = useCallback((ueditor) => {
//         if (actionData) {
//             let dataArr = actionData.dataArr?.map((item: any, index: number) => {
//                 item.menuId = index + 1
//                 return item
//             })
//             dispatch({ type: 'initData', params: { data: { ...actionData, dataArr, actionId: 1 } } })
//             ueditor?.setContent(dataArr[0].content, false)
//         }
//     }, [props?.editData, ueditorRef?.setContent])
//     return <div >
//         <h3 style={{ height: 43, lineHeight: '43px', textAlign: 'center' }}>素材编辑</h3>
//         <Spin spinning={loding} tip='初始化中请稍等。。。'>
//             <Title />
//             {/* ================================ TEditor ============================== */}

//             {/* <TEditor dispatch={dispatch}  setLoding={setLoding} isOk={isOk} content={content}/> */}

//              {/* ================================ UEditor ============================== */}
//             <UEditor dispatch={dispatch}  setLoding={setLoding} isOk={isOk} setContent={setContent} isShowWx={isShowWx}/>
//             <Space className={style.btn}>
//                 <Button onClick={() => { seve() }} type='primary' loading={add?.loading || edit?.loading || addWx?.loading}>保存素材</Button>
//                 {syncNews && !callback && <Button onClick={() => { seve(true) }} type='primary' loading={add?.loading || addWx?.loading || edit?.loading || syncId?.loading}>保存并群发</Button>}
//                 <Button onClick={() => { props.onClose(); initSelectWx() }} >取消</Button>
//             </Space>
//             <ActionModal visible={showActionModal} hideWx={saverNews} />
//         </Spin>
//     </div>
// }

