/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-01-03 14:20:22
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-03-08 11:09:01
 * @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, generate, getCurrentCheckStatus, getData } from './service';

import './style.less';

const IconFont = createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/c/font_1927152_gfxzp431jpt.js',
  });

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 tableRef = useRef<ActionType>();
    
    const [loading,set_loading] = useState(false);

    const tableColumn = [
        {
            title: '职类',
            dataIndex: 'unitTypeName',
            key: 'unitTypeName',
         
        },
        {
            title: '合理编制比例',
            dataIndex: 'staffRate',
            key: 'staffRate',
       
        },
        {
            title: '合理人均薪酬系数',
            dataIndex: 'averageSalary',
            key: 'averageSalary',
          
        },
        {
            title: '人事成本占比',
            dataIndex: 'percent',
            key: 'percent',
          
        },
        {
            title: '人事成本',
            dataIndex: 'cost',
            key: 'cost',
           
        },
        {
            title: '固定工资',
            dataIndex: 'salary',
            key: 'salary',
          
        },
        {
            title: '专项补助',
            dataIndex: 'subsidies',
            key: 'subsidies',
          
        },
        {
            title: '变动薪酬',
            dataIndex: 'variableCompensation',
            key: 'variableCompensation',
          
        },
        {
            title: '考核奖金',
            dataIndex: 'assessmentBonus',
            key: 'assessmentBonus',
            
        },
    ]

    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 generateFunc =async (computeDate:string) => {
    //     const resp = await generate(computeDate);
        
    // }

    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: '注意',
                cancelText: '',
                closable: true,
                content: '当前处于审核状态无法操作！',
            });
            return;
        }

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


    }


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


    useEffect(() => {

        getCurrentComputeDate();

    }, []);


    return (
        <BMSPagecontainer className='PersonnelSalaryBudget' title={`核算年月：${currentComputeDate}`} ghost>
            <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>
                        <span className='btn' onClick={()=>generateFunc(1)}> <IconFont  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>
            <div className='countBtn' onClick={()=>generateFunc(2)}>计算</div>
            <div className='b'>计算结果</div>
            {currentComputeDate&&<BMSTable actionRef={tableRef} pagination={false} rowKey='unitType' columns={tableColumn as ProColumns[]} request={(params, sort, filter) => getPageData(currentComputeDate,params, sort, filter)} />}
        </BMSPagecontainer>
    )
}


export default PersonnelSalaryBudget;
