import { Modal, Spin, Typography } from 'antd';
import React, { useEffect, useState } from 'react';
import '../../tencentAdPutIn/index.less';
import './index.less';
import { getCorpDepartmentListApi, getWechatPagesCsgroupUserApi, updateCustomerServiceGroupApi } from '@/services/adqV3/global';
import { CloseOutlined, UserOutlined } from '@ant-design/icons';
import { useAjax } from '@/Hook/useAjax';
import { DataNode } from 'antd/lib/tree';
import NTree from './nTree';

interface IProps {
    adAccountId: number;
    data: {
        corpName: string;
        tencentCorpId: string;
        groupId: number;
        groupName: string;
        userInfoList: { userId: string, userName: string, msg: string, state: 0 | 1 }[]
    };
    visible: boolean;
    onClose?: () => void;
    onChange?: () => void;
}

// 定义接口
interface Department {
    corpId: string;
    departmentId: number;
    name: string;
    parentid: number;
    orderIn: number;
    createTime: string;
    children: Department[];
}

const updateTreeData = (list: DataNode[], key: React.Key, children: DataNode[], childrenLen?: number): DataNode[] => list.map(node => {
    if (node.key === key) {
        if (childrenLen && node?.children) {
            return { ...node, children: [...node.children, ...children,] };
        }
        return {
            ...node,
            children,
        };
    }
    if (node.children) {
        return {
            ...node,
            children: updateTreeData(node.children, key, children, childrenLen),
        };
    }
    return node;
});

/**
 * 初始化数据
 * @param data 
 * @returns 
 */
const getInitializationData = (data: Department[]): DataNode[] => {
    return data.map((item: Department) => {
        return { title: item.name, key: item.departmentId, checkable: false, children: item?.children?.length ? getInitializationData(item.children) : [] }
    })
}

/**
 * 修改客服组
 * @returns 
 */
const SettingsEnterprise: React.FC<IProps> = ({ adAccountId, data, visible, onClose, onChange }) => {

    /*********************************/
    const [treeData, setTreeData] = useState<DataNode[]>([]);
    const [loading, setLoading] = useState<boolean>(false);
    const [userInfoList, setUserInfoList] = useState<{ userId: string, userName: string, state?: 0 | 1, msg?: string }[]>(data.userInfoList || [])

    const getCorpDepartmentList = useAjax((params) => getCorpDepartmentListApi(params))
    const updateCustomerServiceGroup = useAjax((params) => updateCustomerServiceGroupApi(params))
    /*********************************/

    useEffect(() => {
        const getData = async () => {
            try {
                const res = await getCorpDepartmentList.run({ corpName: data.corpName })
                let dataTree: DataNode[] = []
                if (res?.length > 0) {
                    dataTree = getInitializationData(res)
                }
                setLoading(true)
                const list = await getWechatPagesCsgroupUserApi({
                    adAccountId,
                    tencentCorpId: data.tencentCorpId,
                    corpName: data.corpName
                })
                if (list.data?.length) {
                    dataTree.push(...list.data.map((item: any) => ({ title: item.userName, key: item.userId, isLeaf: true })))
                }
                setLoading(false)
                setTreeData(dataTree)
            } catch (error) {
                console.error(error)
            }
        }
        if (adAccountId)
            getData()
    }, [adAccountId])

    const handleOk = () => {

        updateCustomerServiceGroup.run({
            adAccountId,
            tencentCorpId: data.tencentCorpId,
            groupId: data.groupId,
            groupName: data.groupName,
            userIdList: userInfoList.map(item => item.userId)
        }).then((res) => {
            if (res) {
                onChange?.()
            }
        })
    }

    const onLoadData = ({ key, children }: any) => {
        return new Promise<void>(resolve => {
            getWechatPagesCsgroupUserApi({
                adAccountId,
                tencentCorpId: data.tencentCorpId,
                corpName: data.corpName,
                departmentId: key
            }).then((res) => {
                setTreeData(origin =>
                    updateTreeData(origin, key, res.data.map((item: any) => ({ title: item.userName, key: item.userId, isLeaf: true })), children?.length),
                );
                resolve();
            })
        });
    }


    return <Modal
        title={<strong>设置客服组</strong>}
        open={visible}
        onCancel={onClose}
        onOk={handleOk}
        className='modalResetCss'
        width={750}
        bodyStyle={{ padding: 0 }}
        confirmLoading={updateCustomerServiceGroup.loading}
    >
        <Spin spinning={getCorpDepartmentList.loading || loading}>
            <div className='settingsEnterprise'>
                <div className='settingsEnterprise-left'>
                    <div>
                        <NTree
                            treeData={treeData}
                            loadData={onLoadData}
                            onSelect={(selectedKeys) => {
                                console.log('selected', selectedKeys);
                                setUserInfoList(selectedKeys.map((item: any) => ({ userId: item.value, userName: item.label, ...item })))
                            }}
                            selectedKeys={userInfoList.map(({ userId, userName, ...item }) => ({ value: userId, label: userName, ...item }))}
                        />
                    </div>
                </div>
                <div className='settingsEnterprise-right'>
                    <div>
                        <div className='settingsEnterprise-right-title'>已选 <span>{userInfoList?.length || 0}</span> 个客服</div>
                        <div className='settingsEnterprise-right-list'>
                            {userInfoList.map(item => {
                                return <div className='list-item' key={item.userId}>
                                    <div style={item?.state === 1 ? { color: 'red' } : {}}>
                                        <UserOutlined />
                                        <Typography.Text ellipsis style={item?.state === 1 ? { color: 'red' } : {}}>{item?.userName || item.msg || item.userId}</Typography.Text>
                                    </div>
                                    <a onClick={() => {
                                        setUserInfoList(userInfoList.filter(item2 => item2.userId !== item.userId))
                                    }}><CloseOutlined /></a>
                                </div>
                            })}
                        </div>
                    </div>
                </div>
            </div>
        </Spin>
    </Modal>
};

export default React.memo(SettingsEnterprise);