

/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2022-12-16 09:42:52
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-12-25 11:49:47
 * @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 { Fragment, Key, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import './style.less';

import { Tree, TreeProps, Tabs, Input, Modal, Transfer, Popconfirm, message, Popover, Select } 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, ProColumnType, ProFormDigit, ProFormSelect } from '@ant-design/pro-components';
import { createFromIconfontCN } from '@ant-design/icons';
import { delRequest, getIndicTableData, getBillingItemTableData, getTreeDataRespType, getTreeData, getAllCheckUnit, saveCopyRequest, getAllCheckUnitProjectData, addBillingItemData, editBillingItemData, addIndicItemData, editIndicItemData, getNonCheckTableData, addNonCheckItemData, getCostItemsTableData, addCostItemData, editCostItemData, copySimpleRequest } from './service';
import { TransferItem, TransferProps } from 'antd/es/transfer';
import { getComputeDate } from '@/pages/Home/service';


import 'dayjs/locale/zh-cn';

import React from 'react';
import DirectoryTree from 'antd/es/tree/DirectoryTree';
import { findAllParents, findParentCodes, getDeepestTreeData, getNodesWithChildren } from '@/utils/tooljs';
import { ColumnsType, TableRowSelection } from 'antd/es/table/interface';
import { difference } from 'lodash';
import { getBillProjectData } from '../bilingProjectMana/service';
import { getIndicProjectTableData } from '../indicProjectMana/service';
import { getNonCheckProjectTableData } from '../nonAssessmentProjectMana/service';


import '../../../../utils/zhongtaiB';
import { getCostProjectTable } from '../costIncomeProjectSet/service';

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

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



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


interface TreeNode {
    id: number;
    name: string;
    code?: string;
    children?: TreeNode[];
}

