

/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2022-12-16 09:42:52
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-07-26 16:38:04
 * @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, useRef, useState } from 'react';
import './style.less';

import { TreeProps, Input, Modal, 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, ModalForm, ProColumns, ProFormDependency, ProFormDigit, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { createFromIconfontCN } from '@ant-design/icons';
import { commitRequest, delRequest, generateDataRequest, getCurrentCommitStatusReq, getNonCheckProjectTableData, getTreeData, getTreeDataRespType, addNonCheckProjectTableData, editNonCheckProjectTableData, getNonCheckProjectByUnitCode, getCurrentCheckStatus } from './service';

import { getComputeDate } from '@/pages/Home/service';


import 'dayjs/locale/zh-cn';
import React from 'react';
import DirectoryTree from 'antd/es/tree/DirectoryTree';
import { getDeepestTreeData } from '@/utils/tooljs';

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


import { getCheckUnitDepMapTableDataByUnitClass } from '@/pages/setting/checkUnitSet/checkUnitDepMap/service';
import { getPersonInfoTableData } from '../employeeInfoCheck/service';
import { getJiezhuanStatus } from '@/pages/budgetMana/monthlySet/service';
import { getEmps } from '@/pages/budgetMana/monthlyDataCheck/service';
import { getCurrentUnitCheckStatusReq } from '../secondaryDitriComputed/service';





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

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



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


const NonCheckProjectApprove: 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 formRef = useRef<ProFormInstance>();

    const tableRef = useRef<ActionType>();

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


    const column: ProColumns[] = [
        {
            title: '项目名称',
            dataIndex: 'assessmentName',
        },
        {
            title: '分配方式',
            dataIndex: 'distributionTypeName',
        },
        {
            title: '数值',
            dataIndex: 'value',
        },
        {
            title: '工号',
            dataIndex: 'userId',
        },
        {
            title: '姓名',
            dataIndex: 'targetValueName',
        },
        // {
        //     title: '来源',
        //     dataIndex: 'source',
        // },
        {
            title: '说明',
            dataIndex: 'description',
            ellipsis: true
        },
        {
            title: '状态',
            dataIndex: 'submitName',
            renderText(text, record, index, action) {
                return record.submit == 1 ? text : <span style={{ color: '#FF8C19' }}>{text}</span>
            },
        },
    ];


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

        const { id } = record;

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

    const getCurrentUnitCheckStatus = async () => {
        if (currentSelectedTreeNode) {
            const resp = await getCurrentUnitCheckStatusReq(currentComputeDate as string, currentSelectedTreeNode.code);
            set_unitCheckStat(`${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 (params: any, sort: any, filter: any) => {
        // console.log({ currentSelectedTreeNode });
        // console.log({ params, sort, filter });

        if (currentSelectedTreeNode && currentComputeDate) {
            const resp = await getNonCheckProjectTableData({
                computeDate: currentComputeDate,
                unitCode: currentSelectedTreeNode.code,
                ...params,
            });
            if (resp) {
                return {
                    data: resp,
                    success: true,
                }
            }
            return {
                data: [],
                success: true
            }
        }

        return []
    }


    const updateTable = async (formVal: any, type: 'EDIT' | "ADD") => {

        // 使用右侧筛选选择的核算年月；未选择时回退为当前核算年月
        const computeDateUsed = (empFilterParams && (empFilterParams as any).computeDate) ? (empFilterParams as any).computeDate : currentComputeDate;

        const result = {
            computeDate: computeDateUsed as string,
            unitCode: currentSelectedTreeNode.code,
            deptCode: formVal.deptCode,
            nonAssessmentCode: formVal.nonAssessmentCode.value,
            targetValue: formVal.targetValue,
            value: formVal.value,
            description: formVal.description
        }

        if (type == 'ADD') {
            const resp = await addNonCheckProjectTableData({ ...result });
            if (resp) {
                tableRef.current?.reload();
                message.success('操作成功！');
            }
        }
        if (type == 'EDIT') {
            const resp = await editNonCheckProjectTableData({ id: formVal.id, ...result });
            if (resp) {
                tableRef.current?.reload();
                message.success('操作成功！');
            }
        }

        return true;
    }



    const UpDataActBtn = ({ record, type }: { record: any, type: 'EDIT' | 'ADD' }) => {

        return (
            <ModalForm
                title={`${type == 'EDIT' ? '编辑' : '新增'}非考核项目`}
                width={352}
                initialValues={type == 'EDIT' ? { ...record, nonAssessmentCode: { label: record.assessmentName, value: record.assessmentCode }, targetValue: record.userId } : {}}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> : <span className='add'>添加</span>
                }
                formRef={formRef}
                onFinish={(val) => {
                    return updateTable(type == 'EDIT' ? { ...record, ...val } : { ...val }, type);
                }}
                modalProps={{ destroyOnClose: true }}
                colProps={{ span: 24 }}
                grid
            >
                <ProFormSelect label="科室："
                    name='deptCode'
                    request={async () => {
                        const resp = await getCheckUnitDepMapTableDataByUnitClass({
                            unitCode: currentSelectedTreeNode.code,
                            pageSize: 500,
                            current: 1
                        });
                        if (resp) {
                            return resp.list.map(a => ({ label: a.deptName, value: a.deptCode }))
                        }

                        return []
                    }}
          
                />
                <ProFormSelect
                    name="nonAssessmentCode"
                    label="项目名称"
                    placeholder="请选择"
                    rules={[{ required: true }]}
                    request={async () => {
                        const resp = await getNonCheckProjectByUnitCode({ unitCode: currentSelectedTreeNode.code });
                        if (resp) {
                            return resp.list.map((a: any) => ({
                                label: a.nonAssessmentName, value: a.nonAssessmentCode, d: a
                            }))
                        }
                        return []
                    }}
                    fieldProps={{
                        labelInValue: true,
                        onChange: (value) => {
                            const { d: { distributionTypeName } } = value;
                            formRef.current?.setFieldValue('distributionTypeName', distributionTypeName);
                        }
                    }}
                />
                <ProFormDependency name={['nonAssessmentCode']}>
                    {
                        ({ nonAssessmentCode }) => {
                            return (
                                <ProFormText disabled name="distributionTypeName" label="分配方式" />
                            )
                        }
                    }
                </ProFormDependency>
                <ProFormDigit label="数值" name="value" min={-1000000000000000} rules={[{ required: true }]} />
                <ProFormDependency name={['distributionTypeName','deptCode']}>
                    {
                        ({ distributionTypeName }) => {

                            return (
                                <ProFormSelect
                                    name="targetValue"
                                    label="姓名"
                                    placeholder="请选择"
                                    rules={[{ required: distributionTypeName == '绝对数' ? true : false }]}
                                    params={currentSelectedTreeNode.code}
                                    fieldProps={{
                                        showSearch: true,
                                    }}
                                    request={async () => {
                                        const resp = await getEmps(currentSelectedTreeNode.code);

                                        if (resp) {
                                            return resp.map((a: any) => ({
                                                label:`${a.name}-${a.userId}`, value: a.userId, d: a
                                            }))
                                        }
                                        return []
                                    }}
                                />
                            )
                        }
                    }
                </ProFormDependency>

                <ProFormTextArea
                    name="description"
                    label="说明"
                    colProps={{ span: 24 }}
                    placeholder="请输入"
                />

            </ModalForm>
        )
    }



    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 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('提交成功！');
                    tableRef.current?.reload();
                    getTreeReqFunc(currentComputeDate as string);
                    getCurrentCommitStatus();
                }
            }

        })
    }

    const searchEmpHandle = () => {
        set_empFilterParams({
            name: 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);
        }
    }

    useEffect(() => {

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

    useEffect(() => {
        tableRef.current?.reload();

        if (currentComputeDate && currentSelectedTreeNode) {
            getCurrentCommitStatus();
            getCurrentUnitCheckStatus();
        }
    }, [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(column as ProColumns[]);
        getCurrentComputeDate();

    }, []);


    return (
        <div className='NonCheckProjectApprove'>
            <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 });
                                            } 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,
                                                name: ''
                                            });
                                        }
                                    }} placeholder="输入工号/姓名" suffix={
                                        <IconFont type="iconsousuo" onClick={() => searchEmpHandle()} />
                                    } />
                                </>

                            </div>

                            <div className='btnGroupWrap'>
                                {
                                    !ifBanAllAction && (
                                        <>
                                            <Popover open={ifShowTip} content={auditType == '1' ? '当前处于审核中，无法操作！' : '当前处于提交中，无法操作！'} >
                                                <div className={(commitStatus != '0' || auditType == '1'||unitCheckStat == '1') ? 'btnGroup disabled' : 'btnGroup'}
                                                    /**
                                                     * 当审核中，三个操作按钮都不可点击
                                                     * 当非审核中，生成和添加不可操作
                                                     */
                                                    onMouseEnter={() => auditType == '0' ? commitStatus == '1' ? set_ifShowTip(true) : set_ifShowTip(false) : set_ifShowTip(true)}
                                                    onMouseLeave={() => set_ifShowTip(false)}
                                                >
                                                    {(commitStatus == '1' || auditType == '1'||unitCheckStat == '1') && <span key="2" >添加</span>}
                                                    {((commitStatus == '0' && auditType != '1')&&unitCheckStat != '1') && <UpDataActBtn record type='ADD' />}
                                                </div>
                                            </Popover>
                                            <div key="4" className={(auditType == '1'||unitCheckStat == '1') ? 'commit disabled' : 'commit'} onClick={() => {
                                                // 当审核中或单元已审核时，不允许点击提交
                                                if (auditType == '0' && unitCheckStat != '1') {
                                                    commitBtnhandle();
                                                }
                                            }}>{commitStatus == '1' ? '取消提交' : '提交'}</div>
                                        </>
                                    )
                                }

                            </div>

                        </div>
                        {currentSelectedTreeNode && <BMSTable params={empFilterParams} actionRef={tableRef} rowKey='id' columns={commitStatus == '0' ? [...tableColumn, {
                            title: '操作',
                            key: 'option',
                            width: 120,
                            valueType: 'option',
                            renderText: (_, record: any) => [
                                <UpDataActBtn key={'edit'} record={record} type='EDIT' />,
                                <Popconfirm key="popconfirm" title={`确认删除吗?`} okText="是" cancelText="否" onConfirm={() => delHandle(record)}>
                                    <a key={'del'}>删除</a>
                                </Popconfirm>
                            ],
                        },] : [...tableColumn]} request={(params, sort, filter) => getTableData(params, sort, filter)} />}
                    </div>
                </BMSPagecontainer>
            </div >
        </div >
    );

};

export default NonCheckProjectApprove;