/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-01-03 14:20:22
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-07-21 17:53:26
 * @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 } from 'antd';
import React, { useEffect, useRef, useState } from 'react'
import { caculate, checkRequest, editAssessmentBonus, generate, getCurrentCheckStatus, getData } from './service';

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

import './style.less';
import '../../../utils/zhongtaiB'
import { formatMoneyNumber } from '@/utils/format';
import { getJiezhuanStatus } from '../monthlySet/service';

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

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 tableColumn: ProColumns[] = [
        {
            title: '职类',
            dataIndex: 'unitTypeName',
            key: 'unitTypeName',
            fixed:'left'

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

        },
        {
            title: '合理人均薪酬系数',
            dataIndex: 'averageSalary',
            key: 'averageSalary',

        },
        {
            title: '人事成本占比',
            dataIndex: 'percent',
            key: 'percent',
        },
        {
            title: '人事成本',
            dataIndex: 'cost',
            key: 'cost',
            renderText(num, record, index, action) {
                return formatMoneyNumber(num)
            },
        },
        {
            title: '基金',
            dataIndex: 'fundBonus',
            key: 'fundBonus',
            renderText(num, record, index, action) {
                return formatMoneyNumber(num)
            },
        },
        {
            title: '固定工资',
            dataIndex: 'salary',
            key: 'salary',
            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)
            },
        }
    ]

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

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


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


    useEffect(() => {

        getCurrentComputeDate();

    }, []);


    return (
        <BMSPagecontainer className='PersonnelSalaryBudget' title={`核算年月：${currentComputeDate}`} ghost>
            {!ifBanAllAction&&<div className='checkBtn' onClick={() => checkHandle(`${auditType}`)}>{auditType == '0' ? '审核' : '取消审核'}</div>}
            <div className='paramsWrap'>

                <div className='cardWrap'>
                    <div className='card'>
                        <span>收入</span>
                        <div className='count'>{pageData.income}</div>
                    </div>
                    <div className='card'>
                        <span>成本</span>
                        <div className='count'>{pageData.cost}</div>
                    </div>
                    <div className='card'>
                        <span>合理人事成本比例系数</span>
                        <div className='count'>{pageData.rate}</div>
                    </div>
                </div>

                <div className='func'>
                    <div className='title'>
                        <span className='a'>全院人事成本（D=(A-B)*C）</span>
                        {!ifBanAllAction&&<span className='btn' onClick={() => generateFunc(1)}> <IconFont style={{ color: '#3376FE' }} type='iconzhongxin' /> 重新生成</span>}
                    </div>
                    <InputNumber className='input' size='large' 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='b'>计算结果</div>
            {currentComputeDate && <BMSTable actionRef={tableRef} pagination={false} rowKey='unitType'  scroll={{ x: 140 * 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)} />}
        </BMSPagecontainer>
    )
}


export default PersonnelSalaryBudget;
