/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2022-12-16 09:42:52
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-07-24 10:30:44
 * @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 { ProForm, ProFormDateRangePicker, ProFormDigit, ProFormInstance, ProFormMoney } from '@ant-design/pro-components';

import { useEffect, useRef, useState } from 'react';
import 'dayjs/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import './style.less';
import dayjs from 'dayjs';

import {
    editSave,
    getMonthlyData,
    getMonthlyDataRespType,
    jiezhuanGoBack,
    jiezhuanRequest,
    kaizhnagRequest
} from './service';
import { Divider, message, Modal } from 'antd';
import { getComputeDate } from '@/pages/Home/service';
import moment from 'moment';



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

    const dateFormat = 'YYYY-MM-DD';

    const [data, set_data] = useState<getMonthlyDataRespType>();
    const [currentComputeDate, set_currentComputeDate] = useState('');
    const [ifEdit, set_ifEdit] = useState(false);
    const [isSettlementting, set_isSettlementting] = useState(false);

    const [topform] = ProForm.useForm();
    const [midform] = ProForm.useForm();
    const [bottomform] = ProForm.useForm();

    const formRef = useRef<ProFormInstance>();

    const getCurrentComputeDate = async () => {
        const resp = await getComputeDate();
        set_currentComputeDate(resp);
    }

    const getMonthlyDataFunc = async (dateString: string) => {

        const resp = await getMonthlyData(dateString);
        if (isSettlementting) {
            setTimeout(() => {
                set_isSettlementting(false);
                set_data(resp);
            }, 1000)
        } else {
            set_data(resp);
        }
    }

    const editClickHandle = () => {
        set_ifEdit(true);
    }

    const saveHandle = async (prevData: any) => {
        const f = formRef.current?.getFieldFormatValueObject;
        const value = f ? f() : undefined;
        const { dateRange, personalRate, seniority } = value;

        const resp = await editSave({
            computeDate: currentComputeDate,
            ...prevData,
            beginDate: dateRange && dateRange.length > 0 ? dateRange[0] : '',
            endDate: dateRange && dateRange.length > 0 ? dateRange[1] : '',
            personalRate,
            seniority
        });

        if (resp) {
            set_ifEdit(false);  //获取最新数据
        }
    }

    const jiezhuanHandle = (data: any) => {

        Modal.confirm({
            title: '将对当前核算月份进行结转，结转后将进入下一个核算月份，请确认本月工作已经核算完成后进行结转',
            okText: '确定',
            cancelText: '取消',
            onOk: async (...args) => {
                if (!isSettlementting) {
                    //非结转中才可以再次操作
                    // set_isSettlementting(true);

                    const resp = await jiezhuanRequest(data.computeDate);

                    if (resp) {
                        message.success('结转成功！');
                        getCurrentComputeDate();
                    }
                }
            },
        });

    }

    const goBackHandle = () => {

        Modal.confirm({
            title: '当前核算月份未结账，回退后所有已操作数据会作废，请确认是否要进行回退操作',
            okText: '确定',
            cancelText: '取消',
            onOk: async (...args) => {
                const resp = await jiezhuanGoBack(currentComputeDate);
                if (resp) {
                    message.success('回退成功！');
                    getCurrentComputeDate();
                }
            },
        });

    }

    const getStatus = (num: number | undefined) => {

        if (num || num == 0) {
            //状态0未结算 1结算中 2已结算
            if (num == 0) return '未结算';
            if (num == 1) return '结算中';
            if (num == 2) return '已结算';

        } else {
            return '无效status'
        }

    }

    const kaizhangHandle = () => {
        Modal.confirm({
            title: '是否确定开帐？',
            onOk:async (...args)=>{
                const resp = await kaizhnagRequest(currentComputeDate);
                if (resp) {
                    getMonthlyDataFunc(currentComputeDate);
                }
            },
        })
    }

    useEffect(() => {
        if (!ifEdit) {
            //取消编辑时刷新数据
            getCurrentComputeDate();
        }
    }, [ifEdit]);

    useEffect(() => {
        if (data) {
            topform.setFieldsValue({
                personalRate: data.lastCarry.personalRate,
                seniority: data.lastCarry.seniority,
                dateRange: [dayjs(data.lastCarry.beginDate ? data.lastCarry.beginDate : '1997-01-01', dateFormat), dayjs(data.lastCarry.endDate ? data.lastCarry.endDate : '1997-01-01', dateFormat)],
            });
            midform.setFieldsValue({
                personalRate: data.currentCarry.personalRate,
                seniority: data.currentCarry.seniority,
                dateRange: [dayjs(data.currentCarry.beginDate ? data.currentCarry.beginDate : '1997-01-01', dateFormat), dayjs(data.currentCarry.endDate ? data.currentCarry.endDate : '1997-01-01', dateFormat)],
            });
            bottomform.setFieldsValue({
                personalRate: data.preCarry.personalRate,
                seniority: data.preCarry.seniority,
                dateRange: [dayjs(data.preCarry.beginDate ? data.preCarry.beginDate : '1997-01-01', dateFormat), dayjs(data.preCarry.endDate ? data.preCarry.endDate : '1997-01-01', dateFormat)],
            });
        }
    }, [data])

    useEffect(() => {
        //改变计算月份触发刷新数据
        if (currentComputeDate) {
            getMonthlyDataFunc(currentComputeDate);
        }
    }, [currentComputeDate]);


    useEffect(() => {
        getCurrentComputeDate();
    }, []);



    return (
        <BMSPagecontainer className='MonthlySet' title={`月度结转 ${currentComputeDate}`} ghost>
            <div style={{ height: 16 }}> </div>
            <div className='card'>
                <div className='mark'>{getStatus(data?.lastCarry.status)}</div>
                <div className='cardTitle'>{data?.lastCarry.computeDate}月<span>下一个核算月份</span></div>
                <div className='formWrap'>
                    {data && (
                        <ProForm submitter={false} layout='vertical' grid={true}
                            form={topform}
                            // initialValues={{
                            //     personalRate: data.lastCarry.personalRate,
                            //     seniority: data.lastCarry.seniority,
                            //     dateRange: [dayjs(data.lastCarry.beginDate ? data.lastCarry.beginDate : '1997-01-01', dateFormat), dayjs(data.lastCarry.endDate ? data.lastCarry.endDate : '1997-01-01', dateFormat)],
                            // }}
                            rowProps={{
                                gutter: [24, 0],
                            }} >
                            <ProForm.Group >
                                <ProFormDateRangePicker disabled name="dateRange" width={'lg'} fieldProps={{ locale: locale }} label="日期区间：" colProps={{ span: 8 }} />

                                <ProFormDigit
                                    disabled
                                    label="人事成本比例系数："
                                    name="personalRate"
                                    colProps={{ span: 8 }}
                                    width='lg'
                                    placeholder='请输入'
                                    fieldProps={{ precision: 4 }}
                                />

                                <ProFormDigit
                                    disabled
                                    colProps={{ span: 8 }}
                                    label="年资系数："
                                    name="seniority"
                                    placeholder='请输入'
                                    fieldProps={{ precision: 2 }}
                                />

                            </ProForm.Group>
                        </ProForm>
                    )}

                </div>
            </div>
            <div className='colorBtn' onClick={() => jiezhuanHandle(data?.currentCarry)}>{isSettlementting ? '结转中...' : '结转'}</div>
            <div className='card on'>
                <div className='mark caculating'>{getStatus(data?.currentCarry.status)}</div>
                <div className='cardTitle'>
                    {data?.currentCarry.computeDate}<span>当前核算月份</span>
                    {(!ifEdit && data?.currentCarry.status != 2) && <a onClick={() => editClickHandle()}>编辑</a>}
                    {(!ifEdit && data?.currentCarry.status == 2) && <a onClick={() => kaizhangHandle()}>开帐</a>}

                    {
                        ifEdit && (
                            <div className='editActBtnGroup'>
                                <a onClick={() => set_ifEdit(false)}>取消</a>
                                <Divider type="vertical" style={{ position: 'relative', top: 2 }} />
                                <a onClick={() => saveHandle(data?.currentCarry)}>保存</a>
                            </div>
                        )
                    }

                </div>
                <div className='formWrap'>

                    {
                        data && (
                            <ProForm submitter={false} layout='vertical' grid={true}
                                form={midform}
                                // initialValues={{
                                //     personalRate: data.currentCarry.personalRate,
                                //     seniority: data.currentCarry.seniority,
                                //     dateRange: [moment(data.currentCarry.beginDate ? data.currentCarry.beginDate : '1997-01-01', dateFormat), moment(data.currentCarry.endDate ? data.currentCarry.endDate : '1997-01-01', dateFormat)],
                                // }}
                                rowProps={{
                                    gutter: [16, 0],
                                }}
                                formRef={formRef}
                            >
                                <ProForm.Group>
                                    <ProFormDateRangePicker name="dateRange" disabled={!ifEdit} fieldProps={{ locale: locale }} label="日期区间：" colProps={{ span: 8 }} width='lg' />

                                    <ProFormDigit
                                        disabled={!ifEdit}
                                        label="人事成本比例系数："
                                        name="personalRate"
                                        min={0}
                                        colProps={{ span: 8 }}
                                        width='lg'
                                        placeholder='请输入'
                                        fieldProps={{ precision: 4 }}
                                    />

                                    <ProFormDigit
                                        disabled={!ifEdit}
                                        colProps={{ span: 8 }}
                                        width='lg'
                                        label="年资系数："
                                        name="seniority"
                                        min={0}
                                        placeholder='请输入'
                                        fieldProps={{ precision: 2 }}
                                    />
                                </ProForm.Group>
                            </ProForm>
                        )
                    }

                </div>
            </div>
            <div className='grayBtn' onClick={() => goBackHandle()}>回退</div>
            <div className='card'>
                <div className='mark compeleted'>{getStatus(data?.preCarry.status)}</div>
                <div className='cardTitle'>{data?.preCarry.computeDate}<span>上一个核算月份</span></div>
                <div className='formWrap'>
                    {
                        data && (
                            <ProForm submitter={false} layout='vertical' grid={true}
                                form={bottomform}
                                // initialValues={{
                                //     personalRate: data.preCarry.personalRate,
                                //     seniority: data.preCarry.seniority,
                                //     dateRange: [moment(data.preCarry.beginDate ? data.preCarry.beginDate : '1997-01-01', dateFormat), moment(data.preCarry.endDate ? data.preCarry.endDate : '1997-01-01', dateFormat)],
                                // }}
                                rowProps={{
                                    gutter: [16, 0],
                                }} >
                                <ProForm.Group>
                                    <ProFormDateRangePicker disabled name="dateRange" fieldProps={{ locale: locale }} label="日期区间：" colProps={{ span: 8 }} width='lg' />

                                    <ProFormDigit
                                        disabled
                                        label="人事成本比例系数："
                                        name="personalRate"
                                        min={0}
                                        colProps={{ span: 8 }}
                                        width='lg'
                                        placeholder='请输入'
                                        fieldProps={{ precision: 4 }}
                                    />

                                    <ProFormDigit
                                        disabled
                                        colProps={{ span: 8 }}
                                        width='lg'
                                        label="年资系数："
                                        name="seniority"
                                        min={0}
                                        placeholder='请输入'
                                        fieldProps={{ precision: 2 }}
                                    />
                                </ProForm.Group>
                            </ProForm>
                        )
                    }
                </div>
            </div>
        </BMSPagecontainer>
    );

};

export default MonthlySet;