

/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2022-12-16 09:42:52
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-04-09 10:25:18
 * @FilePath: /BudgetManaSystem/src/pages/budgetMana/monthlySet/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */



import BMSPagecontainer from '@/components/BMSPageContainer';

import { useEffect, useImperativeHandle, useRef, useState } from 'react';
import './style.less';

import { TreeProps, Input, Modal, Transfer, Popconfirm, Tabs, message,Switch } from 'antd';
import { DataNode } from 'antd/es/tree';

import expandedIcon from '../../../../../static/treenode_open.png';
import closeIcon from '../../../../../static/treenode_collapse.png';
import { BMSTable } from '@/components/BMSTable';
import { ActionType, ModalForm, ProColumns } from '@ant-design/pro-components';
import { createFromIconfontCN } from '@ant-design/icons';
import { CheckUnitEmpMapTableDataType, delTableData, addMapEmp, getCheckUnitEmpMapTableDataByUnitClass, getMapEmpList, getTreeData, getTreeDataRespType, updateEmpInfoReq, moveEmpToUnit, getEmpUnitMap } from './service';
import { TransferItem, TransferProps } from 'antd/es/transfer';

import difference from 'lodash/difference';



import 'dayjs/locale/zh-cn';

import React from 'react';
import DirectoryTree from 'antd/es/tree/DirectoryTree';
import { findAllParents, findParentCodes, getDeepestTreeData } from '@/utils/tooljs';

import { ColumnsType, TableRowSelection } from 'antd/es/table/interface';

import '../../../../utils/zhongtaiB';
import '../../../../utils/zhongtaiC';
import { getAllCheckUnit } from '../../projectSetting/checkUnitProjectSet/service';

const IconFont = createFromIconfontCN({
    scriptUrl: '',
});

const SearchIcon = createFromIconfontCN({
    scriptUrl: '',
});


