import useCopy from "@/Hook/useCopy"
import React, { useCallback, useEffect, useState } from "react"
import { Button, Col, Image, message, Pagination, Popconfirm, Row, Space, Spin } from 'antd'
import style from './index.less'
import { DeleteOutlined, EditOutlined, PlusCircleOutlined, SyncOutlined } from "@ant-design/icons"
import Synthetic from "../MaterialModal/synthetic"
import FileModal from './components/fileModal'
import { useModel } from "umi"
import ImgModal from "./components/imgModal"
import MsgWxGraphicListModal from '@/components/MaterialModal/msgWxGraphicListModal'
import filePng from '../../../public/file.png'
import Updata from "../MaterialModal/updata"
import WxSelect from "../WxSelect"
import TreeBox from "./components/tree"
import SortModal from "./components/fileModal/sortModal"
import PreviewLocalModal from "@/components/MaterialModal/previewLocalModal"

interface News {
    id: number,
    sysMediaId: number,
    sortIndex: number,
    title: string,
    thumbUrl: string,
    author: string,
    digest: string,
    showCoverPic: boolean,
    content: string,//内容只在调取详情时获取
    contentSourceUrl: string,//文章地址
    needOpenComment: boolean,
    onlyFansCanComment: boolean
}
interface Item {
    id: number,
    folder: boolean,//是否是文件夹
    fileType: 'video' | 'image' | 'news' | 'voice' | 'knews',//类型
    number: string,//编号
    title: string,//名称
    url: string,//链接
    belongType: string,//所属类型
    createTime: string,//创建时间
    description: string,//k图文描述
    news?: News[]//图文内容
    knewsThumbUrl: string, // 图片链接
    knewsThumbId: number,//本地图片ID
    knewsThumbInfo: any,//k客服详情
    videoTitle: string,//视频标题
}
interface Props {
    showDrawer?: (props?: any) => void,//图文素材弹窗事件
    showSync?: (props?: any) => void,//同步弹窗事件
    isAll?: boolean,//是否允许全选默认开启
    height?: any,//当使用为弹窗组件时设置高度以免太高
    noFile?: boolean,//是否禁止选择文件夹
    isBd?: boolean,//是否强制使用本地数据
}
function FlieBox(props: Props) {

    const { showDrawer, showSync, isAll = true, height, noFile = false, isBd } = props
    const { addData } = useModel('useOperating.useSynthetic')
    const { dispatch } = useModel('useOperating.useMaterialDrawer')
    const { state, set, dels, list, get, onFile, allFile, delPupOn, delPupOff, changeClickFile, editFile, fileClick, treeClick, pathClick, getList, knewsOk, edit_media_folder, get_folder_tree } = useModel(isAll || isBd ? 'useOperating.useBdMedia' : 'useOperating.useBdMediaPup')
    const { fileVisible, belongUser, selectFile, delPupId, xy, rightClickPup, path, publicPath, parentId, imgVisrible, fileType, knewsVisrible, knewsdefaultData, sortVisible } = state
    const { copy } = useCopy()
    const [updataVisible, setUpdataVisible] = useState<boolean>(false)
    const fileImg = require('../../../public/file.png')
    const { dispatch: dDispatch, getWxlists, initSelectWx } = useModel('useOperating.useWxGroupList')//公众号筛选
    const [moveId, setMoveId] = useState<any>('')//移动的素材ID
    const [treeEl, item, folderId, setActionId, setHoverId] = TreeBox({ data: get_folder_tree.data, belongUser })
    const [previewShow, setPreviewShow] = useState<boolean>(false)  // 预览弹窗控制
    const [previewId, setPreviewId] = useState<number>() // 要预览的ID

    /**复制编号 */
    const copyId = useCallback((e: React.MouseEvent<HTMLSpanElement, MouseEvent>, value: string) => {
        e.stopPropagation()//阻止冒泡传递到文件夹被点击事件
        copy(value)
    }, [])
    /**全局右键菜单 */
    const Menu = useCallback((props: { isItem?: boolean }) => {
        if (props.isItem && isAll) {
            return <ul style={{ top: xy?.y, left: xy?.x }} className={style.menu} >
                {
                    isAll && <li onClick={allFile}>全选/反选</li>
                }
                <li onClick={(e) => { delPupOn(rightClickPup.id); onFile(e, rightClickPup, isAll, true) }}> 删除</li>
                {
                    !rightClickPup?.folder && <li onClick={() => {
                        setPreviewShow(true)
                        setPreviewId(rightClickPup?.id)
                    }}>预览</li>
                }
                {
                    !rightClickPup?.folder && <li onClick={() => {
                        showSync && showSync({ sysMediaId: rightClickPup?.id })
                    }}>同步</li>
                }
                <li onClick={() => {
                    getWxlists.run(rightClickPup?.id).then((res: any) => {//获取当前素材关联的公众号列表
                        if (res) {
                            dDispatch({ type: 'selectWx', params: { selectWx: res?.map((item: any) => item.id) } })
                        }
                    })
                    switch (fileType) {
                        case 'news':
                            if (rightClickPup?.folder) {//是文件夹
                                editFile()
                            } else {
                                get.run(rightClickPup?.id).then((res: any) => {//请求详情接口获取详情内容
                                    if (res) {
                                        dispatch({ type: 'actionData', params: { data: { dataArr: res?.news, actionId: 1, sort: res?.sort } } })//设置编辑器的内容
                                        showDrawer && showDrawer({ isEdit: true, editId: rightClickPup?.id })//开启新建素材弹窗
                                        localStorage.setItem('collapsed', '1')//左侧菜单缩进
                                    }
                                })
                            }
                            break;
                        case 'knews':
                            if (rightClickPup?.folder) {//是文件夹
                                editFile()
                            } else {
                                set({ knewsVisrible: true })
                            }
                            break;
                        default://编辑非图文素材
                            editFile()
                    }
                }}>编辑</li>
                <li onClick={() => { set({ actionItem: rightClickPup, sortVisible: true }) }}>编辑排序</li>
                <li onClick={() => { set({ fileVisible: true }) }}>新建文件夹</li>
                <li onClick={() => {
                    switch (fileType) {
                        case 'news':
                            showDrawer && showDrawer()
                            break;
                        case 'knews':
                            set({ knewsVisrible: true, knewsdefaultData: null })
                            break;
                        default:
                            set({ imgVisrible: true })
                    }
                }}>新建素材</li>
                {
                    (fileType !== 'knews' && fileType !== 'news') && <li onClick={() => { setUpdataVisible(true) }}>批量新增素材</li>
                }
                {
                    isAll && <li onClick={dels}>删除选中文件</li>
                }
            </ul>
        }
        return <ul style={{ top: xy?.y, left: xy?.x }} className={style.menu}>
            {
                isAll && <li onClick={allFile}>全选/反选</li>
            }
            {

            }
            {//防止K图文无限嵌套创建判断
                (isAll !== false || fileType !== 'knews') ? <li onClick={() => { set({ fileVisible: true }) }}>新建文件夹</li> : <li>此处无法新建操作</li>
            }
            {
                (isAll !== false || fileType !== 'knews') && <li onClick={() => {
                    switch (fileType) {
                        case 'news':
                            showDrawer && showDrawer()
                            break;
                        case 'knews':
                            set({ knewsVisrible: true, knewsdefaultData: null })
                            break;
                        default:
                            set({ imgVisrible: true })
                    }
                }}>新建素材</li>
            }
            {
                (fileType !== 'knews' && fileType !== 'news') && <li onClick={() => { setUpdataVisible(true) }}>批量新增素材</li>
            }
            {
                isAll && <li onClick={dels}>删除选中文件</li>
            }
        </ul>
    }, [xy, rightClickPup, allFile, fileType, showDrawer, previewShow, previewId])
    /**鼠标右键 */
    const rightMenu = useCallback((e: any, isItem?: any) => {
        e.stopPropagation()
        e.preventDefault()
        let x = e.clientX;
        let y = e.clientY;
        set({ xy: { x, y } })
        if (isItem) {
            set({ rightClickPup: isItem })
            if (!isItem?.folder && isItem?.fileType === 'knews') {
                set({
                    knewsdefaultData: {//客服消息编辑回填弹窗中的内容预先存放
                        newsList: [
                            {
                                title: isItem?.title,
                                knewsThumbUrl: isItem?.knewsThumbUrl,
                                knewsLink: isItem?.knewsLink,
                                description: isItem?.description,
                                knewsThumbInfo: isItem?.knewsThumbInfo,
                                knewsThumbId: isItem?.knewsThumbId,
                                sort: isItem?.sort || 0
                            }
                        ]
                    }
                })
            }
        } else {
            set({ rightClickPup: { id: 'all' } })
        }
        return false;
    }, [])
    /**左键点击页面隐藏菜单 */
    useEffect(() => {
        function fnc(e: any) {
            set({ rightClickPup: { id: '' } })
        }
        document.addEventListener('click', fnc)
        return () => {
            document.removeEventListener('click', fnc)
        }
    }, [])
    /**合成器添加内容 */
    const addNews = useCallback((news: any) => {
        console.log(news)
        addData(news)
    }, [])
    // /**切换个人|公共|父目录ID变化清空选中的文件*/
    useEffect(() => {
        set({ selectFile: [] })
        if (belongUser == '1' && path) {//处理切换个人|公共时保留路径层级的请求
            set({ parentId: path[path?.length - 1]?.id || null })
        }
        if (belongUser == '0' && publicPath) {
            set({ parentId: publicPath[publicPath?.length - 1]?.id || null })
        }
    }, [belongUser, parentId, path?.length, publicPath?.length])
    /**卸载组件处理 */
    useEffect(() => {
        return () => {
            set({ parentId: null })
        }
    }, [])
    /**获取目录树*/
    useEffect(() => {
        // if (isBd) {
        get_folder_tree.run({ belongUser, fileType })
        // }
    }, [isAll, isBd, fileType, belongUser])
    // 点击目录树进入对应目录
    useEffect(() => {
        if (item) {
            let { icon, children, ...arg } = item
            treeClick(arg)
        }
    }, [item])
    // 拖动事件配置
    const moveConfig = useCallback((item) => {
        return {
            draggable: true,
            onDragStart: (ev: any) => {
                let img = document.createElement('img')
                img.src = fileImg;
                ev.dataTransfer.setDragImage(img, 0, 0)
                setMoveId(item.id)
            },
            onDragEnd: (e: any) => {
                if (folderId !== '' && moveId !== '') {
                    edit_media_folder.run({ sysMediaId: moveId, folderId }).then(res => {
                        message.success('操作成功')
                        list.refresh()
                    })
                }
                setActionId('')
                setHoverId('')
                setMoveId('')
            },
        }
    }, [folderId, moveId])
    return <div style={{ display: 'flex', flexFlow: 'row' }}>
        {
            get_folder_tree?.data?.length > 0 && <div style={{ flexShrink: 0 }}>
                {treeEl}
            </div>
        }
        <div style={{ flexShrink: 1 }}>
            <div className={style.files} onContextMenu={rightMenu} style={height ? { height } : {}}>
                {/* 关联公众号筛选 */}
                <div className={style.wxSelect}>
                    <WxSelect mode={1} isAll={isAll} />
                </div>
                {/*合成器 refD?.current?.showDrawer() */}
                {fileType === 'news' && isAll && <Synthetic show={() => { showDrawer && showDrawer() }} />}
                {/* 层级路径 */}
                <div className={style.path} >
                    {//存在渲染个人本地路径不存在执行公共本地
                        belongUser == '1' && path?.map((item: { title: string }, index: number) => {
                            return <span key={index} onClick={() => { pathClick({ ...item, index }) }} >
                                <span className={path?.length !== index + 1 ? style.path_color : ''}>{item?.title}</span>
                                {path?.length !== index + 1 && <span className={style.rt} >{'>'}</span>}
                            </span>
                        })
                    }
                    {
                        belongUser == '0' && publicPath?.map((item: { title: string }, index: number) => {
                            return <span key={index} onClick={() => { pathClick({ ...item, index }) }} >
                                <span className={publicPath?.length !== index + 1 ? style.path_color : ''}>{item?.title}</span>
                                {publicPath?.length !== index + 1 && <span className={style.rt} >{'>'}</span>}
                            </span>
                        })
                    }
                </div>
                {/* 内容 */}
                <div className={(fileType === 'news' || fileType === 'knews') ? style.file_news_content : style.file_content} >
                    {
                        list?.data?.records?.map((item: Item) => {
                            if (item.folder) {
                                {/* 文件夹模板 */ }
                                return <Popconfirm
                                    title="确定要删除吗？"
                                    onConfirm={() => { dels(item) }}
                                    okText="是"
                                    cancelText="否"
                                    onCancel={delPupOff}
                                    visible={delPupId === item.id}
                                    key={item.id}
                                >
                                    <Spin tip='正在请求素材详情，请耐心等待...' spinning={get?.loading}>
                                        <div
                                            className={`${style.flex_box} ${selectFile?.some((id: number) => id === item.id) ? style.action : ''}`}
                                            onContextMenu={(e) => { rightMenu(e, item) }}
                                            onClick={(e) => { changeClickFile(e, item, isAll, noFile) }}
                                            onDragStart={(e: any) => {
                                                e.preventDefault()
                                            }}
                                        >
                                            <span className={`${style.select}`} onClick={(e) => { changeClickFile(e, item, isAll, noFile) }}>
                                                <span role="img" aria-label="check" style={{ color: '#fff' }}><svg viewBox="64 64 896 896" focusable="false" data-icon="check" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M912 190h-69.9c-9.8 0-19.1 4.5-25.1 12.2L404.7 724.5 207 474a32 32 0 00-25.1-12.2H112c-6.7 0-10.4 7.7-6.3 12.9l273.9 347c12.8 16.2 37.4 16.2 50.3 0l488.4-618.9c4.1-5.1.4-12.8-6.3-12.8z"></path></svg></span>
                                            </span>
                                            <img src={fileImg}
                                                className={style.flex_box_img}
                                                onClick={(e: any) => { e.stopPropagation(); fileClick(item) }}
                                                onDragOver={(ev) => {
                                                    ev.preventDefault()
                                                }}
                                                onDrop={() => {
                                                    if (item.id !== folderId) {
                                                        setActionId(item.id)
                                                    }
                                                }}
                                            />
                                            <span className={style.flex_box_name} >{item?.title}</span>
                                            <span className={style.flex_box_id} onClick={(e) => { copyId(e, item?.number) }} >{item?.number}</span>
                                        </div>
                                    </Spin>
                                </Popconfirm>
                            } else if (item.fileType === 'news') {
                                {/* 图文模板 */ }
                                return <Popconfirm
                                    title="确定要删除吗？"
                                    onConfirm={() => { dels(item.id) }}
                                    okText="是"
                                    cancelText="否"
                                    onCancel={delPupOff}
                                    visible={delPupId === item.id}
                                    key={item.id}
                                >
                                    <Spin tip='正在请求素材详情，请耐心等待...' spinning={get?.loading}>
                                        <div
                                            className={`${style.news_box} ${selectFile?.some((id: number) => id === item.id) ? style.action : ''}`}
                                            onContextMenu={(e) => { rightMenu(e, item) }}
                                            onClick={(e) => { changeClickFile(e, item, isAll) }}
                                            {...moveConfig(item)}
                                        >
                                            <span className={`${style.select}`} onClick={(e) => { changeClickFile(e, item, isAll) }}>
                                                <span role="img" aria-label="check" style={{ color: '#fff' }}><svg viewBox="64 64 896 896" focusable="false" data-icon="check" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M912 190h-69.9c-9.8 0-19.1 4.5-25.1 12.2L404.7 724.5 207 474a32 32 0 00-25.1-12.2H112c-6.7 0-10.4 7.7-6.3 12.9l273.9 347c12.8 16.2 37.4 16.2 50.3 0l488.4-618.9c4.1-5.1.4-12.8-6.3-12.8z"></path></svg></span>
                                            </span>
                                            {
                                                item?.news?.map((news: News) => {
                                                    return <div key={news?.id}>
                                                        <Image src={news?.thumbUrl} onClick={(e) => { e.stopPropagation() }} />
                                                        <span className={style.news_box_font}>{news?.title}</span>
                                                        <p className={style.add} onClick={(e) => { e.stopPropagation(); addNews(news) }}><PlusCircleOutlined /></p>
                                                    </div>
                                                })
                                            }
                                            <span className={style.flex_box_id} onClick={(e) => { copyId(e, item?.number) }} >{item?.number}</span>
                                            <span>
                                                <Space>
                                                    <Button
                                                        type='text'
                                                        size='small'
                                                        onClick={(e) => {
                                                            e.stopPropagation();
                                                            getWxlists.run(item?.id).then((res: any) => {//获取当前素材关联的公众号列表
                                                                if (res) {
                                                                    dDispatch({ type: 'selectWx', params: { selectWx: res?.map((item: any) => item.id) } })
                                                                }
                                                            })
                                                            if (item?.folder) {//是文件夹
                                                                editFile()
                                                            } else {
                                                                get.run(item?.id).then((res: any) => {//请求详情接口获取详情内容
                                                                    if (res) {
                                                                        let news = res?.news?.map((item: any, index: number) => {
                                                                            return { ...item, menuId: index + 1 }
                                                                        })
                                                                        dispatch({ type: 'actionData', params: { data: { dataArr: news, actionId: 1, sort: res?.sort } } })//设置编辑器的内容
                                                                        showDrawer && showDrawer({ isEdit: true, editId: item?.id })//开启新建素材弹窗
                                                                        localStorage.setItem('collapsed', '1')//左侧菜单缩进
                                                                    }
                                                                })
                                                            }
                                                        }}
                                                    >
                                                        <EditOutlined />
                                                    </Button>
                                                    <Button
                                                        type='text'
                                                        size='small'
                                                        onClick={(e) => {
                                                            e.stopPropagation();
                                                            showSync && showSync({ sysMediaId: item?.id })
                                                        }}
                                                    >
                                                        <SyncOutlined />
                                                    </Button>
                                                    <Button
                                                        type='text'
                                                        size='small'
                                                        onClick={(e) => {
                                                            e.stopPropagation();
                                                            delPupOn(item.id); onFile(e, item, isAll, true)
                                                        }}
                                                    >
                                                        <DeleteOutlined />
                                                    </Button>
                                                </Space>
                                            </span>
                                        </div>
                                    </Spin>
                                </Popconfirm>
                            } if (item.fileType === 'knews') {
                                {/* K图文模板 */ }
                                return <Popconfirm
                                    title="确定要删除吗？"
                                    onConfirm={() => { dels(item.id) }}
                                    okText="是"
                                    cancelText="否"
                                    onCancel={delPupOff}
                                    visible={delPupId === item.id}
                                    key={item.id}
                                >
                                    <Spin tip='正在请求素材详情，请耐心等待...' spinning={get?.loading}>
                                        <div
                                            className={`${style.knews_box} ${selectFile?.some((id: number) => id === item.id) ? style.action : ''}`}
                                            onContextMenu={(e) => { rightMenu(e, item) }}
                                            onClick={(e) => { changeClickFile(e, item, isAll) }}
                                            {...moveConfig(item)}
                                        >
                                            <span className={`${style.select}`} onClick={(e) => { changeClickFile(e, item, isAll) }}>
                                                <span role="img" aria-label="check" style={{ color: '#fff' }}><svg viewBox="64 64 896 896" focusable="false" data-icon="check" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M912 190h-69.9c-9.8 0-19.1 4.5-25.1 12.2L404.7 724.5 207 474a32 32 0 00-25.1-12.2H112c-6.7 0-10.4 7.7-6.3 12.9l273.9 347c12.8 16.2 37.4 16.2 50.3 0l488.4-618.9c4.1-5.1.4-12.8-6.3-12.8z"></path></svg></span>
                                            </span>
                                            <div >
                                                <div>
                                                    <span className={style.news_box_font}>{item?.title}</span>
                                                    <p>{item?.description}</p>
                                                </div>
                                                <Image src={item?.knewsThumbId ? item?.knewsThumbInfo?.folder ? filePng : item?.knewsThumbInfo?.url : item?.knewsThumbUrl} onClick={(e) => { e.stopPropagation() }} />
                                            </div>
                                            <span className={style.flex_box_id} onClick={(e) => { copyId(e, item?.number) }} >{item?.number}</span>
                                        </div>
                                    </Spin>
                                </Popconfirm>
                            } else {
                                {/* 图片模板 ,视频模板,音频模板*/ }
                                let El = item.fileType === 'image' ?
                                    <Image src={item.url} onClick={(e) => { e.stopPropagation() }}
                                    /> :
                                    item.fileType === 'video' ?
                                        <video src={item.url} style={{ width: 130, height: 100 }} controls />
                                        :
                                        <audio src={item.url} controls style={{ width: 150 }} />
                                return <Popconfirm
                                    title="确定要删除吗？"
                                    onConfirm={() => { dels(item.id) }}
                                    okText="是"
                                    cancelText="否"
                                    onCancel={delPupOff}
                                    visible={delPupId === item.id}
                                    key={item.id}
                                >
                                    <Spin tip='正在请求素材详情，请耐心等待...' spinning={get?.loading}>
                                        <div
                                            className={`${style.image_box} ${selectFile?.some((id: number) => id === item.id) ? style.action : ''}`}
                                            onContextMenu={(e) => { rightMenu(e, item) }}
                                            onClick={(e) => { changeClickFile(e, item, isAll) }}
                                            {...moveConfig(item)}
                                        >
                                            <span className={`${style.select}`} onClick={(e) => { changeClickFile(e, item, isAll) }}>
                                                <span role="img" aria-label="check" style={{ color: '#fff' }}><svg viewBox="64 64 896 896" focusable="false" data-icon="check" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M912 190h-69.9c-9.8 0-19.1 4.5-25.1 12.2L404.7 724.5 207 474a32 32 0 00-25.1-12.2H112c-6.7 0-10.4 7.7-6.3 12.9l273.9 347c12.8 16.2 37.4 16.2 50.3 0l488.4-618.9c4.1-5.1.4-12.8-6.3-12.8z"></path></svg></span>
                                            </span>
                                            {El}
                                            <span className={style.flex_box_name} onClick={(e) => { copyId(e, item?.url) }}>{item?.videoTitle || item?.title}</span>
                                            <span className={style.flex_box_id} onClick={(e) => { copyId(e, item?.number) }} >{item?.number}</span>
                                        </div>
                                    </Spin>
                                </Popconfirm>
                            }
                            return null
                        })
                    }
                </div>
                {/* 鼠标右键菜单 */}
                {rightClickPup.id ? rightClickPup.id === 'all' ? <Menu /> : <Menu isItem /> : null}
                {/* 新建文件弹窗 */}
                {fileVisible && <FileModal isAll={isAll} />}
                {/* 编辑排序 */}
                {sortVisible && <SortModal isAll={isAll} />}
                {/* 新建非图文 */}
                {imgVisrible && <ImgModal isAll={isAll} />}
                {/* 批量新建素材 */}
                {updataVisible && <Updata mediaType={fileType === 'image' ? '1' : fileType === 'video' ? '3' : '2'} callBcak={setUpdataVisible} type={1} isAll={isAll} />}
                {/* 新建客服消息模板 */}
                {
                    knewsVisrible && <MsgWxGraphicListModal
                        title={'K-图文'}
                        visible={knewsVisrible || false}
                        onCancel={() => {
                            // dispatchMate({ type: 'initData', params: { data: { dataArr: [{ menuId: 1 }] } } }) //设置成默认
                            set({ knewsVisrible: false })
                            initSelectWx()
                            return
                        }}
                        isKnews={true}
                        onOK={(props) => { knewsOk(props) }}
                        defaultData={knewsdefaultData}
                        tooltipTxt='只支持单图文'
                        historyType={1}
                        ImportBtShow={1}
                        isProhibitMs={true}
                        msgType={1}
                    />
                }
            </div>
            {
                list?.data?.records?.length > 0 && <div className={style.pagination}>
                    {/* 分页 */}
                    <Pagination
                        showSizeChanger
                        onChange={(page: number, pageSize?: number) => {
                            getList({ pageSize, pageNum: page })
                        }}
                        onShowSizeChange={(current: number, size: number) => {
                            getList({ pageSize: size, pageNum: current })
                        }}
                        current={list?.data?.current}
                        defaultPageSize={20}
                        total={list?.data?.total}
                    />
                </div>
            }
        </div>

        {previewShow && <PreviewLocalModal visible={previewShow} onClose={() => setPreviewShow(false)} previewId={previewId} />}
    </div>
}
export default React.memo(FlieBox)