function getAllLeafCodes(data: TreeNode[]): string[] {
    let result: string[] = [];

    for (let i = 0; i < data.length; i++) {
        const node = data[i];
        if (node.children) {
            result = result.concat(getAllLeafCodes(node.children));
        } else if (node.code) {
            result.push(node.code);
        }
    }

    return result;
}


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

    const [treeData, set_treeData] = useState<getTreeDataRespType[]>([]);
    const [tableColumn, set_tableColumn] = useState<ProColumns[]>([]);
    const [currentSelectedTreeNode, set_currentSelectedTreeNode] = useState<any | undefined>();
    const [currentSelectedTabKey, set_currentSelectedTabKey] = useState<string>('1');
    const [currentComputeDate, set_currentComputeDate] = useState<string | undefined>();
    const [currentEditRow, set_currentEditRow] = useState<any>(undefined);


    const [searchKeywords, set_searchKeywords] = useState('');

    const [searchParams, set_searchParams] = useState<any>({});

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

    const [ifEdit, set_ifEdit] = useState(false);

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

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

    const [currentEditCoreFlag, set_currentEditCoreFlag] = useState(0);
    const [tableSelecterColumn, set_tableSelecterColumn] = useState<ProColumns[]>([]);
    const [isCopy, set_isCopy] = useState(false);
    const [copyType,set_copyType] = useState<'ALL'|"SIMPLE">('ALL'); // ALL 复制全部 SIMPLE 单个复制

    const tableRef = useRef<ActionType>();

    const billingTableColumn: ProColumns[] = [
        {
            title: '项目代码',
            dataIndex: 'itemPointCode',
            renderText(text, record, index, action) {
                return <span style={{ display: 'inline-block', height: '26px', lineHeight: '26px' }}>{text}</span>
            },
            ellipsis: true
        },
        {
            title: '项目名称',
            dataIndex: 'itemName',
            ellipsis: true
        },
        {
            title: '项目类别',
            dataIndex: 'itemType',
            ellipsis: true
        },
        {
            title: '点值',
            width: 120,
            ellipsis: true,
            dataIndex: 'orderPointValue',
            renderText: (text, record, index, action) => {
                if (ifEdit && currentEditRow?.id == record.id) {
                    return <ProFormDigit noStyle fieldProps={{
                        defaultValue: text, onChange(value) {
                            // console.log({value,currentEditRow});
                            if (value && currentEditRow) {
                                set_currentEditRow({ ...currentEditRow, orderPointValue: value })
                            }
                        },
                    }} width={80} />
                } else {
                    return <span style={{ display: 'inline-block', width: 80 }}>{text}</span>
                }
            },
        },
        {
            title: '类型',
            width: 120,
            ellipsis: true,
            dataIndex: 'coreFlagName',
            renderText: (text, record, index, action) => {
                if (ifEdit && currentEditRow && currentEditRow?.id == record.id) {
                    return <Select defaultValue={record.coreFlag} style={{ width: '100%' }} options={
                        [
                            { label: '核心', value: 1 }, { label: '非核心', value: 0 }, { label: '不计', value: 2 }
                        ]
                    } onChange={(a, b) => { set_currentEditCoreFlag(a) }} />
                } else {
                    return <span style={{ display: 'inline-block', width: 120 }}>{text}</span>
                }
            },
        }
    ];

    const indicTableColumn: ProColumns[] = [
        {
            title: '项目代码',
            dataIndex: 'indicatorCode',
            ellipsis: true,
            renderText(text, record, index, action) {
                return <span style={{ display: 'inline-block', height: '26px', lineHeight: '26px' }}>{text}</span>
            },
        },
        {
            title: '项目名称',
            ellipsis: true,
            dataIndex: 'indicatorName',
        },
        {
            title: '类型',
            ellipsis: true,
            dataIndex: 'indicatorTypeName',
        },
        {
            title: '定义',
            ellipsis: true,
            dataIndex: 'indicatorDefinition',
        },
        {
            title: '点值',
            width: 120,
            ellipsis: true,
            dataIndex: 'orderPointValue',
            renderText(text, record, index, action) {
                if (ifEdit && currentEditRow?.id == record.id) {
                    return <ProFormDigit min={-99999} noStyle fieldProps={{
                        defaultValue: text, onChange(value) {
                            if (currentEditRow) {
                                set_currentEditRow({ ...currentEditRow, orderPointValue: value })
                            }
                        },
                    }} width={80} />
                } else {
                    return <span style={{ display: 'inline-block', width: 80 }}>{text}</span>
                }
            },
        }
    ];
    const nonCheckTableColumn: ProColumns[] = [
        {
            title: '项目名称',
            ellipsis: true,
            dataIndex: 'nonAssessmentName',
            renderText(text, record, index, action) {
                return <span style={{ display: 'inline-block', height: '26px', lineHeight: '26px' }}>{text}</span>
            },
        },
        {
            title: '分配方式',
            ellipsis: true,
            dataIndex: 'distributionTypeName',
        },
        {
            title: '分配对象',
            ellipsis: true,
            dataIndex: 'distributionTargetName',
        },
        {
            title: '上限值',
            ellipsis: true,
            dataIndex: 'ceiling',
        },
        {
            title: '评分项',
            width: 260,
            dataIndex: 'orderPointValue',
            ellipsis: true,
            renderText(text, record) {
                return record.secondItem ? record.secondItem.reduce((prev: any, cur: any) => `${prev.length > 0 ? prev + '|' : prev}${cur.secondItemName}`, '') : ''
            },
        }
    ];
    const costTableColumn: ProColumns[] = [
        {
            title: '项目名称',
            ellipsis: true,
            dataIndex: 'name',
            // renderText(text, record, index, action) {
            //     return <span style={{ display: 'inline-block', height: '26px', lineHeight: '26px' }}>{text}</span>
            // },
        },
        {
            title: '类型',
            ellipsis: true,
            dataIndex: 'itemTypeName',
        },
        {
            title: '可控',
            ellipsis: true,
            dataIndex: 'ctrlFlag',
            renderText:(text, record, index, action)=>{
                return (ifEdit&&currentEditRow?.id == record.id) ? <ProFormSelect noStyle fieldProps={{
                    defaultValue: text, onChange(value, option) {
                        set_currentEditRow({ ...currentEditRow, ctrlFlag: value })
                    },
                }} options={[{ label: '是', value: 1 }, { label: '否', value: 0 }]} /> : text == 1 ? '是' : '否'
            },
        },
        {
            title: '序号',
            ellipsis: true,
            dataIndex: 'seqNo',
        },
    ];


    const delHandle = async (record: any) => {
        const { id } = record;
        const resp = await delRequest({ id: id }, currentSelectedTabKey);
        if (resp) {
            message.success('操作成功');
            tableRef.current?.reload();
        }
    }



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


    const getCurrentComputeDate = async () => {
        const resp = await getComputeDate();
        set_currentComputeDate(resp);
    }


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




    const getTableData = async (type: 'BILL' | 'INDIC' | 'NONCHECK' | 'COST', params: any, sort: any, filter: any) => {
        // console.log({ currentSelectedTreeNode });
        // console.log({ params, sort, filter });

        if (currentSelectedTreeNode && currentComputeDate) {
            if (type == 'BILL') {
                const resp = await getBillingItemTableData({
                    unitCode: currentSelectedTreeNode.code,
                    ...params,
                });
                if (resp) {
                    return {
                        data: resp.list,
                        success: true,
                        total: resp.totalCount,
                        pageSize: resp.pageSize,
                        totalPage: resp.totalPage,
                    }
                }
                return {
                    data: [],
                    success: true
                }
            }
            if (type == 'INDIC') {
                const resp = await getIndicTableData({
                    unitCode: currentSelectedTreeNode.code,
                    ...params
                });
                if (resp) {
                    return {
                        data: resp.list,
                        success: true,
                        total: resp.totalCount,
                        pageSize: resp.pageSize,
                        totalPage: resp.totalPage,
                    }
                }
                return {
                    data: [],
                    success: true
                }
            }
            if (type == 'NONCHECK') {
                const resp = await getNonCheckTableData({
                    unitCode: currentSelectedTreeNode.code,
                    ...params
                });
                if (resp) {

                    return {
                        data: resp.list,
                        success: true,
                        total: resp.totalCount,
                        pageSize: resp.pageSize,
                        totalPage: resp.totalPage,
                    }
                }
                return {
                    data: [],
                    success: true
                }
            }
            if (type == 'COST') {
                const resp = await getCostItemsTableData({
                    unitCode: currentSelectedTreeNode.code,
                    ...params
                });
                if (resp) {

                    return {
                        data: resp,
                        success: true,
                    }
                }
                return {
                    data: [],
                    success: true
                }
            }
        }

        return []
    }


    interface TableTransferProps extends TransferProps<TransferItem> {
        leftColumns: ColumnsType<any>;
        rightColumns: ColumnsType<any>;
    }


    const transferTableColumn = [
        {
            title: '项目名称',
            dataIndex: 'itemName',
            ellipsis: true,
            width: 220
        },
        {
            title: '类型',
            dataIndex: 'itemType',

        },
    ];

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

        },
    ];

    const costItemColumns = [
        {
            title: '项目名称',
            dataIndex: 'name',
        }
    ]


    const openCopyHandleModal = (type:'SIMPLE'|'ALL') => {

        set_ifShowModal(true);
        set_isCopy(true);
        set_copyType(type);

    }

    const openTransfer = () => {
        const ref = React.createRef<{ save: any }>();
        Modal.confirm({
            title: '添加',
            icon: <></>,
            width: 800,
            centered: true,
            okText: '确定',
            cancelText: '取消',
            content: <TableTransfer
                ref={ref}
                leftColumns={transferTableColumn}
                rightColumns={transferTableColumn}
            ></TableTransfer>,
            onOk: () => {
                return ref.current && ref.current.save();
            }
        })
    }

    interface TableSelecterProps extends TransferProps<TransferItem> {
        tableSelecterColumn: any[];
        record: any
    }

    const TableSelecter = React.forwardRef(({ tableSelecterColumn, record }: TableSelecterProps, 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 () => {
            if (isCopy) {
                const resp = await getAllCheckUnit();
                if (resp) {
                    const filteredData = resp.filter((a: any) => a.code != currentSelectedTreeNode.code);
                    set_datasource(filteredData);
                    set_showList(filteredData);
                }
            } else {
                //成本项目添加
                const resp2 = await getCostItemsTableData({
                    unitCode: currentSelectedTreeNode.code,
                });

                if (resp2) {
                    const resp = await getCostProjectTable();
                    if (resp) {
                        //const filteredData = resp.filter((a:any)=>a.code != currentSelectedTreeNode.code);
                        set_datasource(resp);
                        set_showList(resp);
                        const parents = getNodesWithChildren(resp2);
                        let codes = getAllLeafCodes(resp2);
                        let _codes = Array.from(new Set(codes.map(obj => JSON.stringify(obj)))).map(str => JSON.parse(str));
                        console.log({parents,_codes})
                        setSelectedKeys(_codes);
                        set_allParentsNode(parents);
                    
                    }
                }
            }

        }
    
        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 (!isCopy && currentSelectedTabKey == '4') {
            
                let _selectedRows = Object.values([...allParentsNode,...selectedRows].reduce((acc, cur) => {
                    acc[cur.code] = cur; // 如果 id 相同，后来的元素将替换前者
                    return acc;
                  }, {}));

                const result = {
                    itemList: _selectedRows.map((a: any) => ({
                        code: a.code,
                        ctrlFlag: a.ctrlFlag,
                        itemType: a.itemType,
                        name: a.name,
                        parentCode: a.parentCode,
                        seqNo: a.seqNo,
                        statFlag: a.statFlag,
                        summaryFlag: a.summaryFlag
                    })),
                    unitCode: currentSelectedTreeNode.code
                };

                const resp = await addCostItemData(result);

                if (resp) {
                    message.success('操作成功！');
                    set_ifShowModal(false);
                    tableRef.current?.reload();
                }

            } else {

                console.log({copyType});

                if(copyType == 'ALL'){
                    const result = {
                        unitCodeList: selectedKeys,
                        unitCode: currentSelectedTreeNode.code
                    };
    
                    const resp = await saveCopyRequest(result, currentSelectedTabKey);
    
                    if (resp) {
                        message.success('复制成功！');
                        set_ifShowModal(false);
                        tableRef.current?.reload();
                    }
                }
                if(copyType == 'SIMPLE'){
                    // console.log({currentEditRow});
                    const result = {
                        unitCodeList: selectedKeys,
                        unitCode: currentSelectedTreeNode.code,
                        itemPointCode:currentSelectedTabKey == '1'?currentEditRow.itemPointCode:currentEditRow.indicatorCode
                    };

                    const resp = await copySimpleRequest(result,currentSelectedTabKey);
                    if (resp) {
                        message.success('复制成功！');
                        set_ifShowModal(false);
                        tableRef.current?.reload();
                    }
                }
            }


        }

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

        return (
            <div className='TableSelecter'>
                <Input placeholder={'请输入'} allowClear
                    suffix={
                        <IconFont type="iconsousuo" onClick={() => {
                            //console.log('iconsousuo', currentSelectedTabKey, keywords);
                            if (isCopy) {
                                set_tableParams({ ...tableParams, name: keywords })
                            }
                        }} />
                    }
                    style={{ marginBottom: 8 }}
                    onChange={(e) => {
                        if (isCopy) {
                            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);
                            }
                        }
                        if (!isCopy) {
                            //set_keywords(e.target.value);
                            const search: any = (data: any, name: string) => {
                                let result = [];

                                for (let i = 0; i < data.length; i++) {
                                    const item = data[i];
                                    if (item.name.indexOf(name) != -1) {
                                        result.push(item);
                                    }
                                    if (item.children) {
                                        result.push(...search(item.children, name));
                                    }
                                }

                                return result;
                            }

                            if (e.target.value.length > 0) {
                                const foundItem = search(datasource, e.target.value);
                                set_showList(foundItem);
                            } 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,
                        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 TableTransfer = React.forwardRef(({ leftColumns, rightColumns, ...restProps }: TableTransferProps, ref) => {

        const [_data, _set_data] = useState<any>();
        const [targetKeys, setTargetKeys] = useState<string[]>([]);
        const [datasource, set_datasource] = useState<any[]>([]);
        const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
        const [targetData, set_targetData] = useState<any[]>([]);
        const [loading, set_loading] = useState(true);
        const transferKey = currentSelectedTabKey == '1'?'itemCode':'code'
    
        //获取单元
        // const getFuncList = async () => {

        //     if (currentSelectedTabKey == '1') {
        //         const resp = await getAllCheckUnitProjectData();
        //         if (resp) {

        //             const resp1 = await getBillingItemTableData({
        //                 unitCode: currentSelectedTreeNode.code,
        //                 pageSize: 500, current: 1
        //             });

        //             if (resp1) {
        //                 let allData = resp;
        //                 set_targetData(resp1.list);
        //                 const defaultSelctedkeys = (resp1.list).map((a: any) => a.itemPointCode);
        //                 set_datasource(allData);
        //                 setTargetKeys(defaultSelctedkeys);
        //             }
        //         }
        //     }
        //     if (currentSelectedTabKey == '2') {
        //         const resp = await getIndicProjectTableData({ pageSize: 500, current: 1 });
        //         if (resp) {

        //             const resp1 = await getIndicTableData({
        //                 unitCode: currentSelectedTreeNode.code,
        //                 pageSize: 500, current: 1
        //             });

        //             if (resp1) {
        //                 set_targetData(resp1.list);
        //                 set_datasource(resp.list.map((a: any) => ({ ...a, itemName: a.indicatorName, itemType: a.indicatorTypeName })));

        //                 const defaultSelctedkeys = (resp1.list).map((a: any) => a.indicatorCode);
        //                 setTargetKeys(defaultSelctedkeys);
        //             }
        //         }
        //     }
        //     if (currentSelectedTabKey == '3') {
        //         const resp = await getNonCheckProjectTableData({ pageSize: 500, current: 1 });
        //         if (resp) {

        //             const resp1 = await getNonCheckTableData({
        //                 unitCode: currentSelectedTreeNode.code,
        //                 pageSize: 1000000, current: 1
        //             });

        //             if (resp1) {
        //                 set_targetData(resp1.list);
        //                 set_datasource(resp.list.map((a: any) => ({ ...a, itemName: a.name, itemType: a.distributionTypeName })));

        //                 const defaultSelctedkeys = (resp1.list).map((a: any) => a.nonAssessmentCode);
        //                 setTargetKeys(defaultSelctedkeys);
        //             }
        //         }
        //     }

        //     set_loading(false);

        // }
        const getFuncList = async () => {
            const fetchData = async (fetchFunc: any, params: any, keyField: string, mapFunc: any) => {
                let allData: any[] = [];
                let page = 1;
                let pageSize = params.pageSize;
        
                const fetchPage = async (page: number) => {
                    const resp = await fetchFunc({ ...params, current: page });
                    if (resp && resp.list.length > 0) {
                        allData = allData.concat(resp.list);
                        if (resp.list.length === pageSize) {
                            await fetchPage(page + 1);
                        }
                    }
                };
        
                await fetchPage(page);
                return allData;
            };
        
            if (currentSelectedTabKey == '1') {
                const resp = await getAllCheckUnitProjectData();
                if (resp) {
                    const resp1 = await fetchData(getBillingItemTableData, { unitCode: currentSelectedTreeNode.code, pageSize: 500 }, 'itemPointCode', (a: any) => a.itemPointCode);
                    set_targetData(resp1);
                    const defaultSelctedkeys = resp1.map((a: any) => a.itemPointCode);
                    set_datasource(resp);
                    setTargetKeys(defaultSelctedkeys);
                }
            }
        
            if (currentSelectedTabKey == '2') {
                const resp = await fetchData(getIndicProjectTableData, { pageSize: 500 }, 'indicatorCode', (a: any) => ({ ...a, itemName: a.indicatorName, itemType: a.indicatorTypeName }));
                if (resp) {
                    const resp1 = await fetchData(getIndicTableData, { unitCode: currentSelectedTreeNode.code, pageSize: 500 }, 'indicatorCode', (a: any) => a.indicatorCode);
                    set_targetData(resp1);
                    set_datasource(resp.map((a: any) => ({ ...a, itemName: a.indicatorName, itemType: a.indicatorTypeName })));
                    const defaultSelctedkeys = resp1.map((a: any) => a.indicatorCode);
                    setTargetKeys(defaultSelctedkeys);
                }
            }
        
            if (currentSelectedTabKey == '3') {
                const resp = await fetchData(getNonCheckProjectTableData, { pageSize: 500 }, 'nonAssessmentCode', (a: any) => ({ ...a, itemName: a.name, itemType: a.distributionTypeName }));
                if (resp) {
                    const resp1 = await fetchData(getNonCheckTableData, { unitCode: currentSelectedTreeNode.code, pageSize: 1000000 }, 'nonAssessmentCode', (a: any) => a.nonAssessmentCode);
                    set_targetData(resp1);
                    set_datasource(resp.map((a: any) => ({ ...a, itemName: a.name, itemType: a.distributionTypeName })));
                    const defaultSelctedkeys = resp1.map((a: any) => a.nonAssessmentCode);
                    setTargetKeys(defaultSelctedkeys);
                }
            }
        
            set_loading(false);
        };
        

        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 () => {

                let flag = false;

                if (currentSelectedTabKey == '1') {
                    const items = datasource.filter(a => targetKeys.includes(a[`${transferKey}`]));
                    //拿到当前的表格数据覆盖全量表格数据
                    //console.log({items,targetKeys});
                    const uodatedData = items.map(a => {
                        if (targetData.length > 0) {
                            const result = targetData.filter(b => b.itemPointCode == a[`${transferKey}`]);
                            if (result.length > 0) {
                                return {
                                    ...a,
                                    orderPointValue: result[0].orderPointValue,
                                    coreFlag: result[0].coreFlag,
                                }
                            } else {
                                return a
                            }
                        } else {
                            return a
                        }
                    })
                    const result = {
                        unitCode: currentSelectedTreeNode.code,
                        item: uodatedData.map(a => ({
                            itemPointCode: a[`${transferKey}`],
                            itemName: a.itemName,
                            orderPointValue: a.orderPointValue,
                            coreFlag: a.coreFlag
                        }))
                    }
                    const resp = await addBillingItemData(result);
                    if (resp) {
                        flag = true
                    }
                }
                if (currentSelectedTabKey == '2') {
                    const items = datasource.filter(a => targetKeys.includes(a.code));

                    //拿到当前的表格数据覆盖全量表格数据
                    const uodatedData = items.map(a => {
                        if (targetData.length > 0) {
                            const result = targetData.filter(b => b.indicatorCode == a.code);
                            if (result.length > 0) {
                                return {
                                    ...a,
                                    orderPointValue: result[0].orderPointValue
                                }
                            } else {
                                return a
                            }
                        } else {
                            return a
                        }
                    })
                    const commitData = uodatedData.map((a: any) => ({
                        indicatorCode: a.code,
                        indicatorName: a.indicatorName,
                        orderPointValue: a.orderPointValue,
                        executePointValue: a.executePointValue
                    }))
                    const result = {
                        unitCode: currentSelectedTreeNode.code,
                        indicatorValues: commitData
                    }

                    const resp = await addIndicItemData(result);
                    if (resp) {
                        flag = true
                    }
                }
                if (currentSelectedTabKey == '3') {
                    const items = datasource.filter(a => targetKeys.includes(a.code));
                    const commitData = items.map(a => ({
                        code: a.code,
                        name: a.name
                    }))
                    const result = {
                        unitCode: currentSelectedTreeNode.code,
                        assessments: commitData
                    }
                    const resp = await addNonCheckItemData(result);
                    if (resp) {
                        flag = true
                    }
                }

                if (flag) {
                    message.success('操作成功！');
                    tableRef.current?.reload();
                }

            }
        }));

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

        return (
            <Transfer className='TableTransfer' showSearch
                titles={['待选项', '已选项']}
                locale={{
                    itemUnit: '项',
                    itemsUnit: '项',
                    searchPlaceholder: '请输入',
                }}
                // oneWay={true}

                onChange={onChange}
                onSelectChange={onSelectChange}
                dataSource={datasource}
                rowKey={record => {
                    if(currentSelectedTabKey == '1'){
                        return record[`${transferKey}`]
                    }else{
                        return record[`${transferKey}`]
                    }
                }}
                targetKeys={targetKeys}
                selectedKeys={selectedKeys}
                filterOption={(inputValue, item) => {
                    if (item.itemName!.indexOf(inputValue) !== -1) {
                        console.log({ item });
                    }
                    return item.itemName!.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(a => a[`${transferKey}`]);
                            const diffKeys = selected
                                ? difference(treeSelectedKeys, listSelectedKeys)
                                : difference(listSelectedKeys, treeSelectedKeys);
                            onItemSelectAll(diffKeys as string[], selected);
                        },
                        onSelect(item, selected) {
                            onItemSelect(item[`${transferKey}`] as string, selected);
                        },
                        selectedRowKeys: listSelectedKeys,
                    };

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

    
    //成本项目添加
    const addCostProject = () => {
        set_isCopy(false);
        set_ifShowModal(true);
    }


    const tableSearchHandle = () => {
        set_searchParams({
            name: searchKeywords
        })
    }

    //编辑按钮操作
    const editBtnHandle = async () => {
        let flag = false;

        if (ifEdit) {
            //保存操作
            if (currentSelectedTabKey == '1' && currentEditRow) {
                //收费项目
                const result = {
                    id: currentEditRow.id,
                    unitCode: currentSelectedTreeNode.code,
                    orderPointValue: `${currentEditRow.orderPointValue}`,
                    coreFlag: currentEditCoreFlag
                }
                const resp = await editBillingItemData(result);
                if (resp) flag = true;
            }
            if (currentSelectedTabKey == '2' && currentEditRow) {
                //收费项目
                const result = {
                    id: currentEditRow.id,
                    unitCode: currentSelectedTreeNode.code,
                    indicatorCode: currentEditRow.indicatorCode,
                    indicatorName: currentEditRow.indicatorName,
                    orderPointValue: currentEditRow.orderPointValue,
                    executePointValue: currentEditRow.executePointValue
                }
                const resp = await editIndicItemData(result);
                if (resp) flag = true;
            }
            if (currentSelectedTabKey == '4' && currentEditRow) {
                //成本项目
                //console.log({ currentEditRow });
                const result = {
                    id: currentEditRow.id,
                    ctrlFlag: currentEditRow.ctrlFlag
                }
                const resp = await editCostItemData(result);
                if (resp) flag = true;


            }
        } else {
            //开启编辑模式
            set_ifEdit(true);
            set_currentEditRow(undefined);
        }

        if (flag) {
            set_ifEdit(false);
            message.success('操作成功！');
            tableRef.current?.reload();
        }
    }


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


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

    const setTableColumn = () => {
        if (currentSelectedTabKey == '1') {
            set_tableColumn(billingTableColumn);
        }
        if (currentSelectedTabKey == '2') {
            set_tableColumn(indicTableColumn);
        }
        if (currentSelectedTabKey == '3') {
            set_tableColumn(nonCheckTableColumn);
        }
        if (currentSelectedTabKey == '4') {
            set_tableColumn(costTableColumn);
        }
    }

    useEffect(() => {

        if (currentComputeDate) {
            getTreeReqFunc(currentComputeDate);
        }
    }, [currentComputeDate]);

    useEffect(() => {
        setTableColumn();
    }, [ifEdit]);


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

    useEffect(() => {
        setTableColumn();
    }, [currentSelectedTabKey]);

    useEffect(() => {
        if (!isCopy) {
            set_tableSelecterColumn(costItemColumns);
        } else {
            set_tableSelecterColumn(checkUnitColumns);
        }
    }, [isCopy])



    useEffect(() => {
        //初始化左侧树结构数据后

        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(billingTableColumn as ProColumns[]);
        getCurrentComputeDate();

    }, []);


    return (
        <div className='CheckUnitProjectSet'>

            <ModalForm title={isCopy ? `复制(${currentSelectedTreeNode ? currentSelectedTreeNode.name : ''})` : `添加成本项目(${currentSelectedTreeNode ? currentSelectedTreeNode.name : ''})`} width={400} submitter={{
                render: (props, defaultDoms) => []
            }} open={ifShowModal} modalProps={{
                closable: false,
            }}>
                <TableSelecter
                    ref={ref}
                    record={undefined}
                    tableSelecterColumn={tableSelecterColumn}
                ></TableSelecter>
            </ModalForm>

            <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>
                                                {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: 'flex-start', alignItems: 'center', height: 32,
                                        borderRadius: '4px',
                                        overflow: 'hidden',
                                        color: '#17181A',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap'

                                    }}>{title}</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='rightContent'>
                <BMSPagecontainer title={false} ghost>
                    <div></div>
                    <Tabs
                        defaultActiveKey="1"
                        onChange={onTabChange}
                        items={[
                            {
                                label: `收费项目`,
                                key: '1',
                            },
                            {
                                label: `指标项目`,
                                key: '2',
                            },
                            {
                                label: `非考核项目`,
                                key: '3',
                            },
                            {
                                label: `成本项目`,
                                key: '4',
                            },
                        ]}
                    />

                    {
                        currentSelectedTabKey == '1' && (
                            <div className='tabContent'>
                                <div className='tableToolbar'>
                                    <div className='search'>
                                        <span>检索：</span><Input className='searchInput' allowClear onChange={(e) => {

                                            set_searchKeywords(e.target.value)
                                            if (e.target.value.length == 0) {
                                                set_searchParams({
                                                    ...searchParams,
                                                    name: e.target.value
                                                })
                                            }
                                        }} placeholder="请输入项目名称" suffix={
                                            <IconFont type="iconsousuo" onClick={() => tableSearchHandle()} />
                                        } />
                                    </div>
                                    <div className={'btnGroup'}>
                                        <span key="2" onClick={() => openCopyHandleModal('ALL')}>复制</span>
                                        <span key="3" onClick={() => openTransfer()}>添加</span>

                                    </div>
                                </div>
                                {currentSelectedTreeNode && <BMSTable params={searchParams} actionRef={tableRef} rowKey='id' columns={[...tableColumn, {
                                    title: '操作',
                                    key: 'option',
                                    width: 140,
                                    valueType: 'option',
                                    render: (text, record: any) => [
                                        <a key={'edit'} onClick={() => {
                                            if (!ifEdit) {
                                                set_ifEdit(true);
                                                set_currentEditRow(record)
                                            }
                                            if (ifEdit) {
                                                editBtnHandle();
                                            }

                                        }}>{(ifEdit && currentEditRow?.id == record.id) ? '保存' : '编辑'}</a>,
                                        <a onClick={() => { openCopyHandleModal('SIMPLE');set_currentEditRow(record);}}>复制</a>,
                                        <Fragment key={'cancel'}>{(ifEdit && currentEditRow?.id == record.id) && <a onClick={() => set_ifEdit(false)}>取消</a>}</Fragment>,
                                        <Popconfirm key="popconfirm" title={`确认删除吗?`} okText="是" cancelText="否" onConfirm={() => delHandle(record)}>
                                            {(currentEditRow?.id != record.id || !ifEdit) && <a key={'del'}>删除</a>}
                                        </Popconfirm>
                                    ],
                                }]} request={(params, sort, filter) => getTableData('BILL', params, sort, filter)} />}
                            </div>
                        )
                    }

                    {
                        currentSelectedTabKey == '2' && (
                            <div className='tabContent'>
                                <div className='tableToolbar'>
                                    <div className='search'>
                                        <span>检索：</span><Input className='searchInput' allowClear placeholder="请输入项目名称" onChange={(e) => {
                                            set_searchKeywords(e.target.value);

                                            if (e.target.value.length == 0) {
                                                set_searchParams({
                                                    ...searchParams,
                                                    name: ''
                                                });
                                            }
                                        }} suffix={
                                            <IconFont type="iconsousuo" onClick={() => tableSearchHandle()} />
                                        } />
                                    </div>
                                    <div className={'btnGroup'}>
                                        <span key="2" onClick={() => openCopyHandleModal('ALL')}>复制</span>
                                        <span key="3" onClick={() => openTransfer()}>添加</span>

                                    </div>
                                </div>
                                {currentSelectedTreeNode && <BMSTable actionRef={tableRef} params={searchParams} rowKey='id' columns={[...tableColumn, {
                                    title: '操作',
                                    key: 'option',
                                    width: 140,
                                    valueType: 'option',
                                    render: (text, record: any) => [
                                        <a key={'edit'} onClick={() => {

                                            if (!ifEdit) {
                                                set_ifEdit(true);
                                                set_currentEditRow(record)
                                            }
                                            if (ifEdit) {
                                                editBtnHandle();
                                            }

                                        }}>{(ifEdit && currentEditRow?.id == record.id) ? '保存' : '编辑'}</a>,
                                        <Fragment key={'cancel'}>{(ifEdit && currentEditRow?.id == record.id) && <a onClick={() => set_ifEdit(false)}>取消</a>}</Fragment>,
                                        <a onClick={() => { openCopyHandleModal('SIMPLE');set_currentEditRow(record);}}>复制</a>,
                                        <Popconfirm key="popconfirm" title={`确认删除吗?`} okText="是" cancelText="否" onConfirm={() => delHandle(record)}>
                                            {(currentEditRow?.id != record.id || !ifEdit) && <a key={'del'}>删除</a>}
                                        </Popconfirm>
                                    ],
                                }]} request={(params, sort, filter) => getTableData('INDIC', params, sort, filter)} />}
                            </div>
                        )
                    }

                    {
                        currentSelectedTabKey == '3' && (
                            <div className='tabContent'>
                                <div className='tableToolbar'>
                                    <div className='search'>
                                        <span>检索：</span><Input className='searchInput' allowClear placeholder="请输入项目名称" onChange={(e) => {
                                            set_searchKeywords(e.target.value);

                                            if (e.target.value.length == 0) {
                                                set_searchParams({
                                                    ...searchParams,
                                                    name: ''
                                                });
                                            }
                                        }} suffix={
                                            <IconFont type="iconsousuo" onClick={() => tableSearchHandle()} />
                                        } />
                                    </div>
                                    <div className={'btnGroup'}>
                                        <span key="2" onClick={() => openCopyHandleModal('ALL')}>复制</span>
                                        <span key="3" onClick={() => openTransfer()}>添加</span>

                                    </div>
                                </div>
                                {currentSelectedTreeNode && <BMSTable actionRef={tableRef} params={searchParams} rowKey='id' columns={[...tableColumn, {
                                    title: '操作',
                                    key: 'option',
                                    valueType: 'option',
                                    render: (text, record: any) => [
                                        <Popconfirm key="popconfirm" title={`确认删除吗?`} okText="是" cancelText="否" onConfirm={() => delHandle(record)}>
                                            {<a key={'del'}>删除</a>}
                                        </Popconfirm>
                                    ],
                                }]} request={(params, sort, filter) => getTableData('NONCHECK', params, sort, filter)} />}
                            </div>
                        )
                    }
                    {
                        currentSelectedTabKey == '4' && (
                            <div className='tabContent'>
                                <div className='tableToolbar'>
                                    <div className='search'>
                                        <span>检索：</span><Input className='searchInput' allowClear placeholder="请输入项目名称" onChange={(e) => {
                                            set_searchKeywords(e.target.value);

                                            if (e.target.value.length == 0) {
                                                set_searchParams({
                                                    ...searchParams,
                                                    name: ''
                                                });
                                            }
                                        }} suffix={
                                            <IconFont type="iconsousuo" onClick={() => tableSearchHandle()} />
                                        } />
                                    </div>
                                    <div className={'btnGroup'}>
                                        <span key="2" onClick={() => openCopyHandleModal('ALL')}>复制</span>
                                        <span key="3" onClick={() => addCostProject()}>添加</span>

                                    </div>
                                </div>
                                {currentSelectedTreeNode && <BMSTable actionRef={tableRef} pagination={false} params={searchParams} rowKey='id' columns={[...tableColumn, 
                                {
                                    title: '操作',
                                    key: 'option',
                                    width: 140,
                                    valueType: 'option',
                                    render: (text, record: any) => [
                                        <a key={'edit'} onClick={() => {
                                            if (!ifEdit) {
                                                set_ifEdit(true);
                                                set_currentEditRow(record)
                                            }
                                            if (ifEdit) {
                                                editBtnHandle();
                    
                                            }

                                        }}>{(ifEdit && currentEditRow?.id == record.id) ? '保存' : '编辑'}</a>,
                                        <Fragment key={'cancel'}>{(ifEdit && currentEditRow?.id == record.id) && <a onClick={() => set_ifEdit(false)}>取消</a>}</Fragment>,
                                        <Popconfirm key="popconfirm" title={`确认删除吗?`} okText="是" cancelText="否" onConfirm={() => delHandle(record)}>
                                            {(currentEditRow?.id != record.id || !ifEdit) && <a key={'del'}>删除</a>}
                                        </Popconfirm>
                                    ],
                                }]} request={(params, sort, filter) => getTableData('COST', params, sort, filter)} />}
                            </div>
                        )
                    }

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

};

export default CheckUnitProjectSet;