

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



import BMSPagecontainer from '@/components/BMSPageContainer';

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

import { TreeProps, Input, Modal, Transfer, Popconfirm, message, Popover, DatePicker } 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, ProColumns } from '@ant-design/pro-components';
import { createFromIconfontCN } from '@ant-design/icons';
import { commitRequest, delPersonRequest, generateDataRequest, getCurrentCommitStatusReq, getPersonInfoTableData, getTotalEmps, getTreeData, getTreeDataRespType, saveEmpsRequest } from './service';
import { TransferItem, TransferProps } from 'antd/es/transfer';
import { getComputeDate } from '@/pages/Home/service';

import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import moment from 'moment';


import 'dayjs/locale/zh-cn';
import React from 'react';
import DirectoryTree from 'antd/es/tree/DirectoryTree';
import { getDeepestTreeData } from '@/utils/tooljs';
import { ColumnsType } from 'antd/es/table';
import { TableRowSelection } from 'antd/es/table/interface';
import { difference } from 'lodash';
import { getCurrentCheckStatus } from '@/services/auth';
import { getJiezhuanStatus } from '@/pages/budgetMana/monthlySet/service';
import { getCurrentUnitCheckStatusReq } from '../secondaryDitriComputed/service';
import { getParamsData } from '@/pages/setting/baseSetting/paramsMana/service';




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

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



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


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

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

    const [currentComputeDate, set_currentComputeDate] = useState<string | undefined>();

    const [ifShowTip, set_ifShowTip] = useState(false);

    const [commitStatus, set_commitStatus] = useState('0'); //提交状态

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

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

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

    const [auditType, set_auditType] = useState('0');  //审核状态

    const [unitCheckStat, set_unitCheckStat] = useState('0');  //单元审核状态

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

    // 新增：控制“人员系数”、“年资系数”、“人员性质”字段显示与隐藏的状态
    const [ifShowColumn, set_ifShowColumn] = useState<boolean>(false);


    const tableRef = useRef<ActionType>();


    // 基础表格列定义（不包含受控列）
    const baseColumns:ProColumns[] = [
        {
            title: '工号',
            dataIndex: 'empNo',
            key: 'empNo',
            sorter:(a,b)=>{
                  return parseInt(a.empNo) - parseInt(b.empNo);
            },
        },
        {
            title: '姓名',
            dataIndex: 'empName',
            key: 'empName',
            sorter: (a, b) => {
                return a.empName.localeCompare(b.empName);
            },
        },
        {
            title: '职务',
            dataIndex: 'jobTitleName',
            key: 'jobTitleName',
            sorter: (a, b) => {
                return a.jobTitleName.localeCompare(b.jobTitleName);
            },
        },
        {
            title: '职称',
            dataIndex: 'titleName',
            sorter: (a, b) => {
                return a.titleName.localeCompare(b.titleName);
            },
        },
        {
            title: '职称系数',
            dataIndex: 'titleRate',
        },
        {
            title: '岗位',
            dataIndex: 'positionName',
            key: 'positionName',
        },
        {
            title: '岗位系数',
            dataIndex: 'positionRate',
            key: 'positionRate',
        },
        {
            title: '年资',
            dataIndex: 'seniority',
            key: 'seniority',
        },
        // 受控列将在后面动态插入
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
        },
    ];

    // 受控列定义
    const controlledColumns: ProColumns[] = [
        {
            title: '人员系数',
            dataIndex: 'userRate',
            key: 'userRate',
        },
        {
            title: '年资系数',
            dataIndex: 'seniorityRate',
            key: 'seniorityRate',
        },
        {
            title: '性质',
            dataIndex: 'tagList',
            key: 'tagList',
            render: (_, record) => {
                // 忽略items字段，只显示tagCode和tagName
                const tagList = record.tagList;
                if (tagList && Array.isArray(tagList)) {
                    return tagList.map((tag, index) => (
                        <span key={index} style={{ marginRight: 8 }}>
                            {tag.tagName}
                        </span>
                    ));
                }
                return '';
            },
        },
    ];

    // 动态生成表格列，受控列根据ifShowColumn插入
    const getTableColumns = () => {
        // 插入位置：在“年资”后面插入三列
        const insertIndex = 7; // "年资"在baseColumns的索引
        let columns = [...baseColumns];
        if (ifShowColumn) {
            columns.splice(insertIndex + 1, 0, ...controlledColumns);
        }
        return columns;
    };


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

        const { props: { record: { id } } } = record;

        const currentComputeDateResp = await getComputeDate();
        if (currentComputeDateResp) {
            const resp = await delPersonRequest({
                computeDate: currentComputeDateResp,
                id: id,
                unitCode: currentSelectedTreeNode.code
            });
            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 getCheckStatus = async (computeDate: string) => {
        const resp = await getCurrentCheckStatus(computeDate);
        if (resp) {
            set_auditType(`${resp}`);  //0 未审核 1 已审核
        }
    }

    const getCurrentCommitStatus = async () => {
        if (currentSelectedTreeNode) {
            const resp = await getCurrentCommitStatusReq({
                computeDate: currentComputeDate as string,
                unitCode: currentSelectedTreeNode.code
            });
            set_commitStatus(`${resp}`);
        }
    }

    

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

        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: '确定',
            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 () => {
        const resp = await generateDataRequest({
            computeDate: currentComputeDate as string,
            unitCode: currentSelectedTreeNode.code
        });
        if (resp) {
            message.success('生成数据成功');
            tableRef.current?.reload();
        } else {
            message.success('生成数据错误！');
        }
    }

    const getCurrentUnitCheckStatus = async () => {
        if (currentSelectedTreeNode) {
            const resp = await getCurrentUnitCheckStatusReq(currentComputeDate as string, currentSelectedTreeNode.code);
            set_unitCheckStat(`${resp}`);//0 未审核 1 已审核
        }
    }

    const generateFunc = () => {

        let msg = '生成操作会覆盖已有的数据，是否继续？';
        Modal.confirm({
            title: '注意',
            okText: '确定',
            cancelText: '取消',
            content: msg,
            onOk: () => confirmGenerateHandle()

        });
    }

    const commitBtnhandle = () => {
        Modal.confirm({
            title: '注意',
            okText: '确定',
            cancelText: '取消',
            content: `${commitStatus == '1' ? '取消提交' : '提交'}当前选择的核算单元的数据?`,
            onOk: async () => {
                const resp = await commitRequest({
                    computeDate: currentComputeDate as string,
                    unitCode: currentSelectedTreeNode.code,
                    type: commitStatus == '1' ? '0' : '1',  //1 提交 0 取消
                });
                if (resp) {
                    message.success('提交成功！');
                    getTreeReqFunc(currentComputeDate as string);
                    getCurrentCommitStatus();
                }
            }

        })
    }

    const searchEmpHandle = () => {
        set_empFilterParams({
            empInfo: empInfoSearchKeywords
        })
        // 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 getJiezhuanStatusHandle = async () => {
        const resp = await getJiezhuanStatus(currentComputeDate as string);
        if (resp == 2) {
            set_ifBanAllAction(true);
        } else {
            set_ifBanAllAction(false);
        }
    }

    // 修改getIfshowColumnParam，调用set_ifShowColumn
    const getIfshowColumnParam = async ()=>{
        const resp = await getParamsData();
        if(resp){
            const needItems = resp.list.filter((a)=>a.code == '1879353982128889856');
            if(needItems.length == 1){
                // 1显示，0隐藏
                set_ifShowColumn(needItems[0].value == '1');
            }
        }
    }

    // 初始化时获取ifShowColumn参数
    useEffect(() => {
        getIfshowColumnParam();
    }, []);

    useEffect(() => {

        if (currentComputeDate) {
            getTreeReqFunc(currentComputeDate);
            getCheckStatus(currentComputeDate);
            getJiezhuanStatusHandle();
            tableRef.current?.reload();
        }
    }, [currentComputeDate]);

    useEffect(() => {
        if (currentComputeDate && currentSelectedTreeNode) {
            
            
            if(!currentSelectedTreeNode.child){
                getCurrentCommitStatus();
                getCurrentUnitCheckStatus();
                tableRef.current?.reload();
            }
            
        }
    }, [currentSelectedTreeNode, currentComputeDate]);




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

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

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


    useEffect(() => {
        if (auditType == '1') {
            //当审核中时，禁掉所有操作
            set_commitStatus('1');
        }
    }, [auditType])

    // 设置表格列
    useEffect(() => {
        set_tableColumn(getTableColumns() as ProColumns[]);
        getCurrentComputeDate();
    }, [ifShowColumn]);


    return (
        <div className='EmployeeInfoCheck'>
            <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: '#3377ff', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{searchValue}</span>
                                                {afterStr}
                                            </span>
                                        ) : (
                                            <span className='strTitle'>{strTitle}</span>
                                        );
                                    return <div style={{
                                        display: 'flex', flexDirection: 'row',
                                        width: '100%',
                                        justifyContent: 'space-between', alignItems: 'center', height: 32,
                                        borderRadius: '4px',
                                        overflow: 'hidden',
                                        color: '#17181A',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap'

                                    }}>
                                        {title}
                                        {!nodeData.map && <span className={nodeData.unitType ? 'point lastChild' : 'point'}></span>}
                                    </div>
                                }
                            }
                            defaultSelectedKeys={[treeData[0].child[0].code]}
                            treeData={treeData as unknown as DataNode[]}
                            // treeData={treeDataNew}
                            switcherIcon={(props: any) => {
                                const { expanded } = props;
                                return !expanded ? <img style={{ width: 20, height: 20, position: 'relative', top: 5 }} src={expandedIcon} /> : <img style={{ width: 20, height: 20, position: 'relative', top: 5 }} src={closeIcon} />
                            }}
                        />
                    )
                }
            </div>
            {/* <div style={{width:16,height:'92vh',background:'#F5F7FA'}}></div> */}
            <div className='rightContent'>
                <BMSPagecontainer title={false} ghost>
                    <div className='tabContent'>
                        <div className='tableToolbar'>
                            <div className='search'>
                                <div style={{ marginRight: 16 }}>
                                    <span>核算年月：</span>
                                    {currentComputeDate&&<DatePicker
                                        onChange={(data, dateString) => {
                                            if (dateString) {
                                                set_empFilterParams({ ...empFilterParams, computeDate: dateString });
                                                set_currentComputeDate(dateString);
                                            } else {
                                                set_empFilterParams({ ...empFilterParams, computeDate: currentComputeDate })
                                            }
                                        }}
                                        allowClear={true}
                                        picker='month'
                                        locale={locale}
                                        defaultValue={moment(currentComputeDate,'YYYY-MM')} 
                                        format='YYYY-MM' placeholder="请选择核算年月" />}
                                </div>
                                <>
                                    <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>

                            <div className='btnGroupWrap'>
                                {
                                    !ifBanAllAction && (
                                        <Popover open={ifShowTip} content={'当前处于提交中，无法操作！'} >
                                            <div className={(commitStatus != '0'||unitCheckStat != '0') ? 'btnGroup disabled' : 'btnGroup'}
                                                /**
                                                 * 当审核中，三个操作按钮都不可点击
                                                 * 当非审核中，生成和添加不可操作
                                                 */
                                                onMouseEnter={() => commitStatus == '1' ? set_ifShowTip(true) : set_ifShowTip(false)}
                                                onMouseLeave={() => set_ifShowTip(false)}
                                            >
                                                <span key="2" onClick={commitStatus == '0' ?unitCheckStat == '0'?() => generateFunc():()=>null : () => { }}>生成</span>
                                                <span key="3" onClick={commitStatus == '0' ?unitCheckStat == '0'?() => addPersonFunc():()=>null : () => { }}>添加</span>
                                            </div>
                                        </Popover>
                                    )
                                }

                                {!ifBanAllAction && <div key="4" className={unitCheckStat != '0'?'commit disabled':'commit'} onClick={() => unitCheckStat != '0'?()=>null:commitBtnhandle()}>{commitStatus == '1' ? '取消提交' : '提交'}</div>}
                            </div>

                        </div>
                        {currentSelectedTreeNode && <BMSTable params={empFilterParams} actionRef={tableRef} rowKey='empNo' columns={commitStatus == '0' ? [...tableColumn, {
                            title: '操作',
                            width: 90,
                            key: 'option',
                            fixed: 'right',
                            valueType: 'option',
                            render: (record: any) => [
                                <Popconfirm key="popconfirm" title={`确认删除吗?`} okText="是" cancelText="否" onConfirm={() => delPersonHandle(record)}>
                                    <a key={'del'}>删除</a>
                                </Popconfirm>
                            ],
                        },] : [...tableColumn]} scroll={{ x: 1260 }} request={(params, sort, filter) => getTableData('PERSON', params, sort, filter)} />}
                    </div>
                </BMSPagecontainer>
            </div >
        </div >
    );

};

export default EmployeeInfoCheck;