import { inject, observer } from 'mobx-react';
import React, { useCallback, useEffect, useState } from 'react';
import style from './index.less'
import { App, Button, Card, Empty, Flex, Form, Input, Popconfirm, Select, Space, Spin, Table, Tabs } from 'antd';
import MassSending from './components/massSending';
import { useAjax } from '@/Hook/useAjax';
import { welcomeMsgJobTypeApi } from '@/pages/weComTask/API/weMaterial/weMaterial';
import SelectCorpUser from '../../corpUserManage/selectCorpUser';
import { SearchOutlined, PlusOutlined, RedoOutlined, SaveOutlined, CheckOutlined } from '@ant-design/icons';
import { getGroupData, getUserInDataData, restoreGroupData, restoreUserInheritData } from './const';
import { friendsColumns, highMassSendingColumns, massSendingColumns, userInheritColumns, welcomeColumns } from './tableConfig';
import SubmitModal from './submitModal';
import { addTaskApi, getCreateDetailsApi, updateTaskApi } from '@/pages/weComTask/API/businessPlan/create';
import { useNavigate } from 'react-router-dom';
import SelectExternalAccount from '@/pages/weComTask/components/selectExternalAccount';
import Welcome from './components/welcome';
import UserInherit from './components/userInherit';
import { toJS } from 'mobx';
import SelectCwTag from '@/pages/weComTask/components/selectCwTag';
import SelectCorpUserGroup from '../../corpUserManage/selectCorpUserGroup';
import { getBindMpListApi } from '@/pages/weComTask/API/corpUserAssign';

export const DispatchTaskCreate = React.createContext<TASK_CREATE.DispatchTaskCreate | null>(null);
/**
 * 任务创建
 * @param props 
 * @returns 
 */
