

/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2022-12-16 09:42:52
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-02-10 17:13:13
 * @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 { Table, TreeProps, Tabs, Input, Modal, Transfer, Popconfirm, message, Popover,Spin,Button,InputNumber,Dropdown} from 'antd';
import { DataNode } from 'antd/es/tree';

import expandedIcon from '../../../../static/treenode_open.png';
import closeIcon from '../../../../static/treenode_collapse.png';

import editIcon from '../../../../static/editIcon.png';
import conformIcon from '../../../../static/confirmIcon.png';

import { BMSTable } from '@/components/BMSTable';
import { ActionType, ModalForm, ProColumns, ProColumnType, ProForm, ProFormDigit, ProFormInstance, ProFormSelect, ProFormTextArea } from '@ant-design/pro-components';
import { createFromIconfontCN, LoadingOutlined } from '@ant-design/icons';
import { checkRequest, delPersonRequest, editEmpInfoReq, fastMapDepAndEmp, generateDataRequest, getAllCheckUnit, getDepInfoTableData, getParams, getPersonInfoTableData, getProjectInfoTableData, getRemarkTempList, getTotalEmps, getTransactionInfo, getTreeData, getTreeDataRespType, jixiaoDataImport, PersonInfoTableDataType, saveEmpsRequest } from './service';
import { TransferItem, TransferProps } from 'antd/es/transfer';
import { getComputeDate } from '@/pages/Home/service';


import 'dayjs/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import { getCurrentCheckStatus } from '@/services/auth';
import React from 'react';
import DirectoryTree from 'antd/es/tree/DirectoryTree';
import { getDeepestTreeData } from '@/utils/tooljs';
import { ColumnsType, TableRowSelection } from 'antd/es/table/interface';
import { difference, set } from 'lodash';

import '../../../../src/utils/zhongtaiA'
import { getJiezhuanStatus } from '../monthlySet/service';
import { useAccess } from '@umijs/max';
import { formatMoneyNumber } from '@/utils/format';
import { getParamsDataBySysId } from '@/services/getDic';
import { BudgetManaSystemId, KcimCenterSysId } from '@/constant';
import { getParamsData } from '@/pages/setting/baseSetting/paramsMana/service';





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

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

const antIcon = <LoadingOutlined style={{ fontSize: 12 }} spin />;


const depInfoTableColumn = [
    {
        title: '科室代码',
        dataIndex: 'deptCode',
        key: 'deptCode',

    },
    {
        title: '科室名称',
        dataIndex: 'deptName',
        key: 'deptName',

    },
    {
        title: '类型',
        dataIndex: 'deptTypeName',
        key: 'deptTypeName',

    },
]

const chargeInfoTableColumn = [
    {
        title: '项目代码',
        dataIndex: 'itemCode',
        key: 'itemCode',

    },
    {
        title: '项目名称',
        dataIndex: 'itemName',
        key: 'itemName',

    },
    {
        title: '类型',
        dataIndex: 'itemType',
        key: 'itemType',

    },
    {
        title: '点值',
        dataIndex: 'itemPoint',
        key: 'itemPoint',

    },
    {
        title: '核心',
        dataIndex: 'coreFlag',
        key: 'coreFlag',

        render: (_: any) => {
            return _ == 1 ? '是' : '否'
        }
    },
]




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

const tabData = [
    {
        label: `人员信息`,
        key: '1',
    },
    {
        label: `科室信息`,
        key: '2',
    },
    {
        label: `收费项目信息`,
        key: '3',
    },
]



