import { Avatar, Button, Checkbox, Input, message, Modal, Select, Space, Spin, Table, Tag, Tree, TreeDataNode, TreeProps, Typography } from "antd";
import React, { useEffect, useMemo, useState } from "react";
import style from '../selectExternalAccount/index.less'
import { CheckOutlined, UserOutlined, CloseOutlined } from '@ant-design/icons'
import { useAjax } from "@/Hook/useAjax";
import { getTagGroupListApi } from "../../API/global";
const { Text, Title } = Typography;

const getParentKey = (key: React.Key, tree: TreeDataNode[]): React.Key => {
    let parentKey: React.Key;
    for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
            if (node.children.some((item) => item.key === key)) {
                parentKey = node.key;
            } else if (getParentKey(key, node.children)) {
                parentKey = getParentKey(key, node.children);
            }
        }
    }
    return parentKey!;
};
/**
 * 朋友圈企业标签选择
 * @param param0 
 * @returns 
 */
const SelectCwTag: React.FC<EXTERNAL_ACCOUNT_PROPS.SelectExternalAccountProps> = ({ corpUsers, visible, onClose, onChange }) => {

    /***************************************/
    const [data, setData] = useState<TASK_CREATE.corpUsersProps[]>(corpUsers)
    const [selectAdz, setSelectAdz] = useState<number>(1)   // 选择广告主
    const [queryForm, setQueryForm] = useState<any>({ pageNum: 1, pageSize: 200, corpId: corpUsers?.[selectAdz - 1]?.corpId })
    const [dataList, setDataList] = useState<{ key: React.Key; title: string }[]>([]);
    const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
    const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
    const [tagsList, setTagsList] = useState<TreeDataNode[]>([]);
    const [searchValue, setSearchValue] = useState<string>('');
    const [groupAll, setGroupAll] = useState<boolean>(true)

    const getTagGroupList = useAjax((params) => getTagGroupListApi(params))
    /***************************************/

    useEffect(() => {
        getTagGroupList.run({ ...queryForm }).then(res => {
            const tagsList = res?.data?.records?.map((item: { corpExternalTagList: { tagName: any; tagId: any }[]; tagGroupName: any; tagGroupId: any }) => {
                let children = item?.corpExternalTagList?.map((c: { tagName: any; tagId: any }) => ({ title: c?.tagName, key: c?.tagId, value: c?.tagId }))
                return { title: item?.tagGroupName, value: 'group' + '_' + item?.tagGroupId, key: 'group' + '_' + item?.tagGroupId, children }
            }) || []
            setTagsList(tagsList)

            const dataList: { key: React.Key; title: string }[] = [];
            const generateList = (data: TreeDataNode[]) => {
                for (let i = 0; i < data.length; i++) {
                    const node = data[i];
                    const { key, title } = node;
                    dataList.push({ key, title: title as string });
                    if (node.children) {
                        generateList(node.children);
                    }
                }
            };
            generateList(tagsList)
            setDataList(dataList)
        }).catch(() => {
            setDataList([])
        })
    }, [queryForm])

    const handleSelectAdz = (value: number) => {
        if (value === selectAdz) {
            return
        }
        setSelectAdz(value)
        setQueryForm(data => data?.corpId === corpUsers?.[value - 1]?.corpId ? data : { ...queryForm, corpId: corpUsers?.[selectAdz - 1]?.corpId })
    }

    const handleOk = () => {
        onChange?.(data)
        // if (data?.every(item => item?.friendsTagContent?.length)) {
            
        // } else {
        //     message.error('请选择企微标签')
        // }
    }

    const onExpand = (newExpandedKeys: React.Key[]) => {
        setExpandedKeys(newExpandedKeys);
        setAutoExpandParent(false);
    };

    const onSearch = (value?: string) => {
        const newExpandedKeys = dataList.map((item) => {
            if (value && item.title.indexOf(value) > -1) {
                return getParentKey(item.key, tagsList);
            }
            return null;
        }).filter((item, i, self): item is React.Key => !!(item && self.indexOf(item) === i));
        setExpandedKeys(newExpandedKeys);
        setSearchValue(value || '')
        setAutoExpandParent(true)
    }

    const onCheck: TreeProps['onCheck'] = (_, info) => {
        const newData = JSON.parse(JSON.stringify(data))
        newData[selectAdz - 1].friendsTagContent = info.checkedNodes?.filter(item => !item?.children)
        setData(newData)
    };

    const treeData = useMemo(() => {
        if (!searchValue) return tagsList;
        const loop = (data: TreeDataNode[]): TreeDataNode[] => data.reduce((pre, cur) => {
            const strTitle = cur.title as string;
            const index = strTitle.indexOf(searchValue);
            if (index > -1) {
                const beforeStr = strTitle.substring(0, index);
                const afterStr = strTitle.slice(index + searchValue.length);
                const title = <span>
                    {beforeStr}
                    <span className={style['site-tree-search-value']}>{searchValue}</span>
                    {afterStr}
                </span>;
                if (!groupAll) {
                    pre.push({ ...cur, title })
                } else {
                    if (cur.children) {
                        let children = loop(cur.children)
                        pre.push({ ...cur, title, children })
                    } else {
                        pre.push({ ...cur, title })
                    }
                }
            } else {
                if (cur.children) {
                    let children = loop(cur.children)
                    if (children?.length > 0) {
                        pre.push({ ...cur, children })
                    }
                }
            }
            return pre
        }, [] as TreeDataNode[])

        return loop(tagsList);
    }, [searchValue, groupAll, tagsList]);

    return <Modal
        title={<strong>朋友圈企微标签选择</strong>}
        open={visible}
        onCancel={onClose}
        onOk={handleOk}
        width={1000}
        className={`${style.SelectPackage}`}
        styles={{
            body: {
                padding: '0 10px 0 10px'
            }
        }}
    >
        <div className={style.content}>
            <div className={style.left}>
                <h4 className={style.title}>客服号</h4>
                <div className={style.accountIdList}>
                    {corpUsers?.map((item, index) => {
                        const friendsTagContent = data[index]?.friendsTagContent || []
                        return <div key={index} onClick={() => { handleSelectAdz(index + 1) }} className={`${style.accItem} ${selectAdz === index + 1 && style.select} `}>
                            <div><Text ellipsis={{ tooltip: true }}>{item?.name}（{item.corpName}）</Text></div>
                            {friendsTagContent?.length > 0 && <CheckOutlined style={{ color: '#1890ff' }} />}
                        </div>
                    })}
                </div>
            </div>
            <div className={style.right} style={{ paddingLeft: 0, paddingRight: 0, paddingBottom: 0 }}>
                <Space style={{ marginBottom: 10, paddingLeft: 10, paddingRight: 10, paddingBottom: 10 }} align="center">
                    <Input.Search placeholder="搜索标签" onSearch={onSearch} allowClear /><Checkbox checked={groupAll} onChange={(e) => setGroupAll(e.target.checked)}>组内标签条件不满足过滤</Checkbox>
                </Space>
                <Spin spinning={getTagGroupList.loading}>
                    <div style={{ height: 400, overflow: 'hidden', width: '100%', paddingLeft: 10, boxSizing: 'border-box', backgroundColor: 'rgba(247, 247, 247, 0.6)' }}>
                        <Tree
                            checkable
                            height={400}
                            onCheck={onCheck}
                            onExpand={onExpand}
                            selectable={false}
                            expandedKeys={expandedKeys}
                            treeData={treeData}
                            checkedKeys={data?.[selectAdz - 1]?.friendsTagContent?.map(item => item.key)}
                            autoExpandParent={autoExpandParent}
                        />
                    </div>
                </Spin>
            </div>
            <div className={style.center}>
                <Title level={5}>已选：{data[selectAdz - 1]?.friendsTagContent?.length || 0}</Title>
                <div className={style.select_content}>
                    {data[selectAdz - 1]?.friendsTagContent?.map(item => <div key={item.key}>
                        <Text ellipsis={{ tooltip: { mouseEnterDelay: 0.5 } }} className={style.marketingAssetName}>{item.title}（{item?.value}）</Text>
                        <CloseOutlined className={style.close} onClick={() => {
                            let newData = JSON.parse(JSON.stringify(data))
                            newData[selectAdz - 1].friendsTagContent = newData[selectAdz - 1]?.friendsTagContent?.filter((i: any) => i?.key !== item.key)
                            setData(newData)
                        }} />
                    </div>)}
                </div>
            </div>
        </div>
    </Modal>
}

export default React.memo(SelectCwTag);