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 { welcomeMsgJobTypeApi } from '@/pages/weComTask/API/weMaterial/weMaterial';
import { useAjax } from '@/Hook/useAjax';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import Strategy from './components/strategy';
import GroupUser from './components/groupUser';
import { SaveOutlined, RedoOutlined, SearchOutlined, PlusOutlined } from '@ant-design/icons';
import { getCorpUserChatAllListApi } from '@/pages/weComTask/API/groupLeaderManage';
import SelectCorpUserChatUser from '../../groupLeaderManage/selectCorpUserChatUser';
import { PreviewColumns } from './tableConfig';
import SelectCorpUser from '../../corpUserManage/selectCorpUser';
import { getBindMpListApi } from '@/pages/weComTask/API/corpUserAssign';
import { getCorpAllListApi } from '@/API/global';
import { removeEmptyValues } from '@/utils/utils';
import SubmitModal from '../../businessPlan/create/submitModal';
import { addPullGroupTaskApi, getCreateDetailsApi, getPullGroupEstimateNumApi, updateGroupTaskApi } from '@/pages/weComTask/API/groupChat';
import { useNavigate } from 'react-router-dom';
import { getPullGroupData } from './const';
import SelectGroupLeader from '../../groupLeaderManage/selectGroupLeader';

export const DispatchGroupChatCreate = React.createContext<GROUP_CHAT_CREATE.DispatchGroupChatCreate | null>(null);

/**
 * 群聊任务创建组件
 * @returns 
 */
