import { useAjax } from "@/Hook/useAjax";
import { Alert, Input, Modal, Space, Typography, Spin, Button, App, TreeDataNode, Tree, TreeProps, Switch, Checkbox, Tag } from "antd";
import React, { useEffect, useMemo, useState } from "react"
import style from './index.less'
import { getTagGroupListApi } from "../../API/global";

interface Props {
    editSelectedRow: any[],
    corpId: string,
    type: 'ADD' | 'DEL',
    visible?: boolean
    onClose?: () => void
    onChange?: () => void
}

/**
 * 添加本地标签给客户
 * @param param0 
 * @returns 
 */
const SelectCwTag: React.FC<Props> = (props) => {

    /**********************************/
    const [sysTagsList, setSysTagsList] = useState<TreeDataNode[]>([])

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

    useEffect(() => {
        getTagGroupList.run({ corpId: props.corpId, pageNum: 1, pageSize: 1000 }).then(res => {
            setSysTagsList(res?.data?.records?.map((item: { corpExternalTagList: { tagName: any; tagId: any }[]; tagGroupName: any; tagGroupId: any }) => {
                const 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 }
            }) || [])
        })
    }, [props.corpId])

    return getTagGroupList.loading ? <div style={{
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100%',
        height: '100vh',
        background: 'rgba(0,0,0,0.5)',
        zIndex: 1000,
        textAlign: 'center',
        lineHeight: '100vh',
        color: '#FFF'
    }}>
        <Spin size="large" /> <span style={{ marginLeft: 20, fontSize: 20 }}>加载中。。。</span>
    </div> : <SelectCwTagEle {...props} tagsList={sysTagsList} />
}

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!;
};

interface EleProps extends Props {
    tagsList: TreeDataNode[]
}
const SelectCwTagEle: React.FC<EleProps> = ({ tagsList, corpId, type, editSelectedRow, visible, onClose, onChange }) => {

    /**********************************/
    const [checkedList, setCheckedList] = useState<any[]>([]);

    const { message } = App.useApp()
    const [searchValue, setSearchValue] = useState<string>('');
    const [groupAll, setGroupAll] = useState<boolean>(true)
    const [dataList, setDataList] = useState<{ key: React.Key; title: string }[]>([]);
    const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
    const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
    /**********************************/

    useEffect(() => {
        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)
    }, [tagsList])


    const handleOk = () => {
        if (checkedList?.length > 0) {
            let params = {
                corpId,
                tagIdList: checkedList.map(item => item.key),
                chatIdList: editSelectedRow.map(item => item.chatId)
            }
            // if (type === 'ADD') {
            //     addChatLocalTags.run(params).then(res => {
            //         if (res.data) {
            //             message.success('操作成功')
            //             onChange?.()
            //         }
            //     })
            // } else if (type === 'DEL') {
            //     delChatLocalTags.run(params).then(res => {
            //         if (res.data) {
            //             message.success('操作成功')
            //             onChange?.()
            //         }
            //     })
            // }
        } 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'] = (checkedKeys, info) => {
        setCheckedList(info.checkedNodes?.filter(item => !item?.children))
    };



    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]);

    return <Modal
        open={visible}
        title={type === 'ADD' ? '添加群新标签' : '删除群标签'}
        onCancel={onClose}
        onOk={handleOk}
        width={750}
        destroyOnClose
        styles={{ body: { paddingBottom: 0 } }}
    >
        <Space direction="vertical" style={{ width: '100%' }}>
            <Alert message={<span>已选 <span style={{ fontSize: 14, fontWeight: 'bold' }}>{editSelectedRow.length}</span> 个群</span>} type="error" />
            <Space align="center">
                <Input.Search placeholder="搜索标签" onSearch={onSearch} allowClear /><Checkbox checked={groupAll} onChange={(e) => setGroupAll(e.target.checked)}>组内标签条件不满足过滤</Checkbox>
            </Space>
            <div style={{ display: 'flex', borderTop: '1px solid #0e0e0e08' }}>
                <div style={{ height: 350, overflow: 'hidden', width: 450, backgroundColor: 'rgba(247, 247, 247, 0.6)' }}>
                    <Tree
                        checkable
                        height={350}
                        onCheck={onCheck}
                        onExpand={onExpand}
                        selectable={false}
                        expandedKeys={expandedKeys}
                        treeData={treeData}
                        checkedKeys={checkedList.map(item => item.key)}
                        autoExpandParent={autoExpandParent}
                    />
                </div>
                <div style={{ width: 'calc(100% - 450px)', height: 350, borderLeft: '1px solid #0e0e0e08', padding: '10px 10px 0', boxSizing: 'border-box' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography.Text type='success' >已选标签:({checkedList?.length || 0})</Typography.Text>
                        <Button size='small' type='primary' onClick={() => {
                            setCheckedList([])
                        }}>清空选择</Button>
                    </div>
                    <div style={{ height: 310, overflowY: 'auto', marginTop: 10 }}>
                        {checkedList?.map(item => <Tag
                            key={item.key}
                            closable
                            style={{ marginBottom: 4 }}
                            onClose={(e) => {
                                e.preventDefault();
                                setCheckedList(checkedList.filter(d => d?.key !== item?.key))
                            }}
                        >
                            <Typography.Text ellipsis={{ tooltip: true }} style={{ maxWidth: 90 }}>{item.title}</Typography.Text>
                        </Tag>)}
                    </div>
                </div>
            </div>
        </Space>
    </Modal>
}

export default React.memo(SelectCwTag)