import React, { useCallback, useEffect, useState } from 'react';
import style from '../../../businessPlan/create/index.less'
import { App, Button, Card, Empty, Form, Input, Popconfirm, Select, Space, Spin, Table } from 'antd';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { welcomeMsgJobTypeApi } from '@/pages/weComTask/API/weMaterial/weMaterial';
import { useAjax } from '@/Hook/useAjax';
import Strategy from './components/Strategy';
import { getBindMpListApi } from '@/pages/weComTask/API/corpUserAssign';
import { DefaultOptionType } from 'antd/es/select';
import { getCorpAllListApi } from '@/API/global';
import { SaveOutlined, RedoOutlined, SearchOutlined, PlusOutlined, CheckOutlined } from '@ant-design/icons';
import Content from './components/content';
import { groupBy, removeEmptyValues } from '@/utils/utils';
import { PreviewColumns } from './tableConfig';
import SubmitModal from '../../../businessPlan/create/submitModal';
import { addTaskApi, getCreateDetailsApi, updateTaskApi } from '@/pages/weComTask/API/businessPlan/create';
import { useNavigate } from 'react-router-dom';
import { getRobotSendData, transformData } from './const';
import GroupChatGroups from '@/pages/weComTask/components/groupChatGroups';


export const DispatchRobotChatCreate = React.createContext<ROBOT_CHAT_CREATE.DispatchRobotChatCreate | null>(null);
/**
 * 官方群发任务创建
 * @returns 
 */