const MonthlyInfoCheck: React.FC = () => {
    const access = useAccess();

    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 [ifShowTip, set_ifShowTip] = useState(false);

    const [auditType, set_auditType] = useState('0');

    const [empInfoSearchKeywords, set_empInfoSearchKeywords] = useState('');

    const [empFilterParams, set_empFilterParams] = useState<any | undefined>(undefined);

    const [depInfoSearchKeywords, set_depInfoSearchKeywords] = useState('');

    const [depFilterParams, set_depFilterParams] = useState<any | undefined>(undefined);

    const [itemInfoSearchKeywords, set_itemInfoSearchKeywords] = useState('');

    const [itemFilterParams, set_itemFilterParams] = useState<any | undefined>(undefined);

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

    const [ifMulti,set_ifMulti] = useState(false); //异动处理时，单元对照是否多选

    const [ifBanAllAction, set_ifBanAllAction] = useState(true);  //是否掩藏所有操作
    const [tabs, set_tabs] = useState<any[]>([]);

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

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

    const [openChangeTable,set_openChangeTable] = useState(false);

    const [currentDeal,set_currentDeal] = useState<undefined|any>(undefined); //当前处理的异动项

    const [reloadChangeTable,set_reloadChangeTable] = useState(false);
    const [dataImportLoading,set_dataImportLoading] = useState(false);
    const [editTableCellId, set_editTableCellId] = useState<number | undefined>(undefined);
    const [ifShowColumn,set_ifShowColumn] = useState(false);



    const tableRef = useRef<ActionType>();


    const personTableColumn:ProColumnType[] = [
        {
            title: '工号',
            dataIndex: 'empNo',
            key: 'empNo',

        },
        {
            title: '姓名',
            dataIndex: 'empName',
            key: 'empName',

        },
        {
            title: '职务',
            dataIndex: 'jobTitleName',
            key: 'jobTitleName',

        },
        {
            title: '职称',
            dataIndex: 'titleName',
            key: 'titleName',

        },
        {
            title: '职称系数',
            dataIndex: 'titleRate',
            key: 'titleRate',

        },
        {
            title: '岗位',
            dataIndex: 'positionName',
            key: 'positionName',

        },
        {
            title: '岗位系数',
            dataIndex: 'positionRate',
            key: 'positionRate',

        },
        {
            title: '年资',
            dataIndex: 'seniority',
            key: 'seniority',

        },
        {
            title: '年资系数',
            hideInTable:!ifShowColumn,
            dataIndex: 'seniorityRate',
            key: 'seniorityRate',

        },
        {
            title: '人员系数',
            hideInTable:!ifShowColumn,
            key: 'userRate',
            renderText(text, record:any, index, action) {
                const {userRate,id} = record;
                let inputVal:number = userRate;

                return (
                    <div style={{ display: 'flex', flexDirection: 'row', width: '100%', justifyContent: 'flex-start', alignItems: 'center' }}>

                        <div style={{ height: 16, display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>

                            {editTableCellId == id?<InputNumber  size='small' defaultValue={userRate} width={80} placeholder='请输入' onChange={(value) => { inputVal = value }} style={{ width: '80px' }} /> : <span>{formatMoneyNumber(userRate)}</span>}
                        </div>
                        <img onClick={() => {
                            if(editTableCellId == id){
                                saveEmpRateInfo({...record,userRate:inputVal});
                                inputVal=0
                            }
                            set_editTableCellId(editTableCellId == id?undefined:id)
                            } } style={{ width: 16, height: 16, cursor: 'pointer', marginLeft: 8 }} src={editTableCellId == id ? conformIcon : editIcon} alt="" />
                    </div>
                    //saveEmpRateInfo({...record,userRate:inputVal})
                )
            },
        },
        {
            title: '性质',
            hideInTable:!ifShowColumn,
            key: 'tagList',
            renderText(text, record:any) {
                const {tagList = []} = record;
                return (<>
                    {
                     tagList.map((a:any,i:number)=>(<span style={{
                       display:'inline-flex',padding:'2px 5px',fontSize:12,background:'#EEF3FA',borderRadius:4,color:'#525866',marginRight:4
                     }}>{a.tagName}</span>))
                    }
               </>)
            },
        },
        {
            title: '备注',
            dataIndex:'remark',
            key: 'remark',
            width:170,
            ellipsis:true
        },
    ];


    const delPersonHandle = async (record: any) => {

        const { id  } = record;

        const currentComputeDateResp = await getComputeDate();
        if (currentComputeDateResp) {
            const resp = await delPersonRequest({
                computeDate: currentComputeDateResp,
                id: id
            });
            if (resp) {
                tableRef.current?.reload();
            }
        }
    }



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


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


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

    const getJiezhuanStatusHandle = async () => {
        const resp = await getJiezhuanStatus(currentComputeDate as string);
        if (resp == 2) {
            set_ifBanAllAction(true);
        } else {
            set_ifBanAllAction(false);
        }
    }


    const getTableData = async (type: 'PERSON' | 'DEP' | 'CHARGE', params: any, sort: any, filter: any) => {
        // console.log({ currentSelectedTreeNode });
        // console.log({ params, sort, filter });

        if (currentSelectedTreeNode && currentComputeDate) {
            if (type == 'PERSON') {
                const resp = await getPersonInfoTableData({
                    computeDate: currentComputeDate,
                    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 == 'DEP') {
                const resp = await getDepInfoTableData({
                    computeDate: currentComputeDate,
                    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 == 'CHARGE') {
                const resp = await getProjectInfoTableData({
                    computeDate: currentComputeDate,
                    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
                }
            }
        }

        return []
    }


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


    const transferTableColumn = [
        {
            title: '工号',
            dataIndex: 'empNo',
        },
        {
            title: '姓名',
            dataIndex: 'name',

        },
    ]

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

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

            const resp = await getTotalEmps({
                computeDate: currentComputeDate as string,
                unitCode: currentSelectedTreeNode.code
            });
            if (resp) {
                //_set_data(resp);
                const allData = resp.allEmployees.concat(resp.checkEmployees);
                set_datasource(allData);
                const defaultSelctedkeys = resp.checkEmployees.map((item: any) => item.empNo);
                setTargetKeys(defaultSelctedkeys);
            }
        }

        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 items = datasource.filter(a => targetKeys.includes(a.empNo));
                const resp = await saveEmpsRequest(items);
                if (resp) {
                    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 => record.empNo}
                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(({ empNo }) => empNo);
                            const diffKeys = selected
                                ? difference(treeSelectedKeys, listSelectedKeys)
                                : difference(listSelectedKeys, treeSelectedKeys);
                            onItemSelectAll(diffKeys as string[], selected);
                        },
                        onSelect({ empNo }, selected) {
                            onItemSelect(empNo as string, selected);
                        },
                        selectedRowKeys: listSelectedKeys,
                    };

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



    const confirmGenerateHandle = async (type: number) => {
        const resp = await generateDataRequest({
            computeDate: currentComputeDate as string,
            generateType: type
        });
        if (resp) {
            message.success('生成数据成功');
            tableRef.current?.reload();
        } else {
            message.success('生成数据错误！');
        }
    }

    const generateFunc = (type: number) => {

        let msg = '';

        if (type == 1) msg = '生成操作会根据基础设定的单元人员对照信息重新生成数据，手动调整的人员信息将会丢失，确定继续生成操作？';
        if (type == 2) msg = '生成操作会覆盖现有的科室数据，确定继续生成操作？';
        if (type == 3) msg = '生成操作会覆盖现有的收费项目数据，确定继续生成操作？';


        Modal.confirm({
            title: '注意',
            content: msg,
            okText: '确定',
            cancelText: '取消',
            onOk: () => confirmGenerateHandle(type)

        })
    }

    const searchEmpHandle = () => {
        set_empFilterParams({
            empInfo: empInfoSearchKeywords
        })
        // tableRef.current?.reload();
    }

    const searchDepHandle = () => {
        set_depFilterParams({
            deptName: depInfoSearchKeywords
        })
    }

    const searchItemHandle = () => {
        set_itemFilterParams({
            itemName: itemInfoSearchKeywords
        })
    }

    const checkHandle = async (type: string) => {

        const resp = await checkRequest({
            computeDate: currentComputeDate as string,
            auditType: type == '0' ? '1' : '0',   //审核类型  1审核 0取消审核
        });

        if (resp) {
            if (type == '0') {
                message.success('审核提交成功！');
                set_auditType('1');
            }
            if (type == '1') {
                message.success('取消审核提交成功！');
                set_auditType('0');
            }
        }
    }

    const getCheckStatus = async (computeDate: string) => {
        const resp = await getCurrentCheckStatus(computeDate);
        if (resp) {
            set_auditType(`${resp}`);  //0 未审核 1 已审核
        }
    }

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

        if(auditType == '0')return;
        Modal.confirm({
              title:'注意',
              content:'绩效数据导入操作会覆盖当月已有的绩效数据，是否继续操作？',
              onOk:async (...args)=>{
                set_dataImportLoading(true);
                const resp = await jixiaoDataImport(currentComputeDate as string);
                if (resp) {
                    set_dataImportLoading(false);
                    message.success('操作成功！');
                    tableRef.current?.reload();
                }else{
                    set_dataImportLoading(false);
                }
              },
        })
        
    }

    const ChangeTable = React.forwardRef(({reload}:{reload:boolean},ref) => {

        const [changeTableDataTypes, set_changeTableDataTypes] = useState<{ label: string, value: any }[]>([]);
        const [changeTableData, set_changeTableData] = useState<any[]>([]);
        const [changeTableDataSource, set_changeTableDataSource] = useState<any[]>([]);
        const _tableColumns: ProColumns[] = [
            {
                title: '异动类型',
                width: 120,
                dataIndex: 'messageType'
            },
            {
                title: '异动信息',
                dataIndex: 'message',
                ellipsis: true
            },
            {
                title: '操作',
                key: 'option',
                width: 80,
                valueType: 'option',
                render: (_: any, record) => (record.messageType=='科室新增'||record.messageType=='人员对照')?[
                    <a key={1} onClick={()=>{
                        set_ifMulti(record.messageType == '科室新增'?true:false);
                        set_currentDeal(record);
                        set_ifShowModal(true);
                        
                    }}>处理</a>
                ]:[],
            }
        ];

        const getInfo = async () => {

            const resp = await getTransactionInfo(currentComputeDate as string);
            if (resp) {
                const types = resp.map((a:any)=>({label:a.messageType,value:a.messageType}));
                let uniqueArr = Array.from(new Set(types.map((e: any) => JSON.stringify(e)))).map(e => JSON.parse(e as string));
                set_changeTableDataTypes(uniqueArr);
                set_changeTableData(resp);
                set_changeTableDataSource(resp);
            }
            set_reloadChangeTable(false);
        }

        const onTypeChange = (type:string)=>{
            if(type == undefined){
                set_changeTableDataSource(changeTableData);
            }else{
                const result = changeTableData.filter(a=>a.messageType == type);
                set_changeTableDataSource(result);
            }
            
        }
    
        useEffect(() => {
            getInfo();
        }, [])

        return (
            <div>
                <div className='search' style={{ marginBottom: 16 }}>
                    <span>异动类型：</span>
                    <ProFormSelect label='异动类型：' noStyle width={160} options={changeTableDataTypes} fieldProps={{
                        onChange(value, option) {
                            onTypeChange(value as string);
                        },
                    }} />
                </div>
                {changeTableDataSource && <BMSTable rowKey={'message'} columns={[..._tableColumns]} dataSource={changeTableDataSource}
                    scroll={{ y: 300 }}
                />}
            </div>
        )
    })
    
    //检查按钮事件
    const checkBtnHandle = () => {
        //点击检查按钮事件
        if (auditType != '0') {
            Modal.error({
                title: '提示',
                content: '当前处于审核状态无法操作！'
            });
            return '';
        }

        set_openChangeTable(true);

        // Modal.info({
        //     title: '异动详情',
        //     icon: <></>,
        //     width: 640,
        //     okText: '知道了',
        //     centered: true,
        //     cancelText: '',
        //     content: (
        //         <ChangeTable reload={reloadChangeTable} ref={ChangeTableRef}></ChangeTable>
        //     ),
        //     onOk: () => {
        //         // return ref.current && ref.current.save();
        //     }
        // })

    }

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


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


    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 getFuncList = async () => {
            const resp = await getAllCheckUnit();
            if (resp) {
                set_datasource(resp);
                set_showList(resp);
            }
        }


        const onSelectChange = (newSelectedRowKeys: React.Key[],selectedRows:any[]) => {
            setSelectedKeys([...newSelectedRowKeys]);
            set_selectedRows(selectedRows);

        };

        const save = async () => {
            const result = {
                computeDate:currentComputeDate,
                mapType:ifMulti?2:1,
                messageCode:currentDeal.messageCode,
                messageName:currentDeal.messageName,
                unitInfo: selectedRows.map((a:any)=>({unitCode:a.code,unitType:a.unitType}))
            };

            const resp = await fastMapDepAndEmp(result);

            if (resp) {
                message.success('操作成功！');
                set_ifShowModal(false);
                set_reloadChangeTable(true);
                
            }
        }

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

        return (
            <div className='TableSelecter'>
                <Input placeholder={'请输入单元名称'} allowClear
                    suffix={
                        <IconFont style={{ color: '#99A6BF' }} type="iconsousuo" />
                    }
                    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);
                        }

                    }}

                />
                <BMSTable columns={tableSelecterColumn}
                    options={{
                        density: true,
                        setting: {
                            listsHeight: 100,
                        },
                    }}
                    rowKey='code'
                    // scroll={{y:300}}
                    tableAlertRender={false}
                    rowSelection={{
                        // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                        // 注释该行则默认不显示下拉选项
                        selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                        onChange: onSelectChange,
                        type:ifMulti?'checkbox':'radio'
                    }}
                    pagination={{ showSizeChanger: false, pageSize:9, simple: true, showTitle: false }}
                    dataSource={showList}
                />
                <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 saveEmpRateInfo = async (saveData:any)=>{
        const resp = await editEmpInfoReq(saveData);
        if(resp){
              message.success('操作成功！');
              tableRef.current?.reload();
              return true
        }else{
            return false
        }
    }

    const formRef = useRef<ProFormInstance>();
    const empEditHandle = async (record:any)=>{
        const {list=[]} = await getRemarkTempList();
        const items = list.map((a:any,index:number)=>({
            key:index,
            label:(
                <a onClick={()=>formRef.current?.setFieldValue('remark',`${formRef.current.getFieldValue('remark')?formRef.current.getFieldValue('remark'):''}${a.name}`)}>{a.name}</a>
              ),
        }))
        return Modal.confirm({
            icon:false,
            title:'编辑系数',
            closable:true,
            width:352,
            content:(
                <div className='empEditModal'>
                     <div className='empEditModal-empInfo'>
                         <div className='empInfo-name'>{`${record.empName}(${record.empNo})`}</div>
                         <div className='empInfo-sub'>
                            <span>职务：{record.titleName?record.titleName:'-'} </span>
                            <span>职称：{record.jobTitleName?record.jobTitleName:'-'}</span>
                            <span>岗位：{record.positionName?record.positionName:'-'}  </span> 
                         </div>
                     </div>
                     <ProForm formRef={formRef} initialValues={{...record}} submitter={false}> 
                           <ProFormDigit label='职称系数：' name='titleRate'   required />    
                           <ProFormDigit label='岗位系数：' name='positionRate'  required />
                           <ProFormDigit label='年资：' name='seniority' required />  
                           <ProFormDigit label='年资系数：'  name='seniorityRate' required />
                           <ProFormDigit label='人员系数：' name='userRate'  required />  
                           <div style={{display:'flex',flexDirection:'row',justifyContent:'space-between',alignItems:'center'}}>
                            <span style={{fontWeight:500,fontSize:14,color:'#17181A'}}>备注：</span>
                            <Dropdown menu={{ items }}>
                            <span style={{display:'flex',flexDirection:'row',justifyContent:'flex-start',alignItems:'center',cursor:'pointer',fontSize:12,color:'#3376FE'}}><IconFont style={{fontSize:16,paddingRight:4}} type={'iconzhongmingming'} />模板</span>
                            </Dropdown>
                           </div>
                           <ProFormTextArea name='remark' noStyle placeholder={'请输入或插入模板'} />  
                     </ProForm>
                </div>
            ),
            okText:'确定',
            cancelText:'取消',
            onOk:async (...args)=>{
                const value = formRef.current?.getFieldsValue();
                return await saveEmpRateInfo({id:record.id,...value});
            },
        })
    }

    const getIfshowColumnParam = async ()=>{
          const resp = await getParamsData();
          if(resp){
              const needItems = resp.list.filter((a)=>a.code == '1879353982128889856');
              if(needItems.length == 1){
                    set_ifShowColumn(needItems[0].value == '1');
              }
          }
    }


    useEffect(() => {

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

    useEffect(()=>{tableRef.current?.reload();},[openChangeTable]);
    useEffect(()=>{
        set_tableColumn(personTableColumn as ProColumns[]);
    },[editTableCellId,ifShowColumn]);

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

    useEffect(() => {
        if (currentSelectedTabKey == '1') {
            set_tableColumn(personTableColumn as ProColumns[]);
        }
        if (currentSelectedTabKey == '2') {
            set_tableColumn(depInfoTableColumn as ProColumns[]);
        }
        if (currentSelectedTabKey == '3') {
            set_tableColumn(chargeInfoTableColumn as ProColumns[]);
        }
    }, [currentSelectedTabKey]);


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

        const tabs = access.whatCanIDoInThisPage(location.pathname.replace('/budgetManaSystem', ''));
        const tabsNameArr = tabs.map((a: any) => a.name);
        const needShowTabs = tabData.filter(a => tabsNameArr.includes(a.label));
        set_tabs(needShowTabs);
        getIfshowColumnParam();
    }, []);


    return (
        <div className='MonthlyInfoCheck'>
            <ModalForm title={`选择对照核算单元(${currentDeal?.messageName})`} width={400} 
            submitter={{
                render: (props, defaultDoms) => []
            }} 
            open={ifShowModal} modalProps={{
                closable: false,
            }}>
                <TableSelecter
                    ref={ref}
                    record={undefined}
                    tableSelecterColumn={tableSelecterUnitColumn}
                ></TableSelecter>
            </ModalForm>

            <Modal title="异动详情" okText='知道了' open={openChangeTable} closable 
               onCancel={()=>set_openChangeTable(false)} 
               footer={
                  [
                  <Button key="submit" type="primary" onClick={()=>set_openChangeTable(false)}>
                     知道了
                </Button>
                ]
               }
            >
                <ChangeTable reload={reloadChangeTable} />
            </Modal>

            <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>                                                                                  A                      
            {/* <div style={{width:16,height:'92vh',background:'#F5F7FA'}}></div> */}
            <div className='rightContent'>
                <BMSPagecontainer title={`核算年月：${currentComputeDate}`} ghost>
                    {
                        !ifBanAllAction && (
                            <>
                                <div className={auditType == '0' ? 'importBtn disabled' : 'importBtn '} onClick={() => importHandle()} style={{ right: auditType == '0' ? '64px' : '93px' }}>
                                    绩效数据导入<Spin spinning={dataImportLoading} indicator={antIcon} />
                                </div>
                                <div className='checkBtn' onClick={() => checkHandle(`${auditType}`)}>{auditType == '0' ? '审核' : '取消审核'}</div>
                                {!ifBanAllAction && (
                                    <div className='midLine'>
                                        <span onClick={() => checkBtnHandle()}>点击检查</span>
                                        是否有异动的人员信息及科室信息
                                    </div>
                                )}
                            </>
                        )
                    }

                    <Tabs
                        defaultActiveKey="1"
                        onChange={onTabChange}
                        items={tabs}
                    />

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

                                            set_empInfoSearchKeywords(e.target.value)
                                            if (e.target.value.length == 0) {
                                                set_empFilterParams({
                                                    ...empFilterParams,
                                                    empInfo: ''
                                                });
                                            }
                                        }} placeholder="输入工号/姓名" suffix={
                                            <IconFont type="iconsousuo" onClick={() => searchEmpHandle()} />
                                        } />
                                    </div>
                                    {
                                        !ifBanAllAction && (
                                            <Popover open={ifShowTip} content={'当前处于审核中，无法操作！'} >
                                                <div className={auditType != '0' ? 'btnGroup disabled' : 'btnGroup'}
                                                    onMouseEnter={() => auditType == '0' ? set_ifShowTip(false) : set_ifShowTip(true)}
                                                    onMouseLeave={() => set_ifShowTip(false)}
                                                >
                                                    {/* <span key="1">调整</span> */}
                                                    <span key="2" onClick={auditType == '0' ? () => generateFunc(1) : () => { }}>生成</span>
                                                    <span key="3" onClick={auditType == '0' ? () => addPersonFunc() : () => { }}>添加</span>
                                                </div>
                                            </Popover>
                                        )
                                    }


                                </div>
                                {currentSelectedTreeNode && <BMSTable params={empFilterParams} scroll={{x:1415}} actionRef={tableRef} rowKey='empNo' columns={(auditType == '0' && !ifBanAllAction) ? [...tableColumn, {
                                    title: '操作',
                                    key: 'option',
                                    fixed:'right',
                                    width:85,
                                    valueType: 'option',
                                    render: (text,record: any) => (currentSelectedTabKey == '1'&&ifShowColumn)?[
                                        <a onClick={()=>empEditHandle(record)}>编辑</a>,
                                        <Popconfirm key="popconfirm" title={`确认删除吗?`} okText="是" cancelText="否" onConfirm={() => delPersonHandle(record)}>
                                            <a key={'del'}>删除</a>
                                        </Popconfirm>
                                    ]:[
                                        <Popconfirm key="popconfirm" title={`确认删除吗?`} okText="是" cancelText="否" onConfirm={() => delPersonHandle(record)}>
                                            <a key={'del'}>删除</a>
                                        </Popconfirm>
                                    ],
                                },] : [...tableColumn]} request={(params, sort, filter) => getTableData('PERSON', 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_depInfoSearchKeywords(e.target.value);

                                            if (e.target.value.length == 0) {
                                                set_depFilterParams({
                                                    ...depFilterParams,
                                                    deptName: ''
                                                });
                                            }
                                        }} suffix={
                                            <IconFont type="iconsousuo" onClick={() => searchDepHandle()} />
                                        } />
                                    </div>
                                    {
                                        !ifBanAllAction && (
                                            <>
                                                <Popover open={ifShowTip} content={'当前处于审核中，无法操作！'} >
                                                    <div className={auditType != '0' ? 'btnGroup disabled' : 'btnGroup'}
                                                        onMouseEnter={() => auditType == '0' ? set_ifShowTip(false) : set_ifShowTip(true)}
                                                        onMouseLeave={() => set_ifShowTip(false)}
                                                    >
                                                        {/* <span key="1">调整</span> */}
                                                        <span key="2" onClick={auditType == '0' ? () => generateFunc(2) : () => { }}>生成</span>
                                                    </div>
                                                </Popover>
                                            </>
                                        )
                                    }

                                </div>
                                {currentSelectedTreeNode && <BMSTable actionRef={tableRef} params={depFilterParams} rowKey='deptCode' columns={tableColumn} request={(params, sort, filter) => getTableData('DEP', 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_itemInfoSearchKeywords(e.target.value);
                                            if (e.target.value.length == 0) {
                                                set_depFilterParams({
                                                    ...itemFilterParams,
                                                    itemName: ''
                                                });
                                            }
                                        }} suffix={
                                            <IconFont type="iconsousuo" onClick={() => searchItemHandle()} />
                                        } />
                                    </div>
                                    {
                                        !ifBanAllAction && (
                                            <Popover open={ifShowTip} content={'当前处于审核中，无法操作！'} >
                                                <div className={auditType != '0' ? 'btnGroup disabled' : 'btnGroup'}
                                                    onMouseEnter={() => auditType == '0' ? set_ifShowTip(false) : set_ifShowTip(true)}
                                                    onMouseLeave={() => set_ifShowTip(false)}
                                                >
                                                    {/* <span key="1">调整</span> */}
                                                    <span key="2" onClick={auditType == '0' ? () => generateFunc(3) : () => { }}>生成</span>
                                                </div>
                                            </Popover>
                                        )
                                    }

                                </div>
                                {currentSelectedTreeNode && <BMSTable actionRef={tableRef} params={itemFilterParams} rowKey='id' columns={tableColumn} request={(params, sort, filter) => getTableData('CHARGE', params, sort, filter)} />}
                            </div>
                        )
                    }


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

};

export default MonthlyInfoCheck;