/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-01-04 14:12:31
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-03-08 11:08:33
 * @FilePath: /BudgetManaSystem/src/pages/budgetMana/oneBatch/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 { ActionType, ProColumns } from '@ant-design/pro-components';
import { message, Modal, Popover, Table, Tabs } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { caculate, checkRequest, getCurrentCheckStatus, getData } from './service';


import './style.less';


import { create, all } from 'mathjs'

const config = {
  number: 'number',
  precision: 14
}
const math = create(all, config as any);




const OneBatch = () => {


  const [tableColumn, set_tableColumn] = useState<ProColumns[] | any[]>([]);

  const [currentComputeDate, set_currentComputeDate] = useState<string | undefined>();

  const [currentTabKey, set_currentTabKey] = useState('1');

  const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>({ reportCode: undefined });

  const [auditType, set_auditType] = useState('0');

  const [ifShowTip, set_ifShowTip] = useState(false);

  const tableRef = useRef<ActionType>();

  const [tableH, set_tableH] = useState(0);


  const onTabChange = (activeKey: string) => {
    set_currentTabKey(activeKey);
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      reportCode: activeKey
    })
  }

  const getTableData = async (params: any, sort: any, filter: any) => {

    const { reportCode = 1 } = params;

    const resp: any = await getData(
      currentComputeDate as string,
      reportCode
    );

    if (resp) {

      const { title, assignmentData } = resp;
      const columns = title.map((item: any) => {
        return {
          title: item.name,
          dataIndex: `${item.code}`,
          key: `${item.code}`,
          width: 140,
   
        }
      });
      set_tableColumn([{
        title: '核算单元',
        dataIndex: 'unitName',
        key: 'unitName',
        width: 140,
        fixed: 'left',
       
      }, ...columns, {
        title: '总奖金',
        dataIndex: 'totalScore',
        key: 'totalScore',
        width: 140,
        fixed: 'right',
       
      }]);

      const data = assignmentData.map((item: any) => {

        let rowData: { [key: string]: any } = {};

        for (let index = 0; index < item.value.length; index++) {
          for (const key in item.value[index]) {

            if (key != 'code') {
              rowData[`${item.value[index].code}`] = item.value[index].value
            }
          }
        }

        return { ...item, ...rowData, id: item.id, columns }
      });

      return {
        data,
        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 confirmCaculateHandle = async () => {
    const resp = await caculate(currentComputeDate as string);
    if (resp) {
      tableRef.current?.reload();
    }
  }


  const getCheckStatus = async (computeDate: string) => {
    const resp = await getCurrentCheckStatus(computeDate);
    if (resp) {
        set_auditType(`${resp}`);  //0 未审核 1 已审核
    }
  }

  const generateFunc = () => {

    Modal.confirm({
      title: '注意',
      cancelText: '',
      closable: true,
      content: '计算会覆盖原有数据，确定要继续计算操作？',
      onOk: () => confirmCaculateHandle()
    })
  }

  const handleResize = (e: any) => {
    const wH = e.target.innerHeight;
    const tableHeight = wH - 290;
    set_tableH(tableHeight);
  }

  function doResize() {
    setTimeout(() => {
      const ev: any = new Event('resize');
      window.dispatchEvent(ev);
    }, 0)
  }


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


  useEffect(() => {
    getCurrentComputeDate();
    window.addEventListener('resize',(e)=>handleResize(e)) //监听窗口大小改变
    doResize();

    return ()=>{
      window.removeEventListener('resize',(e)=>handleResize(e))
    }
  }, [])


  return (
    <BMSPagecontainer className='OneBatch' title={`核算年月：${currentComputeDate}`}>
      <div className='btnGroup'>
        <Popover open={ifShowTip} content={'当前处于审核中，无法操作！'} >
          <div className={auditType == '0' ? 'caculateBtn' : 'caculateBtn disabled'}
            onMouseEnter={() => auditType == '0' ? set_ifShowTip(false) : set_ifShowTip(true)}
            onMouseLeave={() => set_ifShowTip(false)}
            onClick={() => auditType == '0' ? generateFunc() : () => { }}>计算</div>
        </Popover>
        <div className='checkBtn' onClick={() => checkHandle(`${auditType}`)}>{auditType == '0' ? '审核' : '取消审核'}</div>
      </div>
      <div className='content'>
        <Tabs
          defaultActiveKey='1'
          onChange={onTabChange}
          items={[
            {
              label: `临床医生`,
              key: '1',
            },
            {
              label: `医技`,
              key: '2',
            },
            {
              label: `护理`,
              key: '3',
            },
            {
              label: `行政`,
              key: '4',
            },
          ]}
        />
        <div className='tabContent'>
          {currentComputeDate && <BMSTable actionRef={tableRef} rowKey='unitCode' pagination={false} columns={tableColumn as ProColumns[]}
            params={tableDataFilterParams}
            scroll={{ x: 140 * 10, y:tableH }}
            request={(params, sort, filter) => getTableData(params, sort, filter)}

            summary={(pageData) => {
              const Caculate = ({ colData }: { colData: any }) => {

                const { dataIndex } = colData;

                const total = pageData.reduce((prev, cur) => {
                  //return prev + cur[`${dataIndex}`]
                  if (typeof cur[`${dataIndex}`] == 'number') {
                    return math.add(prev, cur[`${dataIndex}`] as number);
                  }
                }, 0);

                return (
                  //<span>{typeof total == 'number'?math.format(total, {precision: 14}) : '合计'}</span>
                  <span>{typeof total == 'number' ? Number(total.toFixed(4)) : '合计'}</span>
                )
              }


              return (
                <Table.Summary fixed>
                  <Table.Summary.Row>
                    {
                      tableColumn.map((item, index) => {
                        return (
                          <Table.Summary.Cell key={index} index={index} align='center' rowSpan={1} >
                            <Caculate colData={item} />
                          </Table.Summary.Cell >
                        )
                      })
                    }
                  </Table.Summary.Row>
                </Table.Summary>
              );
            }}

          />}
        </div>
      </div>

    </BMSPagecontainer>
  )
}

export default OneBatch