const OfficialCreate: React.FC<{ weComTaskStore: { data: { bookList: TASK_CREATE.BookListProps[], bookPlatForm: TASK_CREATE.BookPlatFormProps[] } } }> = ({ weComTaskStore }) => {

    /*******************************************/
    const navigate = useNavigate();
    const { message, modal } = App.useApp()
    const { bookList, bookPlatForm } = toJS(weComTaskStore.data)
    const [settings, setSettings] = useState<ROBOT_CHAT_CREATE.SettingsProps>();
    const [msgJobTypeList, setMsgJobTypeList] = useState<{ value: string, label: string }[]>([])
    const [projectId, setProjectId] = useState<number>()
    const [isEditSc, setIsEditSc] = useState<boolean>(false)
    const [previewData, setPreviewData] = useState<any[]>([])
    const [previewDataOld, setPreviewDataOld] = useState<any[]>([])
    const [mpList, setMpList] = useState<DefaultOptionType[]>([])
    const [corpList, setCorpList] = useState<DefaultOptionType[]>([])
    const [previewContent, setPreviewContent] = useState<{ [x: string]: { [x: string]: string } }>({})
    const [subVisible, setSubVisible] = useState<boolean>(false) // 选择设置名称弹窗控制
    const [corpGroupChat, setCorpGroupChat] = useState<{ [x: string]: any }>({})

    const welcomeMsgJobType = useAjax(() => welcomeMsgJobTypeApi())//获取业务类型
    const getBindMpList = useAjax(() => getBindMpListApi())
    const getCorpAllList = useAjax((param) => getCorpAllListApi(param))
    const addTask = useAjax((params) => addTaskApi(params))
    const updateTask = useAjax((params) => updateTaskApi(params))
    const getCreateDetails = useAjax((params) => getCreateDetailsApi(params))
    /*******************************************/

    useEffect(() => {
        const project = sessionStorage.getItem('ROBOT_OFFICIALTASKID')
        if (project) {
            const { id, isCopy, isEditSc } = JSON.parse(project)
            setIsEditSc(isEditSc)
            if (!isCopy) {
                setProjectId(id)
            }
            getCreateDetails.run(id).then(res => {
                sessionStorage.removeItem('ROBOT_OFFICIALTASKID')
                if (res?.data) {
                    const { bizType, platform, templateProductId, channel, robotGroupChatSendTaskAddDTO, mpAccounts } = res.data
                    const group = mpAccounts.map(m => {
                        return {
                            mpAccount: m?.mpAccountVO?.name ? {
                                label: m?.mpAccountVO?.name || '',
                                value: m?.mpAccountVO?.id || '',
                                appId: m?.mpAccountVO?.appId || '',
                            } : undefined,
                            corp: m?.corpVOList?.map(c => ({ label: c.corpName, value: c.corpId })) || [],
                            ownerUsers: m?.corpUserVOList?.map(u => ({ name: u.name, corpUserId: u.corpUserId, corpId: u.corpId, corpName: u.corpName })) || []
                        }
                    })
                    let newSettings: ROBOT_CHAT_CREATE.SettingsProps = {
                        bizType,
                        platform: Number(platform) as any,
                        templateProductId,
                        channel,
                        group
                    }

                    if (robotGroupChatSendTaskAddDTO && Object.keys(robotGroupChatSendTaskAddDTO).length > 0) {
                        const data = getRobotSendData(robotGroupChatSendTaskAddDTO)
                        newSettings = { ...newSettings, strategyDTO: data }

                        // 处理链接小程序 历史数据
                        const list: any[] = []
                        data?.strategyList?.forEach((str, s_index) => {
                            str?.sendData?.forEach((sd, f_index) => {
                                sd?.contentDTO?.forEach((cd, c_index) => {
                                    if (cd?.attachmentList?.length || cd?.text?.content) {
                                        const mediaItem = JSON.parse(JSON.stringify(cd?.attachmentList || []))
                                        if (cd?.text?.content) {
                                            mediaItem.push({
                                                msgType: 'TASK_CONTENT_TEXT',
                                                textContent: cd?.text?.content
                                            })
                                        }
                                        const linkData = []
                                        const miniProgramData = []
                                        mediaItem.forEach(item => {
                                            switch (item.msgType) {
                                                case 'TASK_CONTENT_LINK':
                                                    linkData.push(item)
                                                    break
                                                case 'TASK_STATUS_MINIPROGRAM':
                                                    miniProgramData.push(item)
                                                    break
                                            }
                                        })
                                        list.push({
                                            strategyIndex: s_index,
                                            sendIndex: f_index,
                                            contentIndex: c_index,
                                            linkData,
                                            miniProgramData
                                        })
                                        return true
                                    }
                                })
                            })
                        })
                        let id = 1
                        const newPreviewContent: { [x: string]: { [x: string]: string } } = {}
                        group.forEach((g, g_index) => {
                            list.forEach((l) => {
                                const { strategyIndex, sendIndex, contentIndex, linkData, miniProgramData } = l
                                if (linkData || miniProgramData) {
                                    const content = mpAccounts?.[g_index]?.groupChatMsgContent?.[strategyIndex]?.[sendIndex]?.[contentIndex]
                                    newPreviewContent[id] = {
                                        linkUrl: content?.linkUrl,
                                        miniprogramAppid: content?.miniprogramAppid,
                                        miniprogramPage: content?.miniprogramPage
                                    }
                                }
                                id++
                            })
                        })
                        setPreviewContent(newPreviewContent)
                    }
                    setSettings(newSettings)

                    // 处理群素材历史数据
                    const newCorpGroupChat: { [x: string]: any } = {}
                    mpAccounts.forEach((m, m_index) => {
                        m?.corpGroupChat?.forEach((c, c_index) => {
                            c?.forEach((i, i_index) => {
                                newCorpGroupChat[m_index + '_' + c_index + '_' + i_index] = {
                                    chatCorpId: i.corpId,
                                    corpGroupChat: {
                                        chatId: i?.chatId,
                                        chatName: i?.chatName,
                                        corpId: i?.corpId,
                                        corpName: i?.corpName
                                    }
                                }
                            })
                        })
                    })
                    setCorpGroupChat(newCorpGroupChat)
                }
            })
        } else {
            const task = localStorage.getItem('TASK_ROBOT_CHAT_SEND_CREATE')
            if (task) {
                setSettings(JSON.parse(task).settings)
            }
        }
    }, [])

    useEffect(() => {
        getBindMpList.run().then(res => {
            if (res?.data)
                setMpList(res.data.map((item: any) => ({ label: item.name, value: item.id, appId: item.appId })))
        })

        getCorpAllList.run({}).then(res => {
            if (res?.data)
                setCorpList(res.data.map((item: any) => ({ label: item.corpName, value: item.corpId })))
        })
    }, [])

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

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

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

    // 预览
    const preview = () => {
        const { bizType, platform, templateProductId, channel, group } = settings
        if (!(settings?.strategyDTO && Object.keys(settings?.strategyDTO).length > 0)) {
            message.error('请先配置内容')
            return
        }
        if (group.some(item => !item?.corp?.length)) {
            message.error('请选择关联主体')
            return
        }
        if (!bizType) {
            message.error('请选择业务类型')
            return
        }
        if (!platform) {
            message.error('请选择书城')
            return
        }
        const list: any[] = []
        if (!settings?.strategyDTO?.strategyList?.every((str, s_index) => {
            const { sendData, ...sdto } = str
            const count = sendData.reduce((pre, cur) => pre + (cur?.contentDTO?.length || 0), 0)
            let saveIndex = 0
            return sendData?.every((sd, f_index) => {
                const { contentDTO, robotCorpId, robotCorpUser, chatCorpId, corpGroupChat, ...cdto } = sd
                if (contentDTO?.length) {
                    return contentDTO?.every((cd, c_index) => {
                        if (cd?.attachmentList?.length || cd?.text?.content) {
                            const mediaItem = JSON.parse(JSON.stringify(cd?.attachmentList || []))
                            if (cd?.text?.content) {
                                mediaItem.push({
                                    msgType: 'TASK_CONTENT_TEXT',
                                    textContent: cd?.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>`
                                }
                            })
                            list.push({
                                bizType,
                                platform,
                                templateProductId,
                                channel,
                                groupSendName: settings?.strategyDTO?.groupSendName,
                                strategyData: sdto,
                                robotCorpId,
                                robotCorpName: corpList.find(item => item.value === robotCorpId)?.label,
                                robotCorpUser,
                                chatCorpId,
                                chatCorpName: corpList.find(item => item.value === chatCorpId)?.label,
                                corpGroupChat,
                                sendData: cdto,
                                contentReactNode,
                                content: cd,
                                strategyIndex: s_index,
                                sendIndex: f_index,
                                contentIndex: c_index,
                                linkData,
                                miniProgramData,
                                contentRowSpan: c_index === 0 ? contentDTO.length : 0, // 用于表格合并
                                strategyRowSpan: saveIndex === 0 ? count : 0
                            })
                            saveIndex += 1
                            return true
                        } else {
                            message.error(`策略：${str?.strategyName}，发送对象：${sd?.sendGroupName}请填写发送内容`)
                            return false
                        }
                    })
                } else {
                    message.error(`策略：${str?.strategyName}，发送对象：${sd?.sendGroupName}请填写发送内容`)
                    return false
                }

            })
        })) {
            return
        }
        let id = 1
        const newPreviewData = group.reduce((pre, cur, index) => {
            return pre.concat(...list.map((item, i) => {
                return {
                    ...item,
                    id: id++,
                    mpAccountId: cur?.mpAccount?.value || index,
                    mpAccountName: cur?.mpAccount?.label || `群发组${index + 1}`,
                    mpAccountAppid: (cur as any)?.mpAccount?.appId,
                    corpIds: cur.corp?.map(item => item.value),
                    corpNames: cur.corp?.map(item => item.label),
                    mpIndex: index,
                    mpRowSpan: i === 0 ? list.length : 0, // 用于表格合并
                }
            }))
        }, [])
        console.log('=========================>', newPreviewData)
        setPreviewData(newPreviewData)
        setPreviewDataOld(newPreviewData)
    }

    const tableSearch = useCallback((values) => {
        console.log(values)
        const obj = removeEmptyValues(values)
        if (Object.keys(obj).length) {
            const newPreviewData = previewDataOld.filter(item => {
                return (obj?.weChatAppids?.length > 0 ? obj.weChatAppids.includes(item?.mpAccountId) : true)
                    && (obj?.corpIds?.length > 0 ? obj.corpIds.some(corpId => item?.corpIds.includes(corpId)) : true)
            })
            setPreviewData(newPreviewData)
        } else {
            setPreviewData(previewDataOld)
        }
    }, [previewDataOld, previewData])

    const setTaskName = () => {
        if (!settings.group?.every((_, index) => settings?.strategyDTO?.strategyList?.every((str, s_index) => str.sendData?.every((sd, f_index) => {
            const chat = corpGroupChat?.[index + '_' + s_index + '_' + f_index]
            return chat?.chatCorpId && chat?.corpGroupChat
        })))) {
            message.error('请补充群聊主体等信息')
            return
        }
        if (previewDataOld.every((item, index) => {
            if ((item?.linkData?.length > 0 ? previewContent?.[index + 1]?.linkUrl : true) && (item?.miniProgramData?.length > 0 ? (previewContent?.[index + 1]?.miniprogramAppid && previewContent?.[index + 1]?.miniprogramPage) : true)) {
                return true
            } else {
                message.error('请补充图文或者小程序内容')
                return false
            }
        })) {
            setSubVisible(true)
        }
    }

    const onSubmit = (values: any) => {
        const corpGroupChatData = transformData(corpGroupChat)
        const groupData = groupBy(previewDataOld, (item) => item['mpIndex'], true);
        const { bizType, platform, templateProductId, channel, strategyDTO, group } = settings
        const params = {
            ...values,
            bizType,
            platform,
            templateProductId,
            channel,
            mpAccounts: group.map((item, index) => {
                const data = groupData[index] || []
                const groupChatMsgContent: any[] = []
                data.forEach(d => {
                    const { strategyIndex, sendIndex, contentIndex, id } = d
                    if (!groupChatMsgContent[strategyIndex]) groupChatMsgContent[strategyIndex] = [];
                    if (!groupChatMsgContent[strategyIndex][sendIndex]) groupChatMsgContent[strategyIndex][sendIndex] = [];
                    groupChatMsgContent[strategyIndex][sendIndex][contentIndex] = previewContent?.[id] || {};
                })
                const mpAccount: any = {
                    mpAccountId: item?.mpAccount?.value,
                    corpIds: item.corp?.map(c => c.value) || [],
                    groupChatMsgContent,
                    corpGroupChat: corpGroupChatData[index]
                }
                if (item.ownerUsers?.length) {
                    mpAccount.ownerUserIds = item.ownerUsers.map(u => u.corpUserId)
                }
                return mpAccount
            }),
            robotChatSendTaskAddDTO: {
                ...strategyDTO,
                strategyList: strategyDTO?.strategyList?.map(item => {
                    const { sendData, ...its } = item
                    return {
                        ...its,
                        taskDetail: sendData.map(sd => {
                            const { externalUserType, externalUserFilter, contentDTO, sendGroupName, robotCorpId, robotCorpUser, ...itsd } = sd

                            const detail: { [x: string]: any } = {
                                ...itsd,
                                contentDTO,
                                externalUserFilterName: sendGroupName,
                            }
                            if (robotCorpId) {
                                detail.robotCorpUser = { corpUserId: robotCorpUser?.[0]?.corpUserId, corpId: robotCorpUser?.[0]?.corpId, corpName: robotCorpUser?.[0]?.corpName, name: robotCorpUser?.[0]?.name }
                            }
                            if (externalUserType === 'specify') {
                                detail.externalUserFilter = {
                                    configName: externalUserFilter.configName,
                                    ...externalUserFilter.configContent
                                }
                            }
                            return detail
                        })
                    }
                })
            }
        }
        if (projectId) {
            params.projectId = projectId
            updateTask.run(params).then(res => {
                console.log(res)
                if (res?.data) {
                    message.success('修改提交成功')
                    setProjectId(undefined)
                    sessionStorage.setItem('CAMPCORP_OFFICIAL', values?.projectName)
                    navigate('/weComTask/groupChatSend/robot/taskList')
                }
            })
        } else {
            addTask.run(params).then(res => {
                if (res?.data) {
                    modal.success({
                        content: '任务提交成功',
                        styles: { body: { fontWeight: 700 } },
                        okText: '跳转任务列表',
                        closable: true,
                        onOk: () => {
                            sessionStorage.setItem('CAMPCORP_OFFICIAL', values?.projectName)
                            navigate('/weComTask/groupChatSend/robot/taskList')
                        },
                        onCancel: () => {
                            setSubVisible(false)
                        }
                    })
                }
            })
        }
    }

    return <div className={style.create}>
        <Spin spinning={false}>
            <Card title={<strong>{projectId ? getCreateDetails?.data?.data?.projectName + '任务编辑' : ''}配置区</strong>} className={`${style.card} ${style.config}`}>
                <Space wrap>
                    <Space.Compact>
                        <Button>群发组</Button>
                        <GroupChatGroups
                            isOwnerUser
                            mpList={mpList}
                            corpList={corpList}
                            value={settings?.group}
                            disabled={isEditSc}
                            onChange={(group) => {
                                setSettings({
                                    ...settings,
                                    group
                                })
                                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}>
                        <DispatchRobotChatCreate.Provider
                            value={{
                                settings, setSettings,
                                onPreviewReset,
                                bookPlatForm, bookList,
                                mpList,
                                corpList,
                                isEditSc
                            }}
                        >
                            {/* 策略配置 */}
                            <Strategy />
                            {/* 群发内容 */}
                            <Content />
                        </DispatchRobotChatCreate.Provider>
                    </div>
                </div>
                <Space className={style.bts} wrap>
                    <Button icon={<SaveOutlined />} onClick={severBd}>存为预设</Button>
                    <Popconfirm
                        title="确定清空?"
                        onConfirm={() => {
                            setSettings(undefined)
                            onPreviewReset()
                            localStorage.removeItem('TASK_ROBOT_CHAT_SEND_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 }}
            extra={previewDataOld?.length > 0 ? <Button type='primary' icon={<PlusOutlined />} onClick={() => {
                setTaskName()
            }}>提交</Button> : undefined}
        >
            {previewDataOld?.length > 0 ? <div style={{ minHeight: 300 }}>
                <Form
                    layout={'inline'}
                    onFinish={tableSearch}
                    colon={false}
                >
                    <Form.Item label={<strong>关联公众号</strong>} style={{ marginBottom: 10 }} name="weChatAppids">
                        <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>
                    <Form.Item label={<strong>群聊主体</strong>} style={{ marginBottom: 10 }} name="corpIds">
                        <Select
                            showSearch
                            style={{ minWidth: 160 }}
                            maxTagCount={1}
                            placeholder="请选择主体"
                            filterOption={(input, option) =>
                                ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                            }
                            allowClear
                            options={corpList}
                            mode='multiple'
                        />
                    </Form.Item>

                    <Form.Item style={{ marginBottom: 10 }}>
                        <Space>
                            <Button htmlType="reset">重置</Button>
                            <Button type="primary" htmlType='submit'>搜索</Button>
                        </Space>
                    </Form.Item>
                </Form>
                <Table
                    dataSource={previewData}
                    columns={PreviewColumns(corpList, bookPlatForm, bookList, bookPlatForm.find(item => item.id === Number(settings?.platform)).platformKey, setPreviewContent, previewContent, corpGroupChat, setCorpGroupChat)}
                    rowKey={'id'}
                    bordered={true}
                    scroll={{ y: 550 }}
                    pagination={false}
                />
            </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)
            }}
        />}
    </div>;
};

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