import { inject, observer } from 'mobx-react';
import React, { useEffect, useState } from 'react';
import style from './index.less'
import { App, Button, Card, Empty, Input, Popconfirm, Select, Space, Spin, Table, Tabs } from 'antd';
import MassSending from './components/massSending';
import { useAjax } from '@/Hook/useAjax';
import { MediaContentProps, welcomeMsgJobTypeApi } from '@/pages/weComTask/API/weMaterial/weMaterial';
import SelectCorpUser from '../../corpUserManage/selectCorpUser';
import { SearchOutlined, PlusOutlined, RedoOutlined, SaveOutlined, CheckOutlined } from '@ant-design/icons';
import { getGroupData, getHighGroupData, getUserInDataData } from './const';
import { highMassSendingColumns, massSendingColumns, userInheritColumns, welcomeColumns } from './tableConfig';
import SubmitModal from './submitModal';
import { addTaskApi } 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 HighMassSending from './components/highMassSending';
import { toJS } from 'mobx';
import Friends from './components/friends';

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>();

    console.log(settings)
    const { message, modal } = App.useApp()
    const [msgJobTypeList, setMsgJobTypeList] = useState<{ value: string, label: string }[]>([])
    const [previewData, setPreviewData] = useState<TASK_CREATE.previewDataProps>({})
    const [subVisible, setSubVisible] = useState<boolean>(false) // 选择设置名称弹窗控制
    const [eaVisible, setEaVisible] = useState<boolean>(false)

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

    const addTask = useAjax((params) => addTaskApi(params))
    /***********************************************/

    useEffect(() => {
        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] })))
            }
        })
    }, [])

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

        const corpUsersLength = settings?.corpUsers?.length
        // 欢迎语
        if (settings?.welcomeMsgTemplateDTO && Object.keys(settings?.welcomeMsgTemplateDTO).length) {
            if (settings?.welcomeMsgTemplateDTO?.mediaContentList?.some(item => item?.some(i => i?.mediaType === 'link' || i?.mediaType === 'miniprogram')) && settings?.corpUsers?.every(item => !item?.welcomeMsgContent?.length)) {
                message.error('请先上传欢迎语Excel内容')
                return
            }
            const welcome = []
            if (!settings?.corpUsers?.every((item, i) => {
                return settings?.welcomeMsgTemplateDTO?.mediaContentList?.every((mediaItem, index, row) => {
                    const welcomeMsgContent = item.welcomeMsgContent?.[index]
                    if (mediaItem?.some(media => media?.mediaType === 'link' ? !welcomeMsgContent?.linkUrl : media?.mediaType === 'miniprogram' ? (!welcomeMsgContent?.miniprogramAppid || !welcomeMsgContent?.miniprogramPage) : false)) {
                        message.error('欢迎语内容配置错误，请检查')
                        return false
                    }
                    const contentReactNode = mediaItem.map(item => {
                        switch (item.mediaType) {
                            case 'link':
                                return `<span style="color: red">链接</span>`
                            case 'miniprogram':
                                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,
                        welcomeMsgContent,
                        contentIndex: index + 1,
                        corpUserId: item.corpUserId,
                        corpUserName: item.name,
                        bizType: settings?.bizType,
                        channel: settings?.channel,
                        platform: settings?.platform,
                        templateProductId: settings?.templateProductId,
                        id: i * row.length + (index + 1),
                        rowSpan: index === 0 ? row.length : 0
                    })
                    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)) {
            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))))) && settings?.corpUsers?.every(item => !item?.groupMsgContent?.length)) {
                message.error('需要配置小程序、链接，请上传配置好的群发Excel文件')
                return
            }
            const massSendingData = getGroupData(settings)
            const massSending = []
            if (!settings?.corpUsers?.every((item, i) => {

                let strategyIndex = 0

                return massSendingData.every((dataItem, li, row) => {
                    const groupMsgContent = item.groupMsgContent?.[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
                    }

                    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 contentReactNode = mediaItem.map(item => {
                        switch (item.msgType) {
                            case 'TASK_CONTENT_LINK':
                                return `<span style="color: red">链接</span>`
                            case 'TASK_STATUS_MINIPROGRAM':
                                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,
                        groupMsgContent,
                        contentReactNode,
                        corpUserId: item.corpUserId,
                        corpUserName: item.name,
                        bizType: settings?.bizType,
                        channel: settings?.channel,
                        platform: settings?.platform,
                        templateProductId: settings?.templateProductId,
                        id: i * row.length + (li + 1),
                        userRowSpan: li % row.length === 0 ? row.length : 0,
                        strategyRowSpan: strategyIndex !== dataItem.strategyIndex ? dataItem.strategyDataCount : 0
                    })
                    strategyIndex = dataItem.strategyIndex
                    return true
                })
            })) {
                return
            }
            console.log('massSending---->', massSending)
            newPreviewData.massSending = massSending
        }

        // 是否有客户继承配置
        if (settings?.userInherit && Object.keys(settings?.userInherit).length) {
            if (settings?.corpUsers?.every(item => !item?.externalUserTransferContent?.length)) {
                message.error('请上传配置好的客户继承Excel文件')
                return
            }
            const userInData = getUserInDataData(settings?.userInherit?.schedulingStrategyDTO, settings?.userInherit?.taskName)

            const userInherit = []
            // 数据内容
            if (!settings?.corpUsers?.every((item, i) => {
                return userInData.every((dataItem, ii, row) => {
                    const externalUser = item.externalUserTransferContent?.[dataItem.strategyIndex - 1]?.[dataItem.inheritIndex - 1]
                    if (!externalUser || !externalUser?.corpUserName || !externalUser?.corpUserId) {
                        message.error('Excel配置错误，' + JSON.stringify(dataItem) + '，' + JSON.stringify(item.externalUserTransferContent))
                        return false
                    }
                    userInherit.push({
                        ...dataItem,
                        externalUser,
                        taskName: dataItem?.taskName,
                        corpUserId: item.corpUserId,
                        corpUserName: item.name,
                        bizType: settings?.bizType,
                        channel: settings?.channel,
                        platform: settings?.platform,
                        templateProductId: settings?.templateProductId,
                        id: i * row.length + (ii + 1)
                    })
                    return true
                })
            })) {
                return
            }
            console.log('userInherit-->', userInherit)
            newPreviewData.userInherit = userInherit
        }

        // 是否有高级群发
        if ((settings?.highMassSendingContent && Object.keys(settings?.highMassSendingContent).length) && (settings?.highMassSendingStrategy && Object.keys(settings?.highMassSendingStrategy).length)) {
            if (settings?.highMassSendingContent?.massSendingContentDTO?.some(item => item?.sendContentDto?.some(si => si?.contentDTO?.some(i => i?.some(a => ["miniprogram", 'link'].includes(a?.mediaType))))) && settings?.corpUsers?.every(item => !item?.highGroupMsgContent?.length)) {
                message.error('需要配置小程序、链接，请上传配置好的高级群发Excel文件')
                return
            }
            const massSendingData = getHighGroupData(settings)
            console.log('massSendingData---->', massSendingData)
            const highMassSending = []
            let rowLength = 0
            if (!settings?.corpUsers?.every((item, i) => {

                let strategyIndex = 0
                let corpUserCount = 0
                return massSendingData.every((dataItem, li, row) => {

                    const mediaItem = JSON.parse(JSON.stringify(dataItem?.content || []))
                    const contentReactNode = mediaItem.map(item => {
                        switch (item.mediaType) {
                            case 'link':
                                return `<span style="color: red">链接</span>`
                            case 'miniprogram':
                                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>`
                        }
                    })
                    const externalUserListLength = item.externalUserList.length
                    return item.externalUserList?.every((externalUser, ii) => {
                        const layer3 = externalUser.corpId + '-' + externalUser.externalUserId
                        const externalUserMsg = item.highGroupMsgContent?.[dataItem.strategyIndex - 1]?.[dataItem.sendDataIndex - 1]?.[layer3]?.[dataItem.contentIndex - 1]
                        if (mediaItem?.some(media => media?.mediaType === 'link' ? !externalUserMsg?.linkUrl : media?.mediaType === 'miniprogram' ? (!externalUserMsg?.miniprogramAppid || !externalUserMsg?.miniprogramPage) : false)) {
                            message.error('高级群发配置错误，请检查')
                            return false
                        }
                        rowLength++;
                        highMassSending.push({
                            ...dataItem,
                            groupMsgContent: externalUserMsg,
                            contentReactNode,
                            externalUser,
                            corpUserId: item.corpUserId,
                            corpUserName: item.name,
                            bizType: settings?.bizType,
                            channel: settings?.channel,
                            platform: settings?.platform,
                            templateProductId: settings?.templateProductId,
                            id: rowLength,
                            userRowSpan: corpUserCount === 0 ? (massSendingData.length * externalUserListLength) : 0,
                            strategyRowSpan: strategyIndex !== dataItem.strategyIndex ? dataItem.sendDataRowSpan * externalUserListLength * dataItem.strategyItemSendDataCount : 0,
                            sendDataRowSpan: ii === 0 ? externalUserListLength * dataItem.sendDataRowSpan : 0
                        })
                        corpUserCount++;
                        strategyIndex = dataItem.strategyIndex

                        return true
                    })
                })
            })) {
                return
            }
            newPreviewData.highMassSending = highMassSending
        }

        if (newPreviewData && Object.keys(newPreviewData).length) {
            setPreviewData(newPreviewData)
        } else {
            message.error('请填写至少填写一项内容')
        }
    }

    const onSubmit = (values: any) => {
        const { bizType, platform, templateProductId, corpUsers, welcomeMsgTemplateDTO, massSendingContent, massSendingStrategy, highMassSendingContent, highMassSendingStrategy, userInherit } = settings
        const params = {
            ...values,
            bizType,
            platform,
            templateProductId,
            corpUsers: corpUsers?.map(item => {
                const params: { [x: string]: any } = {
                    corpId: item.corpId,
                    corpUserId: item.corpUserId
                }
                // 欢迎语
                if (item?.welcomeMsgContent) {
                    params.welcomeMsgContent = item?.welcomeMsgContent
                }
                // 群发
                if (item?.groupMsgContent) {
                    params.groupMsgContent = item?.groupMsgContent
                }
                // 继承
                if (item?.externalUserTransferContent) {
                    params.takeoverUserIds = item?.externalUserTransferContent
                }
                // 高级群发
                if (item?.highGroupMsgContent) {
                    params.messageSendContent = item?.highGroupMsgContent
                    // 外部成员
                    if (item?.externalUserList) {
                        params.corpList = item?.externalUserList.map(item => ({
                            externalUserId: item.externalUserId,
                            corpId: item.corpId
                        }))
                    }
                }

                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
                            }
                            if (sendItem.externalUserType === 'specify') {
                                detail.externalUserFilter = {
                                    configName: sendItem.externalUserFilter.configName,
                                    ...sendItem.externalUserFilter.configContent
                                }
                            }
                            return detail
                        })
                    }
                })
            }
        }
        // 高级群发
        if (highMassSendingStrategy && Object.keys(highMassSendingStrategy).length) {
            params.messageSendTaskAddDTO = {
                groupSendName: highMassSendingStrategy.groupSendName,
                strategyList: highMassSendingStrategy?.strategySettings?.map((settingsItem, settingsIndex) => {
                    const {
                        // 发送对象
                        sendData,
                        // 策略
                        ...strategy
                    } = settingsItem
                    return {
                        ...strategy,
                        taskDetail: sendData.map((sendItem, sendIndex) => {
                            // 发送内容
                            const { contentDTO, sendMode } = highMassSendingContent.massSendingContentDTO[settingsIndex]['sendContentDto'][sendIndex]
                            const detail: { [x: string]: any } = {
                                sendMode,
                                contentDTO: contentDTO.map(item => {

                                    let newContentDTO: { [x: string]: any } = {}
                                    item.forEach((item: MediaContentProps) => {
                                        switch (item.mediaType) {
                                            case "text":
                                                newContentDTO = {
                                                    text: {
                                                        content: item?.textContent
                                                    },
                                                    msgType: 'TASK_CONTENT_TEXT'
                                                }
                                                break
                                            case "miniprogram":
                                                newContentDTO = {
                                                    miniprogram: {
                                                        appId: item?.miniprogramAppid,
                                                        page: item?.miniprogramPage,
                                                        title: item?.miniprogramTitle,
                                                        picUrl: item?.miniprogramPicurl
                                                    },
                                                    msgType: 'TASK_STATUS_MINIPROGRAM'
                                                }
                                                break
                                            case "link":
                                                newContentDTO = {
                                                    link: {
                                                        desc: item?.linkDesc,
                                                        picUrl: item?.linkPicurl,
                                                        title: item?.linkTitle,
                                                        url: item?.linkUrl
                                                    },
                                                    msgType: 'TASK_CONTENT_LINK'
                                                }
                                                break
                                            case "image":
                                                newContentDTO = {
                                                    image: {
                                                        picUrl: item?.imageUrl
                                                    },
                                                    msgType: 'TASK_CONTENT_IMAGE'
                                                }
                                                break
                                            case "video":
                                                newContentDTO = {
                                                    video: {
                                                        videoUrl: item?.videoUrl
                                                    },
                                                    msgType: 'TASK_STATUS_VIDEO'
                                                }
                                                break
                                            case "file":
                                                newContentDTO = {
                                                    file: {
                                                        fileUrl: item?.fileUrl
                                                    },
                                                    msgType: 'TASK_STATUS_FILE'
                                                }
                                                break
                                        }
                                    })

                                    return newContentDTO
                                })
                            }
                            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('params---->', params)
        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({})
    }

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

    return <div className={style.create}>
        <Spin spinning={false}>
            <Card title={<strong>配置区</strong>} className={`${style.card} ${style.config}`}>
                <Space wrap>
                    <Space.Compact>
                        <Button>客服号</Button>
                        <SelectCorpUser
                            value={settings?.corpUsers}
                            onChange={(corpUsers) => {
                                console.log(corpUsers)
                                setSettings({
                                    ...settings, corpUsers: corpUsers.map(item => {
                                        const { corpUserId, name, corpName, corpId } = item
                                        return { corpUserId, name, corpName, corpId }
                                    })
                                })
                                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: 200 }}
                                filterOption={(input, option) =>
                                    ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                                }
                                value={settings?.platform}
                                onChange={(e) => {
                                    setSettings({ ...settings, platform: e })
                                    onPreviewReset()
                                }}
                                options={bookPlatForm.map(item => ({ value: item.id, label: item.platformName }))}
                            />
                        </Space.Compact>
                        <Space.Compact>
                            <Button>适用产品</Button>
                            <Select
                                showSearch
                                style={{ width: 200 }}
                                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.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}

                    {(settings?.highMassSendingStrategy && Object.keys(settings?.highMassSendingStrategy).length > 0) && <Button
                        onClick={() => setEaVisible(true)}
                        type={settings?.corpUsers?.every(item => item?.externalUserList?.length) ? 'primary' : 'default'}
                    >
                        {settings?.corpUsers?.every(item => item?.externalUserList?.length) ? <>
                            重选高级群发外部客户
                            <CheckOutlined style={{ marginLeft: 5 }} />
                        </> : '高级群发外部客户选择'}
                    </Button>}
                </Space>

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

                        <DispatchTaskCreate.Provider
                            value={{
                                settings, setSettings,
                                bookPlatForm,
                                bookList,
                                msgJobTypeList,
                                onPreviewReset
                            }}>
                            <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)
                            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 }}>
                <Tabs
                    defaultActiveKey="1"
                    items={Object.keys(previewData).map(key => ({
                        key: key,
                        label: { 'userInherit': '客户继承', 'massSending': '客户群发', 'welcome': '欢迎语', 'highMassSending': '高级群发' }[key],
                        children: key === 'userInherit' ? <>
                            <Table
                                dataSource={previewData[key]}
                                columns={userInheritColumns()}
                                rowKey={'id'}
                                bordered={true}
                                scroll={{ y: 550 }}
                                pagination={false}
                            />
                        </> : key === 'massSending' ? <>
                            <Table
                                dataSource={previewData[key]}
                                columns={massSendingColumns()}
                                rowKey={'id'}
                                bordered={true}
                                scroll={{ y: 550 }}
                                pagination={false}
                            />
                        </> : key === 'welcome' ? <>
                            <Table
                                dataSource={previewData[key]}
                                columns={welcomeColumns(bookPlatForm, bookList)}
                                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}
                            />
                        </> : 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={() => {
                            setSubVisible(true)
                        }}>提交</Button>
                    </Space>}
                />
            </div> : <div style={{ minHeight: 400, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                <Empty description="请先完成模块配置后，再预览" />
            </div>}
        </Card>

        {/* 提交配置 */}
        {subVisible && <SubmitModal
            visible={subVisible}
            ajax={addTask}
            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
                })
            }}
        />}
    </div>
};

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