const GroupChatCreate: React.FC<{ weComTaskStore: { data: { bookList: TASK_CREATE.BookListProps[], bookPlatForm: TASK_CREATE.BookPlatFormProps[] } } }> = ({ weComTaskStore }) => {

    /***********************************************/
    const navigate = useNavigate();
    const { bookList, bookPlatForm } = toJS(weComTaskStore.data)
    const { message, modal } = App.useApp()

    const [settings, setSettings] = useState<GROUP_CHAT_CREATE.SettingsProps>();
    const [msgJobTypeList, setMsgJobTypeList] = useState<{ value: string, label: string }[]>([])
    const [previewData, setPreviewData] = useState<any[]>([])
    const [previewDataOld, setPreviewDataOld] = useState<any[]>([])
    const [mpList, setMplist] = useState<{ label: string, value: string }[]>([])
    const [subVisible, setSubVisible] = useState<boolean>(false) // 选择设置名称弹窗控制
    const [projectId, setProjectId] = useState<number>()
    const [estimateNumDto, setEstimateNumDto] = useState<Record<string, number>>({})


    const welcomeMsgJobType = useAjax(() => welcomeMsgJobTypeApi())//获取业务类型
    const getBindMpList = useAjax(() => getBindMpListApi())
    const getCorpAllList = useAjax((params) => getCorpAllListApi(params))
    const addPullGroupTask = useAjax((params) => addPullGroupTaskApi(params))
    const updateGroupTask = useAjax((params) => updateGroupTaskApi(params))
    const getCreateDetails = useAjax((params) => getCreateDetailsApi(params))
    const getPullGroupEstimateNum = useAjax((params) => getPullGroupEstimateNumApi(params))
    /***********************************************/

    useEffect(() => {
        const project = sessionStorage.getItem('PG_OFFICIALTASKID')
        if (project) {
            const { id, isCopy } = JSON.parse(project)
            if (!isCopy) {
                setProjectId(id)
            }
            getCreateDetails.run(id).then(res => {
                sessionStorage.removeItem('PG_OFFICIALTASKID')
                if (res?.data) {
                    const { bizType, platform, templateProductId, corpUsers, corpChatUserList, corpRobots, strategyList } = res.data
                    const data = getPullGroupData(strategyList || [])
                    console.log('data-->', data)
                    let newSettings: GROUP_CHAT_CREATE.SettingsProps = {
                        bizType,
                        platform: Number(platform) as any,
                        templateProductId,
                        corpUserChat: corpChatUserList.map(item => {
                            return {
                                label: `${item.name}（${item.corpName}）`,
                                value: item.id,
                                name: item.name,
                                corpName: item.corpName,
                                corpId: item.corpId,
                                corpUserId: item.corpUserId
                            }
                        }),
                        corpUsers: corpUsers?.map(item => {
                            return {
                                name: item.corpUserName,
                                corpUserId: item.corpUserId,
                                corpName: item.corpName,
                                corpId: item.corpId
                            }
                        }),
                        robotCorpUsers: corpRobots?.map(item => {
                            return {
                                name: item.corpUserName,
                                corpUserId: item.corpUserId,
                                corpName: item.corpName,
                                corpId: item.corpId
                            }
                        }),
                        strategyDTO: {
                            ...data
                        }
                    }
                    console.log('------------->', newSettings)
                    setSettings(newSettings)
                }
            })
        } else {
            const task = localStorage.getItem('TASK_GROUP_CHAT_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 + '' })))
        })
        getCorpAllList.run({})
    }, [])


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

    const preview = () => {
        const { corpUserChat, corpUsers, robotCorpUsers, bizType, platform, templateProductId } = settings
        if (!corpUserChat || corpUserChat?.length === 0) {
            message.error('请先选择群主号')
            return
        }
        if (!corpUsers || corpUsers?.length === 0) {
            message.error('请先选择客服号')
            return
        }
        // if (!robotCorpUsers || robotCorpUsers?.length === 0) {
        //     message.error('请先选择机器人号')
        //     return
        // }
        if (!bizType) {
            message.error('请选择业务类型')
            return
        }
        if (!platform) {
            message.error('请选择书城')
            return
        }
        if (!(settings?.strategyDTO && Object.keys(settings?.strategyDTO).length > 0)) {
            message.error('请先设置策略')
            return
        }
        if (!settings?.strategyDTO?.strategyList?.every(item => item?.groupObjectList?.length > 0)) {
            message.error('请先设置群配置')
            return
        }
        const dto = settings.strategyDTO.strategyList.reduce((pre, cur, strategyIndex) => {
            const { groupObjectList, id: strategyId, ...its } = cur
            groupObjectList.forEach((item, index) => {
                pre.push({
                    ...item,
                    ...its,
                    strategyId,
                    taskId: item.id,
                    strategyIndex,
                    goIndex: index,
                    strategyData: {
                        ...its,
                        id: strategyId
                    },
                    groupObjectData: item,
                    taskName: settings.strategyDTO.taskName
                })
            })
            return pre
        }, [])
        let id = 1
        const list = corpUsers.reduce((pre, corpUser) => {
            return pre.concat(dto.map(item => {
                return {
                    ...item,
                    corpUser,
                    corpUserChat,
                    robotCorpUsers,
                    bizType,
                    platform,
                    templateProductId,
                    id: id++
                }
            }))
        }, [])
        setPreviewData(list)
        setPreviewDataOld(list)
        setEstimateNumDto({})
    }

    // 重置表格
    const onPreviewReset = () => {
        setPreviewData([])
        setPreviewDataOld([])
    }

    const tableSearch = useCallback((values) => {
        console.log(values)
        const obj = removeEmptyValues(values)
        if (Object.keys(obj).length) {
            const newPreviewData = previewDataOld.filter(item => {
                const weChatAppid = item?.weChatAppid?.split('_')?.[1]
                return (obj?.mpAccountIds?.length > 0 ? obj.mpAccountIds.includes(weChatAppid) : true) &&
                    (obj?.corpId ? item?.corpUser?.corpId === obj?.corpId : true) &&
                    (obj?.corpUserIds?.length > 0 ? obj?.corpUserIds?.map(item => item.corpUserId)?.includes(item?.corpUser?.corpUserId) : true) &&
                    (obj?.groupCorpId ? item?.corpUserChat?.map(item => item.corpId)?.includes(obj?.groupCorpId) : true) &&
                    (obj?.robotCorpId ? item?.robotCorpUsers?.[0]?.corpId === obj?.robotCorpId : true) &&
                    (obj?.groupObjectName ? item?.groupObjectName?.includes(obj?.groupObjectName) : true)
            })
            setPreviewData(newPreviewData)
        } else {
            setPreviewData(previewDataOld)
        }
    }, [previewDataOld, previewData])

    //获取拉群预估人数
    const getPullGroupEstimateNumFn = useCallback((p?: Record<string, any>) => {
        let params: Record<string, any> = {}
        if (p) {
            params = p
        } else {
            const { bizType, platform, templateProductId, corpUsers, corpUserChat, robotCorpUsers, strategyDTO } = settings
            params ={
                bizType,
                platform,
                templateProductId,
                corpChatUserIds: corpUserChat.map(item => item.value),
                corpRobots: robotCorpUsers?.map(item => ({
                    corpId: item.corpId,
                    corpUserId: item.corpUserId,
                    corpUserName: item.name,
                    corpName: item.corpName
                })),
                corpUsers: corpUsers.map(item => ({
                    corpId: item.corpId,
                    corpUserId: item.corpUserId,
                    corpUserName: item.name,
                    corpName: item.corpName
                })),
                strategyList: strategyDTO.strategyList.map(({ groupObjectList, ...item }) => {
                    return {
                        ...item,
                        taskDetail: groupObjectList.map(go => {

                            const { externalUserType, externalUserFilter, groupObjectName, tagDTO, weChatAppid, ...itgo } = go
                            const detail = {
                                ...itgo,
                                groupName: groupObjectName,
                                msgTagDTO: tagDTO
                            }
                            if (externalUserType === 'specify') {
                                detail.externalUserFilter = {
                                    configName: externalUserFilter.configName,
                                    ...externalUserFilter.configContent
                                }
                            }
                            if (weChatAppid) {
                                detail.mpAccountId = weChatAppid.split('_')[1]
                            }
                            return detail
                        })
                    }
                })
            }
        }

        getPullGroupEstimateNum.run(params).then(res => {
            if (res?.data) {
                setEstimateNumDto(dto => ({ ...dto, ...res.data }))
            }
        })
    }, [settings])

    //提交任务
    const onSubmit = (values: any) => {
        const { bizType, platform, templateProductId, corpUsers, corpUserChat, robotCorpUsers, strategyDTO } = settings
        console.log('--->', values)
        const params: { [x: string]: any } = {
            ...values,
            taskName: values.projectName,
            bizType,
            platform,
            templateProductId,
            corpChatUserIds: corpUserChat.map(item => item.value),
            corpRobots: robotCorpUsers?.map(item => ({
                corpId: item.corpId,
                corpUserId: item.corpUserId,
                corpUserName: item.name,
                corpName: item.corpName
            })),
            corpUsers: corpUsers.map(item => ({
                corpId: item.corpId,
                corpUserId: item.corpUserId,
                corpUserName: item.name,
                corpName: item.corpName
            })),
            strategyList: strategyDTO.strategyList.map(({ groupObjectList, ...item }) => {
                return {
                    ...item,
                    taskDetail: groupObjectList.map(go => {

                        const { externalUserType, externalUserFilter, groupObjectName, tagDTO, weChatAppid, ...itgo } = go
                        const detail = {
                            ...itgo,
                            groupName: groupObjectName,
                            msgTagDTO: tagDTO
                        }
                        if (externalUserType === 'specify') {
                            detail.externalUserFilter = {
                                configName: externalUserFilter.configName,
                                ...externalUserFilter.configContent
                            }
                        }
                        if (weChatAppid) {
                            detail.mpAccountId = weChatAppid.split('_')[1]
                        }
                        return detail
                    })
                }
            })
        }
        delete params?.projectName
        console.log('提交参数--->', params)
        if (projectId) {
            params.projectId = projectId
            updateGroupTask.run(params).then(res => {
                console.log(res)
                if (res?.data) {
                    message.success('修改提交成功')
                    setProjectId(undefined)
                    sessionStorage.setItem('CAMPCORP_PG', values?.projectName)
                    navigate('/weComTask/groupChat/taskList')
                }
            })
        } else {
            addPullGroupTask.run(params).then(res => {
                console.log(res)
                if (res?.data) {
                    modal.success({
                        content: '任务提交成功',
                        styles: { body: { fontWeight: 700 } },
                        okText: '跳转任务列表',
                        closable: true,
                        onOk: () => {
                            sessionStorage.setItem('CAMPCORP_PG', values?.projectName)
                            navigate('/weComTask/groupChat/taskList')
                        },
                        onCancel: () => {
                            setSubVisible(false)
                        }
                    })
                }
            })
        }
    }

    return <div className={style.create}>
        <Spin spinning={getCreateDetails.loading}>
            <Card title={<strong>{projectId ? getCreateDetails?.data?.data?.taskName + '任务编辑' : ''}配置区</strong>} className={`${style.card} ${style.config}`}>
                <Space wrap>
                    <Space.Compact>
                        <Button>群主号</Button>
                        <SelectGroupLeader
                            value={settings?.corpUserChat}
                            onChange={(corpUserChat) => {
                                setSettings({ ...settings, corpUserChat: corpUserChat, corpUsers: undefined, robotCorpUsers: undefined })
                                onPreviewReset()
                            }}
                        />
                    </Space.Compact>

                    {settings?.corpUserChat?.length > 0 && <>
                        <Space.Compact>
                            <Button>客服号</Button>
                            <SelectCorpUserChatUser
                                placeholder="请选择客服号"
                                bindType={1}
                                corpUserChatIds={settings?.corpUserChat?.map(item => item.value)}
                                value={settings?.corpUsers}
                                onChange={(value) => {
                                    setSettings({
                                        ...settings,
                                        corpUsers: value,
                                    })
                                    onPreviewReset()
                                }}
                            />
                        </Space.Compact>
                        <Space.Compact>
                            <Button>机器人号</Button>
                            <SelectCorpUserChatUser
                                placeholder="请选择机器人号"
                                bindType={2}
                                corpUserChatIds={settings?.corpUserChat?.map(item => item.value)}
                                value={settings?.robotCorpUsers}
                                onChange={(value) => {
                                    setSettings({
                                        ...settings,
                                        robotCorpUsers: value,
                                    })
                                    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}>
                        <DispatchGroupChatCreate.Provider
                            value={{
                                settings, setSettings,
                                onPreviewReset,
                                bookPlatForm, bookList
                            }}
                        >
                            {/* 策略配置 */}
                            <Strategy />
                            {/* 进群对象 */}
                            <GroupUser />
                        </DispatchGroupChatCreate.Provider>
                    </div>
                </div>

                <Space className={style.bts} wrap>
                    <Button icon={<SaveOutlined />} onClick={severBd}>存为预设</Button>
                    <Popconfirm
                        title="确定清空?"
                        onConfirm={() => {
                            setSettings(undefined)
                            onPreviewReset()
                            localStorage.removeItem('TASK_GROUP_CHAT_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={() => {
                setSubVisible(true)
            }}>提交</Button> : undefined}
        >
            {previewDataOld?.length > 0 ? <div style={{ minHeight: 300 }}>
                <Form
                    layout={'inline'}
                    onFinish={tableSearch}
                >
                    <Form.Item label={<strong>公众号</strong>} style={{ marginBottom: 10 }} 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>
                    <Form.Item label={<strong>客服号主体</strong>} style={{ marginBottom: 10 }} name="corpId">
                        <Select
                            showSearch
                            style={{ minWidth: 110 }}
                            maxTagCount={1}
                            placeholder="请选择主体"
                            filterOption={(input, option) =>
                                ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                            }
                            allowClear
                            options={getCorpAllList?.data?.data?.map((item: any) => ({ label: item.corpName, value: item.corpId }))}
                        />
                    </Form.Item>

                    <Space.Compact>
                        <Button>客服号</Button>
                        <Form.Item name="corpUserIds" style={{ marginBottom: 10 }}>
                            <SelectCorpUser placeholder="请选择客服号" />
                        </Form.Item>
                    </Space.Compact>
                    <Form.Item label={<strong>群主号主体</strong>} style={{ marginBottom: 10 }} name="groupCorpId">
                        <Select
                            showSearch
                            style={{ minWidth: 110 }}
                            maxTagCount={1}
                            placeholder="请选择主体"
                            filterOption={(input, option) =>
                                ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                            }
                            allowClear
                            options={getCorpAllList?.data?.data?.map((item: any) => ({ label: item.corpName, value: item.corpId }))}
                        />
                    </Form.Item>
                    <Form.Item label={<strong>机器人号主体</strong>} style={{ marginBottom: 10 }} name="robotCorpId">
                        <Select
                            showSearch
                            style={{ minWidth: 110 }}
                            maxTagCount={1}
                            placeholder="请选择主体"
                            filterOption={(input, option) =>
                                ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                            }
                            allowClear
                            options={getCorpAllList?.data?.data?.map((item: any) => ({ label: item.corpName, value: item.corpId }))}
                        />
                    </Form.Item>
                    <Form.Item label={<strong>群配置名称</strong>} style={{ marginBottom: 10 }} name="groupObjectName">
                        <Input placeholder="请输入群配置名称" allowClear />
                    </Form.Item>
                    <Form.Item style={{ marginBottom: 10 }}>
                        <Space>
                            <Button htmlType="reset">重置</Button>
                            <Button type="primary" htmlType='submit'>搜索</Button>
                            <Popconfirm
                                title="获取全部预计人数"
                                description="获取全部预计人数会很慢，确定获取全部预计人数吗？"
                                onConfirm={() => getPullGroupEstimateNumFn()}
                            >
                                <Button type="dashed" loading={getPullGroupEstimateNum.loading}>全部预计人数</Button>
                            </Popconfirm>
                        </Space>
                    </Form.Item>
                </Form>
                <Table
                    dataSource={previewData}
                    columns={PreviewColumns(bookPlatForm, bookList, estimateNumDto, getPullGroupEstimateNumFn)}
                    rowKey={'id'}
                    bordered={true}
                    scroll={{ y: 550 }}
                    loading={getPullGroupEstimateNum.loading}
                    pagination={{
                        showTotal(total, range) {
                            return `共 ${total} 条记录 第 ${range[0]}-${range[1]} 条`
                        },
                    }}
                />
            </div> : <div style={{ minHeight: 400, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                <Empty description="请先完成模块配置后，再预览" />
            </div>}
        </Card>


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

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