/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-01-03 14:20:22
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-07-22 11:39:34
 * @FilePath: /BudgetManaSystem/src/pages/budgetMana/personnelSalaryBudget/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */


import BMSPagecontainer from '@/components/BMSPageContainer'
import { BMSTable } from '@/components/BMSTable';
import { getComputeDate } from '@/pages/Home/service';
import { createFromIconfontCN } from '@ant-design/icons';
import { ActionType, ProColumns } from '@ant-design/pro-components';
import { Input, InputNumber, message, Modal, Steps } from 'antd';
import React, { useEffect, useRef, useState } from 'react'
import { auditRequest, caculate, checkRequest, checkRetainStatusReq, editAssessmentBonus, generate, getAllParameter, getCurrentCheckStatus, getData } from './service';

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

import './style.less';
import '../../../utils/zhongtaiB'
import { formatMoneyNumber } from '@/utils/format';
import { getJiezhuanStatus } from '../monthlySet/service';
import { getParams } from '../monthlyInfoCheck/service';
import { CardList } from './components/cardList';
import { Distribute } from './components/distribute';

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


const steps = [
    {
        title: '保留系数设定',
        content: 'First-content',
    },
    {
        title: '人事薪酬预算',
        content: 'Second-content',
    },
    {
        title: '保留奖金分配',
        content: 'Last-content',
    },
];

const items = steps.map((item) => ({ key: item.title, title: item.title }));

