import { Modal, Spin, Typography } from 'antd';
import React, { useEffect, useState } from 'react';
import '../../../../../tencentAdPutIn/index.less';
import '../../index.less';
import { getCorpDepartmentListApi, getWechatPagesCsgroupUserApi } 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;
    };
    value?: { userId: string, userName: string }[]
    visible?: boolean;
    onClose?: () => void;
    onChange?: (value?: { userId: string, userName: string }[]) => 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, value, visible, onClose, onChange }) => {

    /*********************************/
    const [treeData, setTreeData] = useState<DataNode[]>([]);
    const [loading, setLoading] = useState<boolean>(false);
    const [userInfoList, setUserInfoList] = useState<{ userId: string, userName: string }[]>(value || [])

    const getCorpDepartmentList = useAjax((params) => getCorpDepartmentListApi(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 = () => {
        onChange?.(userInfoList);
    }

    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 }}
    >
        <Spin spinning={getCorpDepartmentList.loading || loading}>
            <div className='settingsEnterprise'>
                <div className='settingsEnterprise-left'>
                    <div>
                        <NTree
                            treeData={treeData}
                            loadData={onLoadData}
                            onSelect={(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>
                                        <UserOutlined />
                                        <Typography.Text ellipsis>{item?.userName || 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);