const Create: React.FC<{ weComTaskStore: { data: { bookList: TASK_CREATE.BookListProps[], bookPlatForm: TASK_CREATE.BookPlatFormProps[] } } }> = ({ weComTaskStore }) => {

    /***********************************************/
    const navigate = useNavigate();
    const { bookList, bookPlatForm } = toJS(weComTaskStore.data)
    const [settings, setSettings] = useState<TASK_CREATE.SettingsProps>();
    const [projectId, setProjectId] = useState<number>()
    const [isEditSc, setIsEditSc] = useState<boolean>(false) // 是否编辑素材
    const { message, modal } = App.useApp()
    const [msgJobTypeList, setMsgJobTypeList] = useState<{ value: string, label: string }[]>([])
    const [previewData, setPreviewData] = useState<TASK_CREATE.previewDataProps>({})
    const [previewDataOld, setPreviewDataOld] = useState<TASK_CREATE.previewDataProps>({})
    const [subVisible, setSubVisible] = useState<boolean>(false) // 选择设置名称弹窗控制
    const [eaVisible, setEaVisible] = useState<boolean>(false)
    const [qwVisible, setQwVisible] = useState<boolean>(false)
    const [mpList, setMplist] = useState<{ label: string, value: number }[]>([])
    const [previewContent, setPreviewContent] = useState<{ groupMsgContent?: any[], welcomeMsgContent?: any[], externalUserTransferContent?: any[] }>({})

    const welcomeMsgJobType = useAjax(() => welcomeMsgJobTypeApi())//获取欢迎语类型

    const addTask = useAjax((params) => addTaskApi(params))
    const updateTask = useAjax((params) => updateTaskApi(params))
    const getCreateDetails = useAjax((params) => getCreateDetailsApi(params))
    const getBindMpList = useAjax(() => getBindMpListApi())
    /***********************************************/
    console.log('settings--->', settings, previewContent)

    useEffect(() => {
        const project = sessionStorage.getItem('OFFICIALTASKID')
        if (project) {
            const { id, isCopy, isEditSc } = JSON.parse(project)
            setIsEditSc(isEditSc)
            if (!isCopy) {
                setProjectId(id)
            }
            getCreateDetails.run(id).then(res => {
                sessionStorage.removeItem('OFFICIALTASKID')
                if (res?.data) {
                    const { corpUsers, bizType, platform, templateProductId, welcomeMsgTemplateDTO, groupSendTaskAddDTO, externalUserTransferTasksDTO } = res.data
                    let newSettings: TASK_CREATE.SettingsProps = {
                        bizType,
                        platform: Number(platform) as any,
                        templateProductId,
                        corpUserGroups: corpUsers.map(item => {
                            return {
                                corpUsers: item.corpUserList.map(({ corpUserId, name, corpId, mpAccountId, mpAccountInfo, id }) => {
                                    return { id: id || (corpId + '_' + corpUserId), corpUserId, name, corpName: item.corpName, corpId, mpAccountId, mpAccountName: mpAccountInfo?.name }
                                })
                            }
                        }),
                        welcomeMsgTemplateDTO
                    }
                    if (groupSendTaskAddDTO && Object.keys(groupSendTaskAddDTO).length > 0) {
                        const data = restoreGroupData(groupSendTaskAddDTO)
                        newSettings = { ...newSettings, ...data }
                    }
                    if (externalUserTransferTasksDTO && Object.keys(externalUserTransferTasksDTO)?.length > 0) {
                        const data = restoreUserInheritData(externalUserTransferTasksDTO)
                        newSettings.userInherit = data
                    }
                    setSettings(newSettings)

                    // 历史数据回填

                    const welcomeMsgContent: any[] = []
                    const groupMsgContent: any[] = []
                    corpUsers.forEach((c, c_index) => {
                        if (c?.welcomeMsgContent?.length > 0) {
                            welcomeMsgContent[c_index] = c?.welcomeMsgContent?.map(item => ({
                                linkUrl: item?.linkUrl,
                                miniprogramAppid: item?.miniprogramAppid,
                                miniprogramPage: item?.miniprogramPage
                            }))
                        }
                        if (c?.groupMsgContent?.length > 0) {
                            groupMsgContent[c_index] = c?.groupMsgContent?.map(item => {
                                return item?.map(i2 => i2?.map(item => ({
                                    linkUrl: item?.linkUrl,
                                    miniprogramAppid: item?.miniprogramAppid,
                                    miniprogramPage: item?.miniprogramPage
                                })))
                            })
                        }
                    })
                    const newPreviewContent: { groupMsgContent?: any[], welcomeMsgContent?: any[], externalUserTransferContent?: any[] } = {
                        welcomeMsgContent,
                        groupMsgContent
                    }
                    setPreviewContent(newPreviewContent)
                }
            })
        } else {
            const task = localStorage.getItem('TASK_CORP_CREATE')
            if (task) {
                setSettings(JSON.parse(task).settings)
            }
        }
    }, [])

    useEffect(() => {
        welcomeMsgJobType.run().then(res => {
            if (res?.data) {
                setMsgJobTypeList(Object.keys(res.data).map(key => ({ value: key, label: res.data[key] })))
            }
        })
        getBindMpList.run().then(res => {
            setMplist(res?.data?.map((item: any) => ({ label: item.name, value: item.id })))
        })
    }, [])

    // 预览
    const preview = () => {
        const newPreviewData: TASK_CREATE.previewDataProps = {}
        if (!settings?.corpUserGroups || settings?.corpUserGroups?.length === 0) {
            message.error('请先选择客服号')
            return
        }

        if (!settings?.bizType) {
            message.error('请选择业务类型')
            return
        }
        if (!settings?.platform) {
            message.error('请选择书城')
            return
        }

        // 欢迎语
        if (settings?.welcomeMsgTemplateDTO && Object.keys(settings?.welcomeMsgTemplateDTO).length) {
            const welcome = []
            if (!settings?.corpUserGroups?.every((item, i) => {
                return settings?.welcomeMsgTemplateDTO?.mediaContentList?.every((mediaItem, index, row) => {
                    const linkData = []
                    const miniProgramData = []
                    const contentReactNode = mediaItem.map(item => {
                        switch (item.mediaType) {
                            case 'link':
                                linkData.push(item)
                                return `<span style="color: red">链接</span>`
                            case 'miniprogram':
                                miniProgramData.push(item)
                                return `<span style="color: red">小程序</span>`
                            case 'file':
                                return `<span>文件</span>`
                            case 'video':
                                return `<span>视频</span>`
                            case 'image':
                                return `<span>图片</span>`
                            case 'text':
                                return `<span>文本</span>`
                            default:
                                return `<span style="color: red">请联系管理员</span>`
                        }
                    })
                    welcome.push({
                        ...settings?.welcomeMsgTemplateDTO,
                        sendData: mediaItem,
                        contentReactNode,
                        corpUsergroupIndex: i,
                        corpUserGroupName: `客服组${i + 1}`,
                        corpUserList: item.corpUsers,
                        linkData,
                        miniProgramData,
                        contentIndex: index + 1,
                        bizType: settings?.bizType,
                        channel: settings?.channel,
                        platform: settings?.platform,
                        templateProductId: settings?.templateProductId,
                        id: i * row.length + (index + 1),
                        rowSpan: index === 0 ? row.length : 0,
                        mpAccountId: item.corpUsers?.[0]?.mpAccountId,
                        mpAccountName: item.corpUsers?.[0]?.mpAccountName,
                        corpUserStrList: item.corpUsers?.map(item => item.corpId + '_' + item.corpUserId)
                    })
                    return true
                })
            })) {
                return
            }
            console.log('welcome--->', welcome)
            newPreviewData.welcome = welcome
        }

        // 群发
        if ((settings?.massSendingContent && Object.keys(settings?.massSendingContent).length) && (settings?.massSendingStrategy && Object.keys(settings?.massSendingStrategy).length)) {
            const massSendingData = getGroupData(settings)
            const massSending = []
            if (!settings?.corpUserGroups?.every((item, i) => {

                let strategyIndex = 0

                return massSendingData.every((dataItem, li, row) => {

                    const mediaItem = JSON.parse(JSON.stringify(dataItem?.content?.attachmentList || []))
                    if (dataItem?.content?.text?.content) {
                        mediaItem.push({
                            msgType: 'TASK_CONTENT_TEXT',
                            textContent: dataItem?.content?.text?.content
                        })
                    }
                    const linkData = []
                    const miniProgramData = []
                    const contentReactNode = mediaItem.map(item => {
                        switch (item.msgType) {
                            case 'TASK_CONTENT_LINK':
                                linkData.push(item)
                                return `<span style="color: red">链接</span>`
                            case 'TASK_STATUS_MINIPROGRAM':
                                miniProgramData.push(item)
                                return `<span style="color: red">小程序</span>`
                            case 'TASK_STATUS_FILE':
                                return `<span>文件</span>`
                            case 'TASK_STATUS_VIDEO':
                                return `<span>视频</span>`
                            case 'TASK_CONTENT_IMAGE':
                                return `<span>图片</span>`
                            case 'TASK_CONTENT_TEXT':
                                return `<span>文本</span>`
                            default:
                                return `<span style="color: red">请联系管理员</span>`
                        }
                    })

                    massSending.push({
                        ...dataItem,
                        contentReactNode,
                        corpUsergroupIndex: i,
                        corpUserGroupName: `客服组${i + 1}`,
                        corpUserList: item.corpUsers,
                        bizType: settings?.bizType,
                        channel: settings?.channel,
                        platform: settings?.platform,
                        templateProductId: settings?.templateProductId,
                        id: i * row.length + (li + 1),
                        linkData,
                        miniProgramData,
                        userRowSpan: li % row.length === 0 ? row.length : 0,
                        strategyRowSpan: strategyIndex !== dataItem.strategyIndex ? dataItem.strategyDataCount : 0,
                        mpAccountId: item.corpUsers?.[0]?.mpAccountId,
                        mpAccountName: item.corpUsers?.[0]?.mpAccountName,
                        corpUserStrList: item.corpUsers?.map(item => item.corpId + '_' + item.corpUserId)
                    })
                    strategyIndex = dataItem.strategyIndex
                    return true
                })
            })) {
                return
            }
            console.log('massSending---->', massSending)
            newPreviewData.massSending = massSending
        }

        // 是否有客户继承配置
        if (settings?.userInherit && Object.keys(settings?.userInherit).length) {
            const userInData = getUserInDataData(settings?.userInherit?.schedulingStrategyDTO, settings?.userInherit?.taskName)

            const userInherit = []
            // 数据内容
            if (!settings?.corpUserGroups?.every((item, i) => {
                return userInData.every((dataItem, ii, row) => {

                    userInherit.push({
                        ...dataItem,
                        taskName: dataItem?.taskName,
                        corpUsergroupIndex: i,
                        corpUserGroupName: `客服组${i + 1}`,
                        corpUserList: item.corpUsers,
                        bizType: settings?.bizType,
                        channel: settings?.channel,
                        platform: settings?.platform,
                        templateProductId: settings?.templateProductId,
                        userRowSpan: ii === 0 ? row.length : 0,
                        id: i * row.length + (ii + 1)
                    })
                    return true
                })
            })) {
                return
            }
            console.log('userInherit-->', userInherit)
            newPreviewData.userInherit = userInherit
        }
        if (newPreviewData && Object.keys(newPreviewData).length) {
            setPreviewData(newPreviewData)
            setPreviewDataOld(newPreviewData)
        } else {
            message.error('请填写至少填写一项内容')
        }
    }

    // 设置任务名称
    const setTaskName = () => {
        console.log('---------->', previewContent)
        // 欢迎语
        if (settings?.welcomeMsgTemplateDTO && Object.keys(settings?.welcomeMsgTemplateDTO).length) {
            if (settings?.welcomeMsgTemplateDTO?.mediaContentList?.some(item => item?.some(i => i?.mediaType === 'link' || i?.mediaType === 'miniprogram')) && !(previewContent?.welcomeMsgContent?.length > 0)) {
                message.error('请先上传欢迎语Excel内容')
                return
            }
            if (!settings?.corpUserGroups?.every((_, i) => {
                return settings?.welcomeMsgTemplateDTO?.mediaContentList?.every((mediaItem, index) => {
                    const welcomeMsgContent = previewContent.welcomeMsgContent?.[i]?.[index]
                    if (mediaItem?.some(media => media?.mediaType === 'link' ? !welcomeMsgContent?.linkUrl : media?.mediaType === 'miniprogram' ? (!welcomeMsgContent?.miniprogramAppid || !welcomeMsgContent?.miniprogramPage) : false)) {
                        message.error('欢迎语内容配置错误，请检查')
                        return false
                    }
                    return true
                })
            })) {
                return
            }
        }
        // 群发任务
        if ((settings?.massSendingContent && Object.keys(settings?.massSendingContent).length) && (settings?.massSendingStrategy && Object.keys(settings?.massSendingStrategy).length)) {
            if (settings?.massSendingContent?.massSendingContentDTO?.some(item => item?.sendContentDto?.some(si => si?.contentDTO?.some(i => i?.attachmentList?.some(a => ['TASK_CONTENT_LINK', 'TASK_STATUS_MINIPROGRAM'].includes(a?.msgType))))) && !(previewContent?.groupMsgContent?.length > 0)) {
                message.error('需要配置小程序、链接，请认真填写')
                return
            }
            const massSendingData = getGroupData(settings)
            if (!settings?.corpUserGroups?.every((_, i) => {
                return massSendingData.every((dataItem) => {
                    const groupMsgContent = previewContent?.groupMsgContent?.[i]?.[dataItem.strategyIndex - 1]?.[dataItem.sendDataIndex - 1]?.[dataItem.contentIndex - 1]
                    if (dataItem?.content?.attachmentList?.length && dataItem?.content?.attachmentList?.some(item => (item?.msgType === 'TASK_CONTENT_LINK' ? !groupMsgContent?.linkUrl : item?.msgType === 'TASK_STATUS_MINIPROGRAM' ? (!groupMsgContent?.miniprogramAppid || !groupMsgContent?.miniprogramPage) : false))) {
                        message.error('群发内容配置错误，请检查')
                        return false
                    }
                    return true
                })
            })) {
                return
            }
        }
        // 客户继承
        if (settings?.userInherit && Object.keys(settings?.userInherit).length) {
            const userInData = getUserInDataData(settings?.userInherit?.schedulingStrategyDTO, settings?.userInherit?.taskName)
            if (!settings?.corpUserGroups?.every((item, i) => {
                return userInData.every((dataItem) => {
                    const externalUser = previewContent.externalUserTransferContent?.[i]?.[dataItem.strategyIndex - 1]?.[dataItem.inheritIndex - 1]
                    if (!externalUser || !externalUser?.corpUserName || !externalUser?.corpUserId) {
                        message.error('配置错误，' + JSON.stringify(dataItem) + '，' + JSON.stringify(item.externalUserTransferContent))
                        return false
                    }
                    return true
                })
            })) {
                return
            }
        }
        setSubVisible(true)
    }

    const onSubmit = (values: any) => {
        const { bizType, platform, templateProductId, corpUserGroups, welcomeMsgTemplateDTO, massSendingContent, massSendingStrategy, userInherit } = settings
        const params = {
            ...values,
            bizType,
            platform,
            templateProductId,
            corpUsers: corpUserGroups?.map((item, index) => {
                const params: { [x: string]: any } = {
                    corpId: item.corpUsers[0].corpId,
                    corpUserIds: item.corpUsers.map(item => item.corpUserId)
                }
                // 欢迎语
                if (settings?.welcomeMsgTemplateDTO && Object.keys(settings?.welcomeMsgTemplateDTO).length) {
                    params.welcomeMsgContent = previewContent?.welcomeMsgContent?.[index] || undefined
                }
                // 群发
                if (massSendingStrategy && Object.keys(massSendingStrategy).length > 0) {
                    params.groupMsgContent = previewContent?.groupMsgContent?.[index] || undefined
                }
                // 继承
                if (settings?.userInherit && Object.keys(settings?.userInherit).length) {
                    params.takeoverUserIds = previewContent?.externalUserTransferContent?.[index] || undefined
                }
                return params
            })
        }
        // 欢迎语
        if (welcomeMsgTemplateDTO && Object.keys(welcomeMsgTemplateDTO).length) {
            params.welcomeMsgTemplateDTO = welcomeMsgTemplateDTO
        }

        // 群发
        if (massSendingStrategy && Object.keys(massSendingStrategy).length) {
            params.groupSendTaskAddDTO = {
                groupSendName: massSendingStrategy.groupSendName,
                strategyList: massSendingStrategy?.strategySettings?.map((settingsItem, settingsIndex) => {
                    const {
                        // 发送对象
                        sendData,
                        // 策略
                        ...strategy
                    } = settingsItem
                    return {
                        ...strategy,
                        taskDetail: sendData.map((sendItem, sendIndex) => {
                            // 发送内容
                            const { contentDTO, sendMode } = massSendingContent.massSendingContentDTO[settingsIndex]['sendContentDto'][sendIndex]
                            const detail: { [x: string]: any } = {
                                sendMode,
                                contentDTO,
                                externalUserFilterName: sendItem?.externalUserFilterName
                            }
                            if (sendItem.externalUserType === 'specify') {
                                detail.externalUserFilter = {
                                    configName: sendItem.externalUserFilter.configName,
                                    ...sendItem.externalUserFilter.configContent
                                }
                            }
                            return detail
                        })
                    }
                })
            }
        }

        // 客户继承
        if (userInherit && Object.keys(userInherit).length) {
            params.externalUserTransferTasksDTO = {
                taskName: userInherit.taskName,
                schedulingStrategyDTO: userInherit.schedulingStrategyDTO.map(strategyItem => {
                    const {
                        inheritDto,
                        ...strategy
                    } = strategyItem
                    return {
                        ...strategy,
                        transferStrategyContentDTOS: inheritDto.map(inheritItem => {
                            const inherit: { [x: string]: any } = {
                                transferSuccessMsg: inheritItem.transferSuccessMsg
                            }
                            if (inheritItem.transferType === 'specify') {
                                inherit.externalUserFilter = {
                                    configName: inheritItem.transferUserDto.configName,
                                    ...inheritItem.transferUserDto.configContent
                                }
                            }
                            return inherit
                        })
                    }
                })
            }
        }
        console.log('11111111111111', values)
        if (projectId) {
            params.projectId = projectId
            updateTask.run(params).then(res => {
                console.log(res)
                if (res?.data) {
                    message.success('修改提交成功')
                    setProjectId(undefined)
                    sessionStorage.setItem('CAMPCORP', values?.projectName)
                    navigate('/weComTask/businessPlan/taskList')
                }
            })
        } else {
            addTask.run(params).then(res => {
                console.log(res)
                if (res?.data) {
                    modal.success({
                        content: '任务提交成功',
                        styles: { body: { fontWeight: 700 } },
                        okText: '跳转任务列表',
                        closable: true,
                        onOk: () => {
                            sessionStorage.setItem('CAMPCORP', values?.projectName)
                            navigate('/weComTask/businessPlan/taskList')
                        },
                        onCancel: () => {
                            setSubVisible(false)
                        }
                    })
                }
            })
        }
    }

    // 重置表格
    const onPreviewReset = () => {
        setPreviewData({})
        setPreviewDataOld({})
        if (!isEditSc) {
            setPreviewContent({})
        }
    }

    const severBd = () => {
        localStorage.setItem('TASK_CORP_CREATE', JSON.stringify({ settings }))
        message.success('存储成功')
    }

    const setContent = useCallback((data: TASK_CREATE.SetContentProps) => {
        const { msg, index, type } = data
        const newPreviewContent: { groupMsgContent?: any[], welcomeMsgContent?: any[], externalUserTransferContent?: any[] } = JSON.parse(JSON.stringify(previewContent))
        switch (type) {
            case 'welcome':
                newPreviewContent.welcomeMsgContent = newPreviewContent?.welcomeMsgContent || []
                if (!newPreviewContent.welcomeMsgContent?.[index[0]]) newPreviewContent.welcomeMsgContent[index[0]] = [];
                if (!newPreviewContent.welcomeMsgContent[index[0]][index[1]]) newPreviewContent.welcomeMsgContent[index[0]][index[1]] = {};
                newPreviewContent.welcomeMsgContent[index[0]][index[1]] = { ...newPreviewContent.welcomeMsgContent[index[0]][index[1]], ...msg }
                break
            case 'massSending':
                newPreviewContent.groupMsgContent = newPreviewContent?.groupMsgContent || []
                if (!newPreviewContent.groupMsgContent?.[index[0]]) newPreviewContent.groupMsgContent[index[0]] = [];
                if (!newPreviewContent.groupMsgContent[index[0]][index[1]]) newPreviewContent.groupMsgContent[index[0]][index[1]] = [];
                if (!newPreviewContent.groupMsgContent[index[0]][index[1]][index[2]]) newPreviewContent.groupMsgContent[index[0]][index[1]][index[2]] = [];
                if (!newPreviewContent.groupMsgContent[index[0]][index[1]][index[2]][index[3]]) newPreviewContent.groupMsgContent[index[0]][index[1]][index[2]][index[3]] = {};
                newPreviewContent.groupMsgContent[index[0]][index[1]][index[2]][index[3]] = { ...newPreviewContent.groupMsgContent[index[0]][index[1]][index[2]][index[3]], ...msg }
                break
            case 'userInherit':
                newPreviewContent.externalUserTransferContent = newPreviewContent?.externalUserTransferContent || []
                if (!newPreviewContent.externalUserTransferContent?.[index[0]]) newPreviewContent.externalUserTransferContent[index[0]] = [];
                if (!newPreviewContent.externalUserTransferContent[index[0]][index[1]]) newPreviewContent.externalUserTransferContent[index[0]][index[1]] = [];
                if (!newPreviewContent.externalUserTransferContent[index[0]][index[1]][index[2]]) newPreviewContent.externalUserTransferContent[index[0]][index[1]][index[2]] = {};
                newPreviewContent.externalUserTransferContent[index[0]][index[1]][index[2]] = { ...newPreviewContent.externalUserTransferContent[index[0]][index[1]][index[2]], ...msg }
                break
        }
        setPreviewContent(newPreviewContent)
    }, [previewContent])

    const tableSearch = useCallback((values) => {
        console.log(values)
        if (values?.mpAccountIds?.length > 0 || values?.corpUserIds?.length > 0) {
            const newPreviewData: TASK_CREATE.previewDataProps = {}
            const corpUserStrList = values?.corpUserIds?.map(item => item.corpId + '_' + item.corpUserId)
            if (previewDataOld?.welcome) {
                newPreviewData.welcome = previewDataOld.welcome.filter(item => (
                    (values?.mpAccountIds?.length > 0 ? values.mpAccountIds.includes(item.mpAccountId) : true)
                    &&
                    (corpUserStrList?.length > 0 ? item.corpUserStrList.some(str => corpUserStrList.includes(str)) : true)
                )).map(item => ({ ...item, rowSpan: 1 }))
            }
            if (previewDataOld?.massSending) {
                newPreviewData.massSending = previewDataOld.massSending.filter(item => (
                    (values?.mpAccountIds?.length > 0 ? values.mpAccountIds.includes(item.mpAccountId) : true)
                    &&
                    (corpUserStrList?.length > 0 ? item.corpUserStrList.some(str => corpUserStrList.includes(str)) : true)
                )).map(item => ({ ...item, userRowSpan: 1, strategyRowSpan: 1, sendDataRowSpan: 1 }))
            }
            setPreviewData(newPreviewData)
        } else {
            setPreviewData(previewDataOld)
        }
    }, [previewDataOld, previewData])

    return <div className={style.create}>
        <Spin spinning={getCreateDetails.loading}>
            <Card title={<strong>{projectId ? getCreateDetails?.data?.data?.projectName + '任务编辑' : ''}配置区</strong>} className={`${style.card} ${style.config}`}>
                <Space wrap>
                    <Space.Compact>
                        <Button>客服组</Button>
                        <SelectCorpUserGroup
                            disabled={isEditSc}
                            value={settings?.corpUserGroups}
                            onChange={(corpUserGroups) => {
                                console.log(corpUserGroups)
                                setSettings({
                                    ...settings, corpUserGroups: corpUserGroups.map(item => {
                                        return {
                                            ...item, corpUsers: item.corpUsers.map((item: any) => {
                                                const { corpUserId, name, corpName, corpId, mpAccountId, mpAccountInfo, id } = item
                                                return { corpUserId, name, corpName, corpId, mpAccountId, mpAccountName: mpAccountInfo?.name || item?.mpAccountName, id }
                                            })
                                        }
                                    })
                                })
                                onPreviewReset()
                            }}
                        />
                    </Space.Compact>
                    <Space.Compact>
                        <Button>业务类型</Button>
                        <Select
                            showSearch
                            style={{ width: 120 }}
                            allowClear
                            placeholder="请选择类型"
                            filterOption={(input, option) =>
                                ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                            }
                            value={settings?.bizType}
                            onChange={(e) => {
                                setSettings({ ...settings, bizType: e })
                                onPreviewReset()
                            }}
                            options={msgJobTypeList.filter(item => item.value === 'novel')}
                        />
                    </Space.Compact>

                    {settings?.bizType === 'novel' ? <>
                        <Space.Compact>
                            <Button>书城</Button>
                            <Select
                                showSearch
                                allowClear
                                placeholder="请选择书城"
                                style={{ width: 120 }}
                                filterOption={(input, option) =>
                                    ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                                }
                                value={settings?.platform}
                                onChange={(e) => {
                                    setSettings({ ...settings, platform: e, templateProductId: undefined })
                                    onPreviewReset()
                                }}
                                options={bookPlatForm.map(item => ({ value: item.id, label: item.platformName }))}
                            />
                        </Space.Compact>
                        <Space.Compact>
                            <Button>适用产品</Button>
                            <Select
                                showSearch
                                style={{ width: 150 }}
                                allowClear
                                placeholder="请选择模板适用产品"
                                filterOption={(input, option) =>
                                    ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                                }
                                value={settings?.templateProductId}
                                onChange={(e) => {
                                    setSettings({ ...settings, templateProductId: e })
                                    onPreviewReset()
                                }}
                                options={bookList.filter(item => settings?.platform ? item.platformId === settings?.platform : true).map(item => ({ value: item.id, label: item.bookName }))}
                            />
                        </Space.Compact>
                    </> : settings?.bizType === 'game' ? <Space.Compact>
                        <Button>游戏渠道</Button>
                        <Input
                            style={{ width: 200 }}
                            allowClear
                            placeholder="请输入游戏渠道"
                            value={settings.channel}
                            onChange={(e) => {
                                setSettings({ ...settings, channel: e.target.value })
                                onPreviewReset()
                            }}
                        />
                    </Space.Compact> : undefined}
                    
                </Space>

                <div className={style.settingsBody}>
                    <div className={style.settingsBody_content}>

                        <DispatchTaskCreate.Provider
                            value={{
                                settings, setSettings,
                                bookPlatForm,
                                bookList,
                                msgJobTypeList,
                                onPreviewReset,
                                isEditSc
                            }}>
                            <div className={style.settingsBody_content_right}>
                                {/* 欢迎语 */}
                                <Welcome />
                                {/* 群发设置 */}
                                <MassSending />
                                {/* 高级群发 */}
                                {/* <HighMassSending /> */}
                                {/* 朋友圈 */}
                                {/* <Friends /> */}
                                {/* 客户继承 */}
                                <UserInherit />
                            </div>
                        </DispatchTaskCreate.Provider>
                    </div>
                </div>

                <Space className={style.bts} wrap>
                    <Button icon={<SaveOutlined />} onClick={severBd}>存为预设</Button>
                    <Popconfirm
                        title="确定清空?"
                        onConfirm={() => {
                            setSettings(undefined)
                            setPreviewData({})
                            setPreviewDataOld({})
                            localStorage.removeItem('TASK_CORP_CREATE')
                        }}
                    >
                        <Button icon={<RedoOutlined />} danger>清空配置/预设</Button>
                    </Popconfirm>
                    <Button type='primary' onClick={preview}><SearchOutlined />预览任务/配置内容</Button>
                </Space>
            </Card>
        </Spin>

        <Card className={style.card} style={{ marginTop: 10, marginBottom: 10 }}>
            {Object.keys(previewData).length > 0 ? <div style={{ minHeight: 300 }}>
                <Form
                    layout={'inline'}
                    onFinish={tableSearch}
                >
                    <Form.Item label={<strong>公众号</strong>} name="mpAccountIds">
                        <Select
                            showSearch
                            style={{ minWidth: 160 }}
                            maxTagCount={1}
                            placeholder="公众号"
                            filterOption={(input, option) =>
                                ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                            }
                            allowClear
                            mode='multiple'
                            options={mpList}
                        />
                    </Form.Item>

                    <Space.Compact>
                        <Button>客服组</Button>
                        <Form.Item name="corpUserIds">
                            <SelectCorpUser placeholder="请选择客服号" />
                        </Form.Item>
                    </Space.Compact>
                    <Form.Item>
                        <Space>
                            <Button htmlType="reset">重置</Button>
                            <Button type="primary" htmlType='submit'>搜索</Button>
                        </Space>
                    </Form.Item>
                </Form>
                <Tabs
                    defaultActiveKey="1"
                    items={Object.keys(previewData).map(key => ({
                        key: key,
                        label: { 'userInherit': '客户继承', 'massSending': '客户群发', 'welcome': '欢迎语', 'highMassSending': '高级群发', 'friends': '朋友圈' }[key],
                        children: key === 'userInherit' ? <>
                            <Table
                                dataSource={previewData[key]}
                                columns={userInheritColumns(setContent)}
                                rowKey={'id'}
                                bordered={true}
                                scroll={{ y: 550 }}
                                pagination={false}
                            />
                        </> : key === 'massSending' ? <>
                            <Table
                                dataSource={previewData[key]}
                                columns={massSendingColumns(setContent, bookPlatForm, bookList, previewContent, bookPlatForm.find(item => item.id === Number(settings?.platform)).platformKey)}
                                rowKey={'id'}
                                bordered={true}
                                scroll={{ y: 550 }}
                                pagination={false}
                            />
                        </> : key === 'welcome' ? <>
                            <Table
                                dataSource={previewData[key]}
                                columns={welcomeColumns(bookPlatForm, bookList, setContent, previewContent, bookPlatForm.find(item => item.id === Number(settings?.platform)).platformKey)}
                                rowKey={'id'}
                                bordered={true}
                                scroll={{ y: 550 }}
                                pagination={false}
                            />
                        </> : key === 'highMassSending' ? <>
                            <Table
                                dataSource={previewData[key]}
                                columns={highMassSendingColumns()}
                                rowKey={'id'}
                                bordered={true}
                                scroll={{ y: 550 }}
                                pagination={false}
                            />
                        </> : key === 'friends' ? <>
                            <Table
                                dataSource={previewData[key]}
                                columns={friendsColumns()}
                                rowKey={'id'}
                                bordered={true}
                                scroll={{ y: 550 }}
                                pagination={false}
                            />
                        </> : undefined
                    }))}
                    tabBarExtraContent={<Space size={10}>
                        {/* <Text strong>欢迎语：{previewData?.welcome?.length || 0}，群发：{previewData?.massSending?.length || 0}，客户继承：{previewData?.userInherit?.length || 0}</Text> */}
                        <Button type='primary' icon={<PlusOutlined />} onClick={() => {
                            setTaskName()
                        }}>提交</Button>
                    </Space>}
                />
            </div> : <div style={{ minHeight: 400, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                <Empty description="请先完成模块配置后，再预览" />
            </div>}
        </Card>

        {/* 提交配置 */}
        {subVisible && <SubmitModal
            visible={subVisible}
            loading={addTask.loading || updateTask.loading}
            projectName={projectId ? getCreateDetails?.data?.data?.projectName : undefined}
            onChange={(values) => {
                onSubmit(values)
            }}
            onClose={() => {
                setSubVisible(false)
            }}
        />}

        {/* 选择外部客户 */}
        {eaVisible && <SelectExternalAccount
            corpUsers={settings?.corpUsers || []}
            visible={eaVisible}
            onClose={() => {
                setEaVisible(false)
            }}
            onChange={(value) => {
                setEaVisible(false)
                setSettings({
                    ...settings,
                    corpUsers: value
                })
            }}
        />}

        {qwVisible && <SelectCwTag
            corpUsers={settings?.corpUsers || []}
            visible={qwVisible}
            onClose={() => {
                setQwVisible(false)
            }}
            onChange={(value) => {
                setQwVisible(false)
                setSettings({
                    ...settings,
                    corpUsers: value
                })
            }}
        />}
    </div>
};

export default inject('store')(observer((props: any) => Create(props.store)))