const mockData = [{"userId":43375,"account":"admin","name":"管理员","unitCode":"","userCate":"","userCateName":"","jobTitle":"1","jobTitleName":"无","title":"1","titleRate":"1","titleName":"无","position":"1","positionName":"学部/片区/病区主任-外科","degree":"1","degreeName":"博士","doctorLevel":"","doctorLevelName":"","practiceSubject":"","practiceSubjectName":"","practiceCate":"","practiceCateName":"","major":"1","majorName":"无","entryTime":"2023-12-13 12:00:00","qualificationCertificateNo":"","practiceCertificateNo":"","practiceStatus":0,"practiceStatusName":"未知","isOnService":0,"isOnServiceName":"在职"},{"userId":43376,"account":"CS001","name":"测试001","unitCode":"","userCate":"","userCateName":"","jobTitle":"1","jobTitleName":"无","title":"1","titleRate":"1","titleName":"无","position":"1","positionName":"学部/片区/病区主任-外科","degree":"1","degreeName":"博士","doctorLevel":"","doctorLevelName":"","practiceSubject":"","practiceSubjectName":"","practiceCate":"","practiceCateName":"","major":"1","majorName":"无","entryTime":"2023-12-13 12:00:00","qualificationCertificateNo":"","practiceCertificateNo":"","practiceStatus":0,"practiceStatusName":"未知","isOnService":0,"isOnServiceName":"在职"},{"userId":43632,"account":"N0013","name":"宁晓","unitCode":"","userCate":"","userCateName":"","jobTitle":"1","jobTitleName":"无","title":"1","titleRate":"1","titleName":"无","position":"1","positionName":"学部/片区/病区主任-外科","degree":"1","degreeName":"博士","doctorLevel":"","doctorLevelName":"","practiceSubject":"","practiceSubjectName":"","practiceCate":"","practiceCateName":"","major":"1","majorName":"无","entryTime":"2023-12-13 12:00:00","qualificationCertificateNo":"","practiceCertificateNo":"","practiceStatus":0,"practiceStatusName":"未知","isOnService":0,"isOnServiceName":"在职"},{"userId":43633,"account":"N0002","name":"郭能瑞","unitCode":"","userCate":"","userCateName":"","jobTitle":"1","jobTitleName":"无","title":"1","titleRate":"1","titleName":"无","position":"1","positionName":"学部/片区/病区主任-外科","degree":"1","degreeName":"博士","doctorLevel":"","doctorLevelName":"","practiceSubject":"","practiceSubjectName":"","practiceCate":"","practiceCateName":"","major":"1","majorName":"无","entryTime":"2023-12-13 12:00:00","qualificationCertificateNo":"","practiceCertificateNo":"","practiceStatus":0,"practiceStatusName":"未知","isOnService":0,"isOnServiceName":"在职"},{"userId":43634,"account":"N0010","name":"史俊青","unitCode":"","userCate":"","userCateName":"","jobTitle":"1","jobTitleName":"无","title":"1","titleRate":"1","titleName":"无","position":"1","positionName":"学部/片区/病区主任-外科","degree":"1","degreeName":"博士","doctorLevel":"","doctorLevelName":"","practiceSubject":"","practiceSubjectName":"","practiceCate":"","practiceCateName":"","major":"1","majorName":"无","entryTime":"2023-12-13 12:00:00","qualificationCertificateNo":"","practiceCertificateNo":"","practiceStatus":0,"practiceStatusName":"未知","isOnService":0,"isOnServiceName":"在职"},{"userId":43635,"account":"N0016","name":"武和平","unitCode":"","userCate":"","userCateName":"","jobTitle":"1","jobTitleName":"无","title":"1","titleRate":"1","titleName":"无","position":"1","positionName":"学部/片区/病区主任-外科","degree":"1","degreeName":"博士","doctorLevel":"","doctorLevelName":"","practiceSubject":"","practiceSubjectName":"","practiceCate":"","practiceCateName":"","major":"1","majorName":"无","entryTime":"2023-12-13 12:00:00","qualificationCertificateNo":"","practiceCertificateNo":"","practiceStatus":0,"practiceStatusName":"未知","isOnService":0,"isOnServiceName":"在职"},{"userId":43636,"account":"N0101","name":"庞哲","unitCode":"","userCate":"","userCateName":"","jobTitle":"1","jobTitleName":"无","title":"1","titleRate":"1","titleName":"无","position":"1","positionName":"学部/片区/病区主任-外科","degree":"1","degreeName":"博士","doctorLevel":"","doctorLevelName":"","practiceSubject":"","practiceSubjectName":"","practiceCate":"","practiceCateName":"","major":"1","majorName":"无","entryTime":"2023-12-13 12:00:00","qualificationCertificateNo":"","practiceCertificateNo":"","practiceStatus":0,"practiceStatusName":"未知","isOnService":0,"isOnServiceName":"在职"},{"userId":43637,"account":"N1001","name":"蔡静","unitCode":"","userCate":"","userCateName":"","jobTitle":"1","jobTitleName":"无","title":"1","titleRate":"1","titleName":"无","position":"1","positionName":"学部/片区/病区主任-外科","degree":"1","degreeName":"博士","doctorLevel":"","doctorLevelName":"","practiceSubject":"","practiceSubjectName":"","practiceCate":"","practiceCateName":"","major":"1","majorName":"无","entryTime":"2023-12-13 12:00:00","qualificationCertificateNo":"","practiceCertificateNo":"","practiceStatus":0,"practiceStatusName":"未知","isOnService":0,"isOnServiceName":"在职"},{"userId":43638,"account":"N0108","name":"焦阳","unitCode":"","userCate":"","userCateName":"","jobTitle":"1","jobTitleName":"无","title":"1","titleRate":"1","titleName":"无","position":"1","positionName":"学部/片区/病区主任-外科","degree":"1","degreeName":"博士","doctorLevel":"","doctorLevelName":"","practiceSubject":"","practiceSubjectName":"","practiceCate":"","practiceCateName":"","major":"1","majorName":"无","entryTime":"2023-12-13 12:00:00","qualificationCertificateNo":"","practiceCertificateNo":"","practiceStatus":0,"practiceStatusName":"未知","isOnService":0,"isOnServiceName":"在职"},{"userId":43639,"account":"N1005","name":"庞玫","unitCode":"","userCate":"","userCateName":"","jobTitle":"1","jobTitleName":"无","title":"1","titleRate":"1","titleName":"无","position":"1","positionName":"学部/片区/病区主任-外科","degree":"1","degreeName":"博士","doctorLevel":"","doctorLevelName":"","practiceSubject":"","practiceSubjectName":"","practiceCate":"","practiceCateName":"","major":"1","majorName":"无","entryTime":"2023-12-13 12:00:00","qualificationCertificateNo":"","practiceCertificateNo":"","practiceStatus":0,"practiceStatusName":"未知","isOnService":0,"isOnServiceName":"在职"}]


