import { App, Button, Input, Modal, Select, Space, Table, Typography } from "antd";
import { CorpUserProps } from "./selectCorpUserGroup";
import { useEffect, useState } from "react";
import style from '../../components/selectExternalAccount/index.less';
import { CheckOutlined, SearchOutlined, CloseOutlined } from '@ant-design/icons';
import React from "react";
import { useAjax } from "@/Hook/useAjax";
import { getAdAccountAllOfMember } from "@/API/global";
import { getCorpUserApi, getGroupListApi } from "../../API/corpUserManage";
import { WeTableSelectConfig } from "./tableConfig";
import { getBindMpListApi } from "../../API/corpUserAssign";
const { Text, Title } = Typography;


interface Props {
    visible?: boolean;
    onClose?: () => void;
    value?: TASK_CREATE.CorpUserGroupProps[];
    onChange?: (value?: TASK_CREATE.CorpUserGroupProps[]) => void;
    disabled?: boolean;
}
const SelectCorpUserGroupModal: React.FC<Props> = ({ visible, onClose, value, onChange, disabled }) => {

    /*****************************************/
    const { message } = App.useApp()
    const [data, setData] = useState<TASK_CREATE.CorpUserGroupProps[]>(value)
    const [selectAdz, setSelectAdz] = useState<number>(1)   // 选择广告主

    const [queryForm, setQueryForm] = useState<CORP_USER_ASSIGN_API.GetCorpUserProps>({ pageNum: 1, pageSize: 20, stopUse: false, status: 1, corpIds: value?.[0]?.corpUsers?.[0]?.corpId as any })
    const [queryFormNew, setQueryFormNew] = useState<CORP_USER_ASSIGN_API.GetCorpUserProps>({ pageNum: 1, pageSize: 20, stopUse: false, status: 1, corpIds: value?.[0]?.corpUsers?.[0]?.corpId as any })

    const allOfMember = useAjax(() => getAdAccountAllOfMember())
    const getCorpUser = useAjax((params) => getCorpUserApi(params))
    const getGroupList = useAjax(() => getGroupListApi())
    const getBindMpList = useAjax(() => getBindMpListApi())
    /*****************************************/

    useEffect(() => {
        allOfMember.run()
        getGroupList.run()
        getBindMpList.run()
    }, [])

    useEffect(() => {
        const params = { ...queryForm }
        if (params?.corpIds) {
            params.corpIds = (params.corpIds as any).split(/[\s,，\n]/).filter((item: string) => item)
        } else {
            delete params?.corpIds
        }
        if (params?.corpUserIds) {
            params.corpUserIds = (params.corpUserIds as any).split(/[\s,，\n]/).filter((item: string) => item)
        } else {
            delete params?.corpUserIds
        }
        getCorpUser.run(params)
    }, [queryForm])

    const handleOk = () => {
        if (data?.every(item => item?.corpUsers?.length)) {
            onChange?.(data)
        } else {
            message.error('请选择客服号')
        }
    }

    const handleSelectAdz = (value: number, data: TASK_CREATE.CorpUserGroupProps[], isSd: boolean) => {
        if (value === selectAdz && isSd) {
            return
        }
        const nowCorpUsers = data[value - 1]?.corpUsers
        const newQueryForm: any = { ...queryForm }
        if (nowCorpUsers?.length > 0) {
            newQueryForm.corpIds = nowCorpUsers[0]?.corpId
            if (nowCorpUsers?.[0]?.mpAccountId) {
                newQueryForm.mpAccountId = nowCorpUsers[0]?.mpAccountId
            } else {
                delete newQueryForm?.mpAccountId
            }
        } else {
            delete newQueryForm?.corpIds
            delete newQueryForm?.mpAccountId
        }
        setQueryForm(newQueryForm)
        setQueryFormNew(newQueryForm)
        setSelectAdz(value)
    }

    return <Modal
        title={<strong>选择客服号</strong>}
        open={visible}
        onCancel={onClose}
        onOk={handleOk}
        width={1100}
        className={`${style.SelectPackage}`}
        okButtonProps={{ disabled }}
        styles={{
            body: {
                padding: '0 10px 0 10px'
            }
        }}
    >
        <div className={style.content}>
            <div className={style.left} style={{ width: 180 }}>
                <div className={style.leftTitle}>
                    <h4 className={style.title}>客服组</h4>
                    <a onClick={() => {
                        setData(d => ([...d, { corpUsers: [] }]))
                    }}>新增组</a>
                </div>
                <div className={style.accountIdList}>
                    {data?.map((item, index) => {
                        const corpUserList = data[index]?.corpUsers || []
                        return <div key={index} onClick={() => { handleSelectAdz(index + 1, data, true) }} className={`${style.accItem} ${selectAdz === index + 1 && style.select} `}>
                            <div><Text ellipsis={{ tooltip: true }}>客服组{index + 1}</Text></div>
                            {corpUserList?.length > 0 && <CheckOutlined style={{ color: '#1890ff' }} />}
                        </div>
                    })}
                </div>
            </div>
            <div className={style.right}>
                <Space style={{ marginBottom: 10 }} align="end" size={5} wrap>
                    <Input style={{ width: 150 }} onChange={(e) => setQueryFormNew({ ...queryFormNew, corpIds: e.target.value as any })} value={queryFormNew?.corpIds} placeholder="企微ID（多个，,空格换行）" allowClear />
                    <Input style={{ width: 150 }} onChange={(e) => setQueryFormNew({ ...queryFormNew, corpUserName: e.target.value as any })} value={queryFormNew?.corpUserName} placeholder="客服号名称" allowClear />
                    <Input style={{ width: 150 }} onChange={(e) => setQueryFormNew({ ...queryFormNew, corpUserIds: e.target.value as any })} value={queryFormNew?.corpUserIds} placeholder="客服ID（多个，,空格换行）" allowClear />
                    <Select
                        value={queryFormNew?.groupId}
                        onChange={(e) => setQueryFormNew({ ...queryFormNew, groupId: e })}
                        showSearch
                        style={{ width: 100 }}
                        placeholder="分组"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                        }
                        allowClear
                        options={getGroupList?.data?.data?.map((item: any) => ({ label: item.groupName, value: item.groupId }))}
                    />
                    <Select
                        value={queryFormNew?.operUserId}
                        onChange={(e) => setQueryFormNew({ ...queryFormNew, operUserId: e })}
                        showSearch
                        style={{ width: 100 }}
                        placeholder="运营"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                        }
                        allowClear
                        options={allOfMember?.data?.data?.map((item: any) => ({ label: item.nickname, value: item.userId }))}
                    />
                    <Select
                        value={queryFormNew?.mpAccountId}
                        onChange={(e) => setQueryFormNew({ ...queryFormNew, mpAccountId: e })}
                        showSearch
                        style={{ width: 100 }}
                        placeholder="公众号"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                        }
                        allowClear
                        options={getBindMpList?.data?.data?.map((item: any) => ({ label: item.name, value: item.id }))}
                    />
                    <Select
                        value={queryFormNew?.groupOwner}
                        onChange={(e) => setQueryFormNew({ ...queryFormNew, groupOwner: e })}
                        showSearch
                        style={{ width: 100 }}
                        placeholder="是否群主号"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                        }
                        allowClear
                        options={[{ label: '是', value: 1 }, { label: '否', value: 0 }]}
                    />
                    <Select
                        value={queryFormNew?.machine}
                        onChange={(e) => setQueryFormNew({ ...queryFormNew, machine: e })}
                        showSearch
                        style={{ width: 100 }}
                        placeholder="是否机器号"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                        }
                        allowClear
                        options={[{ label: '是', value: 1 }, { label: '否', value: 0 }]}
                    />
                    <Button type="primary" onClick={() => {
                        setQueryForm({ ...queryFormNew, pageNum: 1 })
                    }} loading={getCorpUser.loading} icon={<SearchOutlined />}>搜索</Button>
                </Space>

                <Table
                    columns={WeTableSelectConfig()}
                    dataSource={getCorpUser?.data?.data?.records}
                    size='small'
                    scroll={{ y: 300 }}
                    rowKey={'id'}
                    loading={getCorpUser.loading}
                    pagination={{
                        current: getCorpUser?.data?.data?.current || 1,
                        pageSize: getCorpUser?.data?.data?.size || 20,
                        total: getCorpUser?.data?.data?.total,
                        showTotal: (total) => `共 ${total} 条数据`,
                        showSizeChanger: true
                    }}
                    rowSelection={{
                        type: 'checkbox',
                        selectedRowKeys: data?.[selectAdz - 1]?.corpUsers?.map(item => item.id),
                        getCheckboxProps: (record: any) => ({
                            disabled: data.filter((_, i) => i !== selectAdz - 1)?.map(item => item.corpUsers).flat(1)?.map(item => item.id).includes(record.id) ||
                                (data?.[selectAdz - 1]?.corpUsers?.length > 0 ? data?.[selectAdz - 1]?.corpUsers?.[0]?.corpId !== record.corpId || (data?.[selectAdz - 1]?.corpUsers?.[0]?.mpAccountId ? data?.[selectAdz - 1]?.corpUsers?.[0]?.mpAccountId !== record.mpAccountId : record.mpAccountId) : false)
                        }),
                        onSelect: (record: { id: string }, selected: boolean) => {
                            const newData = JSON.parse(JSON.stringify(data))
                            let dataIten = newData[selectAdz - 1]?.corpUsers || []
                            if (selected) {
                                dataIten.push({ ...record })
                            } else {
                                dataIten = dataIten.filter((item: { id: string }) => item.id !== record.id)
                            }
                            newData[selectAdz - 1].corpUsers = dataIten
                            setData(newData)
                        },
                        onSelectAll: (selected: boolean, _, changeRows: { id: string, corpId: string, mpAccountId?: string }[]) => {
                            const newData = JSON.parse(JSON.stringify(data))
                            const dataIten = newData[selectAdz - 1]?.corpUsers || []
                            if (selected) {
                                const newSelectAccData = [...dataIten]
                                if (newSelectAccData?.length === 0) {
                                    const { mpAccountId, corpId } = changeRows[0]
                                    changeRows = changeRows.filter(item => item.corpId === corpId && item?.mpAccountId === mpAccountId)
                                }
                                changeRows.forEach((item: { id: string }) => {
                                    const index = newSelectAccData.findIndex((ite: { id: string }) => {
                                        return ite.id === item.id
                                    })
                                    if (index === -1) {
                                        const data: any = { ...item }
                                        newSelectAccData.push(data)
                                    }
                                })
                                newData[selectAdz - 1].corpUsers = newSelectAccData
                            } else {
                                const newSelectAccData = dataIten.filter((item: { id: string }) => {
                                    const index = changeRows.findIndex((ite: { id: string }) => ite.id === item.id)
                                    if (index !== -1) {
                                        return false
                                    } else {
                                        return true
                                    }
                                })
                                newData[selectAdz - 1].corpUsers = newSelectAccData
                            }
                            setData(newData)
                        }
                    }}
                    onChange={(pagination) => {
                        setQueryForm({ ...queryForm, pageNum: pagination.current || 1, pageSize: pagination.pageSize || 20 })
                    }}
                />
            </div>

            <div className={style.center}>
                <div style={{ margin: '0 0 5px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <Title level={5} style={{ margin: 0 }}>已选：{data[selectAdz - 1]?.corpUsers?.length || 0}</Title>
                    {data.length > 1 && <a style={{ color: 'red' }} onClick={() => {
                        const newData = data.filter((_, index) => index !== selectAdz - 1)
                        setData(newData)
                        if (selectAdz > 1) {
                            handleSelectAdz(selectAdz - 1, newData, false)
                        } else {
                            handleSelectAdz(1, newData, false)
                        }
                    }}>删除组</a>}
                </div>
                <div className={style.select_content}>
                    {data[selectAdz - 1]?.corpUsers?.map(item => <div key={item.corpUserId}>
                        <Text ellipsis={{ tooltip: true }} className={style.marketingAssetName}>{item.name}（{item?.corpName}）</Text>
                        <CloseOutlined className={style.close} onClick={() => {
                            let newData = JSON.parse(JSON.stringify(data))
                            newData[selectAdz - 1].corpUsers = newData[selectAdz - 1]?.corpUsers?.filter((i: any) => i?.corpUserId !== item.corpUserId)
                            setData(newData)
                        }} />
                    </div>)}
                </div>
            </div>
        </div>
    </Modal>
}

export default React.memo(SelectCorpUserGroupModal);