const PersonnelSalaryBudget = () => {


    const [auditType, set_auditType] = useState('0');
    const [currentComputeDate, set_currentComputeDate] = useState<string | undefined>();
    const [pageData, set_pageData] = useState({
        rate: 0, income: 0, personalCost: 0, cost: 0
    });

    const [editTableCellId, set_editTableCellId] = useState<number | undefined>(undefined);

    const [inputSalaryNum, set_inputSalaryNum] = useState(0);

    const tableRef = useRef<ActionType>();

    const [loading, set_loading] = useState(false);

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

    const [ifEditTable, set_ifEditTable] = useState(true);

    const [ifEditIncome, set_ifEditIncome] = useState(false);
    const [ifEditCost, set_ifEditCost] = useState(false);
    const [ifEditRate, set_ifEditRate] = useState(false);
    const [currentStep, set_currentStep] = useState(2);
    const [pageType, set_pageType] = useState(1); //1旧版 2新版

    const tableColumn: ProColumns[] = [
        {
            title: '职类',
            dataIndex: 'unitTypeName',
            key: 'unitTypeName',
            fixed: 'left'

        },
        {
            title: '合理编制比例',
            dataIndex: 'staffRate',
            key: 'staffRate',

        },
        {
            title: '合理人均薪酬系数',
            dataIndex: 'averageSalary',
            key: 'averageSalary',
            ellipsis: true
        },
        {
            title: ifEditTable ? '绩效奖金占比' : '人事成本占比',
            dataIndex: 'percent',
            key: 'percent',
        },
        {
            title: '占有效收入比',
            dataIndex: 'effectiveRate',
            key: 'effectiveRate',
        },
        {
            title: ifEditTable ? '绩效奖金' : '人事成本',
            dataIndex: 'cost',
            key: 'cost',
            renderText(num, record, index, action) {
                return formatMoneyNumber(num)
            },
        },
        {
            title: '固定工资',
            dataIndex: 'salary',
            hideInTable: ifEditTable,
            key: 'salary',
            renderText(num, record, index, action) {
                return formatMoneyNumber(num)
            },
        },
        {
            title: '基金',
            dataIndex: 'fundBonus',
            key: 'fundBonus',
            renderText(num, record, index, action) {
                return formatMoneyNumber(num)
            },
        },

        {
            title: '专项补助',
            dataIndex: 'subsidies',
            key: 'subsidies',
            renderText(num, record, index, action) {
                return formatMoneyNumber(num)
            },
        },
        {
            title: '变动薪酬',
            dataIndex: 'variableCompensation',
            key: 'variableCompensation',
            renderText(num, record, index, action) {
                return formatMoneyNumber(num)
            },
        },
        {
            title: '不参与考核奖金',
            dataIndex: 'noAssessmentBonus',
            key: 'noAssessmentBonus',
            renderText(num, record, index, action) {
                return formatMoneyNumber(num)
            },
        },
        {
            title: '合理化考核奖金',
            dataIndex: 'rationalizeBonus',
            key: 'rationalizeBonus',
            renderText(num, record, index, action) {
                return formatMoneyNumber(num)
            },
        },
        {
            title: '保留金额',
            dataIndex: 'retainBonus',
            key: 'retainBonus',
            hideInTable: pageType == 1,
            renderText(num, record, index, action) {
                return formatMoneyNumber(num)
            },
        }
    ];

    const getPageData = async (currentComputeDate: string, params: any, sort: any, filter: any) => {
        const resp = await getData(currentComputeDate);
        if (resp) {

            set_pageData({
                rate: resp.rate,
                income: resp.income,
                personalCost: resp.personalCost,
                cost: resp.cost
            });
            return {
                data: resp.detail,
                success: true,
            }
        }
        return []
    }

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

        let resp = undefined;

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

    

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


    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 editHandle = async (record: any) => {
        const { id } = record;
        if (id == editTableCellId) {
            //保存
            if (inputSalaryNum) {
                const resp = await editAssessmentBonus({
                    assessmentBonus: inputSalaryNum,
                    id
                });
                if (resp) {
                    tableRef.current?.reload();
                }
            }
            set_editTableCellId(undefined);
        } else {
            //编辑
            set_editTableCellId(id);
        }

    }

    const confirmGenerateHandle = async (index: number) => {
        if (index == 1) {
            const resp = await generate(currentComputeDate as string);
            if (resp) {
                message.success('生成完成！');
                tableRef.current?.reload();
            }
        }
        if (index == 2) {
            const resp = await caculate({
                computeDate: currentComputeDate as string,
                ...pageData
            });
            if (resp) {
                message.success('计算完成！');
                tableRef.current?.reload();
            }
        }
    }


    const generateFunc = (index: number) => {
        /**
         * index == 1 生成 2 计算
         * 
         */

        if (auditType == '1') {
            Modal.confirm({
                title: '注意',
                okText: '确定',
                cancelText: '',
                closable: true,
                content: '当前处于审核状态无法操作！',
            });
            return;
        }

        Modal.confirm({
            title: '注意',
            okText: '确定',
            cancelText: '',
            closable: true,
            content: index == 1 ? '生成后需重新计算数据，确定要进行生成操作？' : '计算会覆盖原有数据，确定要继续计算操作？',
            onOk: () => { set_loading(true); confirmGenerateHandle(index) }
        });


    }

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



    const setPageType = async () => {
        const resp = await getParams();
        if (resp) {
            const needItems = resp.list.filter((a: any) => a.code == '1686657454764597248');
            if (needItems.length > 0) {
                if (needItems[0].value == '2') {
                    set_ifEditTable(false);
                } else {
                    set_ifEditTable(true);
                }
            }
        }
    }

    const nextHandle = async () => {
        if (currentStep > 2) return;
        if (currentStep == 1) {
            const canProceed = await checkRetainStatusHandle();
            if (canProceed) {
                set_currentStep(currentStep + 1);
            }
        } else {
            set_currentStep(currentStep + 1);
        }
    }

    const checkRetainStatusHandle = async () => {
        const resp = await checkRetainStatusReq(currentComputeDate as string);
        let flag = false;
        if (resp) {
            // 使Modal操作成为决定flag的一部分
            await new Promise((resolve, reject) => {
                Modal.confirm({
                    title: '注意',
                    content: '保留系数设定的数据有调整，需重新进行计算操作',
                    okText: '确定',
                    cancelText: '取消',
                });
            });
        } else {
            flag = true;
        }

        return flag;
    }


    const prevHandle = () => {
        set_currentStep(currentStep - 1)
    }

    const getAllParameterHandle = async () => {
        const resp = await getAllParameter();
        if (resp) {
            const needItem = resp.list.filter((a: any) => a.code == '1788097421696442368');
            if (needItem.length > 0) {
                set_pageType(needItem[0].value == '1' ? 2 : 1)
            }
        }
    }



    useEffect(() => {
        if (!ifEditIncome && !ifEditCost && !ifEditRate) {
            if (ifEditTable && pageData.income > 0) {
                const result = (pageData.income - pageData.cost) * pageData.rate;
                set_pageData({ ...pageData, personalCost: result })
            }
        }
    }, [ifEditIncome, ifEditCost, ifEditRate]);


    useEffect(() => {
        currentComputeDate && getCheckStatus(currentComputeDate);
        currentComputeDate && getJiezhuanStatusHandle();
    }, [currentComputeDate]);



    useEffect(() => {

        getCurrentComputeDate();
        setPageType();
        getAllParameterHandle();

    }, []);


    return (
        <BMSPagecontainer className='PersonnelSalaryBudget' title={false} ghost>
            <div className='Pageheader'>
                <div className='lineOne' style={{ marginBottom: pageType == 1 ? 0 : 24 }}>
                    <div className='title'>{`核算年月：${currentComputeDate}`}</div>
                    <div className='btns'>
                        {(pageType == 2 && currentStep > 0) && <div className={'checkBtn prev'} style={{ right: currentStep == 2 ? 80 : 95 }} onClick={() => prevHandle()}>{'上一步'}</div>}
                        {(pageType == 2 && currentStep < 2) && <div className={'checkBtn'} onClick={() => nextHandle()}>{'下一步'}</div>}
                        {(!ifBanAllAction && (currentStep == 2) || pageType == 1) && <div className='checkBtn' onClick={() => checkHandle(`${auditType}`)}>{auditType == '0' ? '审核' : '取消审核'}</div>}
                    </div>
                </div>
                {
                    pageType == 2 && (
                        <div className='lineTwo'>
                            <Steps current={currentStep} items={items} responsive={false} />
                        </div>
                    )
                }

            </div>
            {
                currentStep == 0 && currentComputeDate && (
                    <CardList computeDate={currentComputeDate} />
                )
            }
            {
                ((pageType == 2 && currentStep == 1) || pageType == 1) && (
                    <>
                        <div className='paramsWrap'>
                            <div className='paramsWrapHeader'>
                                <span className='title'>人事薪酬预算</span>
                                {(!ifBanAllAction && !ifEditTable) && <span className='btn' onClick={() => generateFunc(1)}> <IconFont style={{ color: '#3376FE', fontSize: 16 }} type='iconzhongxin' /> 重新生成</span>}
                            </div>
                            <div className='cardWrap'>
                                <div className='card'>
                                    <span>{ifEditTable ? '总收入' : '收入'}</span>
                                    <div className='count'>
                                        <span onClick={() => auditType == '0' ? set_ifEditIncome(true) : () => { }}>{!ifEditIncome && pageData.income}</span>
                                        {(ifEditIncome && ifEditTable) && <InputNumber precision={2} onChange={(num) => { set_pageData({ ...pageData, income: num ? num : 0 }) }} style={{ width: 160 }} autoFocus defaultValue={pageData.income} onBlur={() => {
                                            set_ifEditIncome(false);
                                        }} />}
                                        {(!ifEditIncome && ifEditTable && auditType == '0') && <div className='editBtn' onClick={() => auditType == '0' ? set_ifEditIncome(true) : () => { }}><img src={editIcon_gray} alt="" /></div>}
                                    </div>
                                </div>
                                <div className='card'>
                                    <span>{ifEditTable ? '材料及药品收入' : '成本'}</span>
                                    <div className='count'>
                                        <span onClick={() => auditType == '0' ? set_ifEditCost(true) : () => { }}>{!ifEditCost && pageData.cost}</span>
                                        {(ifEditCost && ifEditTable) && <InputNumber precision={2} onChange={(num) => { set_pageData({ ...pageData, cost: num ? num : 0 }) }} style={{ width: 160 }} autoFocus defaultValue={pageData.cost} onBlur={() => {
                                            set_ifEditCost(false);
                                        }} />}
                                        {(!ifEditCost && ifEditTable && auditType == '0') && <div className='editBtn' onClick={() => auditType == '0' ? set_ifEditCost(true) : () => { }}><img src={editIcon_gray} alt="" /></div>}
                                    </div>
                                </div>
                                <div className='card'>
                                    <span>{ifEditTable ? '绩效占有效收入比' : '人事成本占比'}</span>
                                    <div className='count'>
                                        <span onClick={() => auditType == '0' ? set_ifEditRate(true) : () => { }}>{!ifEditRate && pageData.rate}</span>
                                        {(ifEditRate && ifEditTable) && <InputNumber precision={4} onChange={(num) => { set_pageData({ ...pageData, rate: num ? num : 0 }) }} style={{ width: 160 }} autoFocus defaultValue={pageData.rate} onBlur={() => {
                                            set_ifEditRate(false);
                                        }} />}
                                        {(!ifEditRate && ifEditTable && auditType == '0') && <div className='editBtn' onClick={() => auditType == '0' ? set_ifEditRate(true) : () => { }}><img src={editIcon_gray} alt="" /></div>}
                                    </div>
                                </div>
                                <div className='card' style={{ background: '#F5F7FA', marginLeft: 8 }}>
                                    <span>可分配奖金（D=(A-B)*C）</span>
                                    <div className='count'>
                                        <InputNumber className={ifEditTable ? 'input borderUpper' : 'input'} size='large' precision={2} min={-10000000} value={pageData.personalCost} placeholder='请输入'
                                            disabled={auditType == '1'}
                                            onChange={(value) => set_pageData({ ...pageData, personalCost: value as number })} />
                                    </div>
                                </div>
                            </div>

                            {/* <div className='func'>
    <div className='title'>
        <span className='a'>{ifEditTable?'可分配奖金(D=(A-B)*C)':'全院人事成本（D=(A-B)*C）'}</span>
        {(!ifBanAllAction&&!ifEditTable)&&<span className='btn' onClick={() => generateFunc(1)}> <IconFont style={{ color: '#3376FE' }} type='iconzhongxin' /> 重新生成</span>}
    </div>
    <InputNumber className={ifEditTable?'input borderUpper':'input'} size='large' precision={2} min={-10000000} value={pageData.personalCost} placeholder='请输入'
        disabled={auditType == '1'}
        onChange={(value) => set_pageData({ ...pageData, personalCost: value as number })} />
</div> */}
                            {/* <div className='midLine'>
    <span>手动计算</span>
    根据手动填写的全院人事成本计算出各职系的
</div> */}

                        </div>
                        {!ifBanAllAction && <div className='countBtn' onClick={() => generateFunc(2)}>开始计算</div>}

                        <div className='tableWrap' style={{ padding: 16, background: '#fff' }}>
                            <div className='b'>计算结果</div>
                            {currentComputeDate && <BMSTable actionRef={tableRef} pagination={false} rowKey='unitType' scroll={{ x: 180 * 11 }} columns={[...tableColumn, {
                                title: '可分配考核奖金',
                                dataIndex: 'assessmentBonus',
                                key: 'assessmentBonus',
                                fixed: 'right',
                                render: (text: any, record: any) => {
                                    if (ifBanAllAction) return text
                                    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 == record.id ? <Input size='small' defaultValue={record.assessmentBonus} width={80} placeholder='请输入' onChange={(e) => { set_inputSalaryNum(Number(e.target.value)) }} style={{ width: '80px' }} /> : <span>{formatMoneyNumber(text)}</span>
                                                }
                                            </div>
                                            {auditType == '0' && <img onClick={() => editHandle(record)} style={{ width: 16, height: 16, cursor: 'pointer', marginLeft: 8 }} src={editTableCellId == record.id ? conformIcon : editIcon} alt="" />}
                                        </div>
                                    )
                                }
                            },]} request={(params, sort, filter) => getPageData(currentComputeDate, params, sort, filter)} />}
                        </div>

                    </>
                )
            }
            {
                currentStep == 2 && pageType == 2 && currentComputeDate && (
                    <Distribute computeDate={currentComputeDate} />
                )
            }

        </BMSPagecontainer>
    )
}


export default PersonnelSalaryBudget;