export type TableListItem = {
    key: number;
    name: string;
};




const CheckUnitDepMap: React.FC = () => {

    const [treeData, set_treeData] = useState<getTreeDataRespType[]>([]);
    const [tableColumn, set_tableColumn] = useState<ProColumns[]>([]);
    const [currentSelectedTreeNode, set_currentSelectedTreeNode] = useState<any | undefined>();
    const [currentTabKey, set_currentTabKey] = useState('1');

    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>(undefined);
    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState('');

    const [tableData, set_tableData] = useState<CheckUnitEmpMapTableDataType[]>([]);

    const [currentSelectedEmp, set_currentSelectedEmp] = useState<undefined | any>(undefined); //当前操作的人员

    const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
    const [searchValue, setSearchValue] = useState('');
    const [autoExpandParent, setAutoExpandParent] = useState(true);

    const [ifShowModal, set_ifShowModal] = useState(false);

    const tableSelecterRef = React.createRef<{ save: any; getSelectedKeys: any }>();

    const tableRef = useRef<ActionType>();

    const column:ProColumns[] = [
        {
            title: '工号',
            dataIndex: 'account'
        },
        {
            title: '姓名',
            dataIndex: 'name',
        },
        {
            title: '人员类别',
            dataIndex: 'userCateName',
        },
        {
            title: '职务',
            dataIndex: 'jobTitleName',
        },
        {
            title: '职称',
            dataIndex: 'titleName',
        },
        {
            title: '职称系数',
            dataIndex: 'titleRate',
        },
        {
            title: '岗位',
            dataIndex: 'positionName',
        },
        {
            title: '岗位系数',
            dataIndex: 'positionRate',
        },
        {
            title: '核算单元',
            dataIndex: 'unitName',
            hideInTable:currentTabKey == '1',
            render: (_: any, record: any) => {
                 return _
            }
        },
        // {
        //     title: '学历',
        //     dataIndex: 'degreeName',
        // },
        // {
        //     title: '入职时间',
        //     dataIndex: 'entryTime',
        // },
        // {
        //     title: '在职',
        //     dataIndex: 'isOnServiceName',
        // },
        {
            title: '操作',
            key: 'option',
            valueType: 'option',
            hideInTable:currentTabKey == '1',
            render: (_: any, record: any) => {
                  return <a onClick={() => { set_currentSelectedEmp(record); set_ifShowModal(true) }}>选择单元</a>
            },
        }, 
        {
            title: '操作',
            key: 'option',
            valueType: 'option',
            hideInTable:currentTabKey == '2',
            render: (_: any, record: any) => {
                return [
                    <a onClick={() => { set_currentSelectedEmp(record); set_ifShowModal(true) }}>移动</a>,
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableDataHandle(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>
                ]
            },
        },
    ];

    const tableSelecterColumn = [                                                                                                     
        {
            title: '核算单元名称',
            dataIndex: 'unitName',
        },
        {
            title: '职类',
            dataIndex: 'unitTypeName',

        },
    ]


    const delTableDataHandle = async (record: any) => {
        const resp: any = await delTableData(record.id);
        if (resp) {
            getTreeReqFunc();
            tableRef.current?.reload()
        }
    }



    const onSelect: TreeProps['onSelect'] = (selectedKeys, info) => {
        // console.log('selected', selectedKeys, info);
        const { node } = info;
        set_currentSelectedTreeNode(node);
    };



    const getTableData = async ( params: any, sort: any, filter: any) => {
        // console.log({ currentSelectedTreeNode });
        // console.log({ params, sort, filter });

        if (currentSelectedTreeNode) {
            if(currentTabKey == '1'){
                const resp = await getCheckUnitEmpMapTableDataByUnitClass({
                    ...params,
                    unitCode: currentSelectedTreeNode.code,
    
                });
                if (resp) {
                    set_tableData(resp.list);
                    return {
                        data: resp.list,
                        success: true,
                        total: resp.totalCount,
                        pageSize: resp.pageSize,
                        totalPage: resp.totalPage,
                    }
                }
            }

            if(currentTabKey == '2'){
                const resp = await getEmpUnitMap({
                    ...params,
                });
                if (true) {
                    set_tableData(resp);
                    return {
                        data:resp.list,
                        success: true,
                        total: resp.totalCount,
                        pageSize: resp.pageSize,
                        totalPage: resp.totalPage,
                    }
                }
            }
            
            return {
                data: [],
                success: true
            }

        }

        return []
    }


    const TableSelecter = React.forwardRef(({ tableSelecterColumn, record }: any, ref) => {

        const [datasource, set_datasource] = useState<any[]>([]);
        const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
        const [selectedRows, set_selectedRows] = useState<any[]>([])
        const [showList, set_showList] = useState<any[]>([]);
        const [tableParams, set_tableParams] = useState<any>({});
        const [keywords, set_keywords] = useState('');
        const [allParentsNode, set_allParentsNode] = useState<any[]>([]);

        //获取表格数据
        const getFuncList = async () => {
            const resp = await getAllCheckUnit();
            if (resp) {
                if(currentTabKey == '1'){
                    const filteredData = resp.filter((a: any) => a.code != currentSelectedTreeNode.code);
                    set_datasource(filteredData);
                    set_showList(filteredData);
                }
                if(currentTabKey == '2'){
                    const filteredData = resp.filter((a: any) => a.code != currentSelectedEmp.unitCode);
                    set_datasource(filteredData);
                    set_showList(filteredData);
                }
            }
        }

        const onSelectHandle = (record: any, selected: boolean, selectedRows: any[], nativeEvent: any) => {

            // console.log({selectedRows});

            if (selected) {
                let data = [...datasource];
                let parent = record.parentCode != 0 ? findAllParents([...data], `${record.parentCode}`) : undefined;

                parent = parent ? parent.filter(obj => Object.keys(obj).length !== 0) : [];

                set_allParentsNode([...allParentsNode, ...parent]);

                let result = [...selectedRows, ...parent];

                result = result.filter(obj => Object.keys(obj).length !== 0);

                const _result = Array.from(new Set(result.map(obj => JSON.stringify(obj)))).map(str => JSON.parse(str));

                setSelectedKeys([...selectedRows.map((a: { code: any; }) => a.code)]);
                set_selectedRows([...selectedRows, ..._result]);
            } else {
                if (record.children) {
                    const parentCodes = findParentCodes(record);

                    //除去取消勾选的父级
                    const _allParentsNode = allParentsNode.filter(a => !parentCodes.includes(a.code));
                    set_allParentsNode([..._allParentsNode]);
                    setSelectedKeys([...selectedRows.map((a: { code: any; }) => a.code)]);
                    set_selectedRows([...selectedRows]);
                } else {
                    setSelectedKeys([...selectedRows.map((a: { code: any; }) => a.code)]);
                    set_selectedRows([...selectedRows]);
                }
            }



        };

        const onSelectAllHandle = (selected: boolean, selectedRows: any[], changeRows: any[]) => {
            if (selected) {
                setSelectedKeys([...selectedRows.map((a: { code: any; }) => a.code)]);
                set_selectedRows([...selectedRows]);
            } else {
                set_allParentsNode([]);
                setSelectedKeys([]);
                set_selectedRows([]);
            }

        }

        const save = async () => {
            if (selectedKeys.length == 0) {
                set_ifShowModal(false);
                return
            }
            const result = {
                ...currentSelectedEmp,
                unitCode: selectedKeys[0]
            }
            const resp = await moveEmpToUnit(result);
            if (resp) {
                message.success('操作成功！');
                set_ifShowModal(false);
                tableRef.current?.reload();
            }
        }

        useEffect(() => {
            getFuncList();
        }, [])

        return (
            <div className='TableSelecter'>
                <Input placeholder={'请输入'} allowClear
                    suffix={
                        <IconFont type="iconsousuo" onClick={() => {

                        }} />
                    }
                    style={{ marginBottom: 8 }}
                    onChange={(e) => {
                        if (e.target.value.length != 0) {
                            const result = datasource.filter(item => item.unitName.indexOf(e.target.value) != -1);
                            set_showList(result);
                        } else {
                            set_showList(datasource);
                        }

                    }}


                />
                <div className='wrapper' style={{ maxHeight: '491px', overflowY: 'scroll' }}>
                    <BMSTable columns={tableSelecterColumn}
                        options={{
                            density: true,
                            setting: {
                                listsHeight: 100,
                            },
                        }}
                        params={tableParams}
                        rowKey='code'
                        tableAlertRender={false}
                        rowSelection={{
                            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                            // 注释该行则默认不显示下拉选项
                            selectedRowKeys: selectedKeys,
                            onSelect: onSelectHandle,
                            checkStrictly: false,
                            type: 'radio',
                            onSelectAll(selected, selectedRows, changeRows) {
                                onSelectAllHandle(selected, selectedRows, changeRows);
                            },
                        }}
                        pagination={false}
                        dataSource={showList}
                    />
                </div>
                <div className='footer'>
                    <span className='cancel' onClick={() => set_ifShowModal(false)}>取消</span>
                    <span className='ok' onClick={() => save()}>{`确认(${selectedKeys.length > 0 && selectedKeys.length})`}</span>
                </div>
            </div>

        )
    });



    const transferTableColumn: any[] = [
        {
            title: '工号',
            dataIndex: 'account',
            with: 100,
            ellipsis: true,
        },
        {
            title: '姓名',
            width: 120,
            dataIndex: 'name',
            ellipsis: true
        },
    ];

    const addHandle = () => {

        const ref = React.createRef<{ save: any; }>();

        Modal.confirm({
            title: `添加单元对照科室(${currentSelectedTreeNode.name})`,
            icon: <></>,
            width: 750,
            okText: '确定',
            cancelText: '取消',
            centered: true,
            content: <TableTransfer
                ref={ref}
                record={currentSelectedTreeNode}
                leftColumns={transferTableColumn}
                rightColumns={transferTableColumn} dataSource={[]}
            ></TableTransfer>,
            onOk: () => {
                return ref.current && ref.current.save();
            }
        })
    }

    const TableTransfer = React.forwardRef(({ leftColumns, rightColumns, record }: any, ref) => {


        const [targetKeys, setTargetKeys] = useState<string[]>([]);
        const [datasource, set_datasource] = useState<any[]>([]);
        const [selectedKeys, setSelectedKeys] = useState<string[]>([]);

        //获取对照科室
        const getFuncList = async () => {
            const resp = await getMapEmpList();
            if (resp) {

                let defaultSelctedkeys: string[] = [];

                if (currentSelectedTreeNode) {
                    const resp2 = await getCheckUnitEmpMapTableDataByUnitClass({
                        pageSize: 500,
                        current: 1,
                        empName: '',
                        unitCode: currentSelectedTreeNode.code,

                    });
                    if (resp2) {
                        defaultSelctedkeys = resp2.list.map((item: any) => item.userId);
                        // console.log({defaultSelctedkeys,resp2});
                        setTargetKeys([...defaultSelctedkeys]);
                        set_datasource([...resp, ...resp2.list]);

                    }
                }
            }
        }

        const onChange = (nextTargetKeys: string[]) => {
            setTargetKeys(nextTargetKeys);
        };

        const onSelectChange = (sourceSelectedKeys: string[], targetSelectedKeys: string[]) => {
            //console.log('sourceSelectedKeys:', sourceSelectedKeys,'targetSelectedKeys:',targetSelectedKeys);
            setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
        };

        useImperativeHandle(ref, () => ({
            save: async () => {

                const needData = datasource.filter(item => targetKeys.includes(item.userId));

                const result = {
                    unitCode: record.code,
                    unitType: record.unitType,
                    employee: needData
                };

                const resp = await addMapEmp(result);

                if (resp) {
                    message.success('添加成功！');
                    getTreeReqFunc();
                    tableRef.current?.reload();

                }
            }
        }));

        useEffect(() => {
            getFuncList();
        }, [])

        return (
            <Transfer className='TableTransfer' showSearch
                titles={['待选项', '已选项']}
                locale={{
                    itemUnit: '项',
                    itemsUnit: '项',
                    searchPlaceholder: '请输入'
                }}
                onChange={onChange}
                onSelectChange={onSelectChange}
                dataSource={datasource}
                rowKey={record => record.userId}
                targetKeys={targetKeys}
                selectedKeys={selectedKeys}
                filterOption={(inputValue, item) => {
                    return item.name!.indexOf(inputValue) !== -1

                }}
            >
                {({
                    direction,
                    filteredItems,
                    onItemSelectAll,
                    onItemSelect,
                    selectedKeys: listSelectedKeys,
                    disabled: listDisabled,
                }) => {

                    // console.log({ filteredItems, listSelectedKeys,direction });
                    const columns = direction === 'left' ? leftColumns : rightColumns;

                    const rowSelection: TableRowSelection<TransferItem> = {
                        getCheckboxProps: (item) => ({ disabled: listDisabled || item.disabled }),
                        onSelectAll(selected, selectedRows) {
                            const treeSelectedKeys = selectedRows.map(({ userId }) => userId);
                            const diffKeys = selected
                                ? difference(treeSelectedKeys, listSelectedKeys)
                                : difference(listSelectedKeys, treeSelectedKeys);
                            onItemSelectAll(diffKeys as string[], selected);
                        },
                        onSelect({ userId }, selected) {
                            onItemSelect(userId as string, selected);
                        },
                        selectedRowKeys: listSelectedKeys,
                    };

                    return (
                        <BMSTable
                            rowSelection={rowSelection}
                            columns={columns as TransferItem[]}
                            dataSource={filteredItems}
                            size="small"
                            rowKey={'userId'}
                            tableAlertRender={false}
                            pagination={{ simple: true, pageSize: 9, showTotal: () => false }}
                            style={{ pointerEvents: listDisabled ? 'none' : undefined }}
                            onRow={({ userId, disabled: itemDisabled }) => ({
                                onClick: () => {
                                    if (itemDisabled || listDisabled) return;
                                    onItemSelect(userId as string, !listSelectedKeys.includes(userId as string));
                                },
                            })}
                        />
                    );
                }}
            </Transfer>
        )
    })


    const dataList: any[] = [];

    const getParentKey = (key: React.Key, tree: any[]): React.Key => {
        let parentKey: React.Key;
        for (let i = 0; i < tree.length; i++) {
            const node = tree[i];
            if (node.child) {
                if (node.child.some((item: { code: React.Key; }) => item.code === key)) {
                    parentKey = node.code;
                } else if (getParentKey(key, node.child)) {
                    parentKey = getParentKey(key, node.child);
                }
            }
        }
        return parentKey!;
    };


    const onTreeSearchKeyChange = (e: React.ChangeEvent<HTMLInputElement>) => {

        const { value } = e.target;
        const newExpandedKeys = dataList
            .map((item) => {
                if (item.name.indexOf(value) > -1) {
                    return getParentKey(item.code, treeData);
                }
                return null;
            });

        const b = newExpandedKeys.filter((item, i, self) => item && self.indexOf(item) === i);

        setExpandedKeys(newExpandedKeys as React.Key[]);
        setSearchValue(value);
        setAutoExpandParent(true);
    }


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

    const generateList = (data: any[]) => {
        for (let i = 0; i < data.length; i++) {
            const node = data[i];
            const { code, name } = node;
            dataList.push({ code, name });
            if (node.child) {
                generateList(node.child);
            }
        }
    };
    generateList(treeData as any);


    const getTreeReqFunc = async () => {
        const resp = await getTreeData();
        set_treeData(resp);
    }

    const tableDataSearchHandle = (paramName: string) => {

        set_tableDataFilterParams({
            ...tableDataFilterParams,
            [`${paramName}`]: tableDataSearchKeywords
        })

    }

    const updateEmpInfo = async () => {
        const resp = await updateEmpInfoReq();
        if (resp) {
            message.success('更新成功！');
            tableRef.current?.reload()
        }
    }

    const onTabChange = (activeKey:string)=>{
         set_currentTabKey(activeKey);
    }


    useEffect(() => {
        if (currentSelectedTreeNode && currentSelectedTreeNode.unitType) {
            tableRef.current?.reload();
        }
    }, [currentSelectedTreeNode]);




    useEffect(() => {
        //初始化左侧树结构数据后
        if (currentSelectedTreeNode) return;
        if (treeData?.length > 0) {

            if (treeData[0].child && treeData[0].child.length > 0) {
                const [node, nodeParent] = getDeepestTreeData(treeData[0], 'child');

                set_currentSelectedTreeNode(node);
                setExpandedKeys([nodeParent.code]);
            }
        }
    }, [treeData]);


    useEffect(()=>{
        set_tableColumn(column as ProColumns[]);
        tableRef.current?.reload();
    },[currentTabKey])

    useEffect(() => {
        set_tableColumn(column as ProColumns[]);

        getTreeReqFunc();


    }, []);


    return (
        <div className='CheckUnitEmpSet'>
            <ModalForm title={`选择目标核算单元(${currentSelectedEmp&&currentSelectedEmp.name})`} width={400} submitter={{
                render: (props, defaultDoms) => []
            }} open={ifShowModal} modalProps={{
                closable: false,
            }}>
                <TableSelecter
                    ref={tableSelecterRef}
                    record={undefined}
                    tableSelecterColumn={tableSelecterColumn}
                ></TableSelecter>
            </ModalForm>

            <div className='tabWrap'>
                <Tabs
                    defaultActiveKey="1"
                    onChange={onTabChange}
                    items={[
                        {
                            label: `单元人员对照`,
                            key: '1',
                        },
                        {
                            label: `人员单元对照`,
                            key: '2',
                        },
                    ]}
                />
                <span className='updateInfo' onClick={() => updateEmpInfo()}>更新人员信息</span>
            </div>
            <div className='contentWrap'>
                {
                    currentTabKey == '1' && (
                        <div className='leftTree'>
                            <div className='search'>
                                <Input
                                    className='searchInput'
                                    placeholder="请输入类目名称"
                                    size='small'
                                    allowClear
                                    style={{ marginBottom: 16 }}
                                    onChange={onTreeSearchKeyChange}
                                    suffix={
                                        <SearchIcon type='iconsousuo' />
                                    }
                                />
                            </div>
                            {
                                treeData && treeData.length > 0 && currentSelectedTreeNode && (
                                    <DirectoryTree
                                        fieldNames={{ title: 'name', key: 'code', children: 'child' }}
                                        rootStyle={{ height: '100%', paddingBottom: 50, overflowY: 'scroll', overflowX: 'hidden' }}
                                        onSelect={onSelect}
                                        onExpand={onExpand}
                                        expandedKeys={expandedKeys}
                                        autoExpandParent={autoExpandParent}
                                        selectedKeys={[currentSelectedTreeNode.code]}
                                        blockNode={true}
                                        icon={() => null}
                                        titleRender={
                                            (nodeData: any) => {
                                                const strTitle = nodeData.name as string;
                                                const index = strTitle.indexOf(searchValue);
                                                const beforeStr = strTitle.substring(0, index);
                                                const afterStr = strTitle.slice(index + searchValue.length);
                                                const title =
                                                    index > -1 ? (
                                                        <span style={{ display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
                                                            {beforeStr}
                                                            <span className={'site-tree-search-value'} style={{ color: 'red', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{searchValue}</span>
                                                            {afterStr}
                                                        </span>
                                                    ) : (
                                                        <span className={'strTitle'}>{strTitle}</span>
                                                    );
                                                return <div style={{
                                                    display: 'flex', flexDirection: 'row',
                                                    width: '100%',
                                                    justifyContent: 'space-between', alignItems: 'center', height: 32,
                                                    borderRadius: '4px',
                                                    overflow: 'hidden',
                                                    color: '#17181A',
                                                    textOverflow: 'ellipsis',
                                                    whiteSpace: 'nowrap'

                                                }}>
                                                    {title}
                                                    {!nodeData.map && <span className={nodeData.unitType ? 'point lastChild' : 'point'}></span>}
                                                </div>
                                            }
                                        }
                                        defaultSelectedKeys={[treeData[0].child[0].code]}
                                        treeData={treeData as unknown as DataNode[]}
                                        // treeData={treeDataNew}
                                        switcherIcon={(props: any) => {
                                            const { expanded } = props;
                                            return !expanded ? <img style={{ width: 20, height: 20, position: 'relative', top: 5 }} src={expandedIcon} /> : <img style={{ width: 20, height: 20, position: 'relative', top: 5 }} src={closeIcon} />
                                        }}
                                    />
                                )
                            }
                        </div>
                    )
                }

                {/* <div style={{width:16,height:'92vh',background:'#F5F7FA'}}></div> */}
                <div className={currentTabKey == '1'?'rightContent':'rightContent expand'}>
                    <BMSPagecontainer title={false} ghost>

                        <div className='content'>
                            <div className='tableToolbar'>
                                <div className='search'>
                                    <span>检索：</span><Input className='searchInput' allowClear placeholder="请输入工号/姓名" onChange={(e) => {
                                        set_tableDataSearchKeywords(e.target.value);
                                        if (e.target.value.length == 0) {
                                            set_tableDataFilterParams({ ...tableDataFilterParams, empName: '' });
                                        }
                                    }} suffix={
                                        <IconFont type="iconsousuo" onClick={() => tableDataSearchHandle('empName')} />
                                    }

                                        onPressEnter={(e) => {
                                            set_tableDataFilterParams({
                                                ...tableDataFilterParams,
                                                empName: (e.target as HTMLInputElement).value
                                            });
                                        }}
                                    />
                                </div>
                                <div className='btnGroup'>
                                    {currentTabKey == '1'&&<span className='add' onClick={() => addHandle()}>添加</span>}
                                    {currentTabKey == '2'&&<><Switch size='small' onChange={(bool)=>{
                                          set_tableDataFilterParams({
                                            ...tableDataFilterParams,
                                            map:bool?2:0
                                        });
                                    }} /><span style={{position:'relative',marginLeft:8,top:1}}>显示未对照人员</span></>}
                                </div>
                            </div>
                            {currentSelectedTreeNode && <BMSTable actionRef={tableRef} params={tableDataFilterParams} rowKey='id' columns={tableColumn} request={(params, sort, filter) => getTableData( params, sort, filter)} />}
                        </div>


                    </BMSPagecontainer>
                </div>
            </div>
        </div>
    );

};

export default CheckUnitDepMap;