/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-01-04 14:12:31
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-12-08 15:20:58
 * @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 { Space, Dropdown, MenuProps, DatePicker } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { getData, getRedirReportData } from './service';


import './style.less';

import { useParams } from '@umijs/max';
import { DownOutlined } from '@ant-design/icons';
import { useLocation } from '@umijs/max';
import exportTableToExcel from '@/utils/tableToExcel';


import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import moment from 'moment';
import { formatMoneyNumber } from '@/utils/format';
import { number } from 'mathjs';



// const {search} = locatio
let computeDate:any = undefined;

const ReportTemplate = () => {


  const { reportCode: urlReportCode } = useParams();

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

  const [tableData, set_tableData] = useState<any[]>([]);

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

  const [breadCrumbList, set_breadCrumbList] = useState<any[]>([]);

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

  const tableRef = useRef<ActionType>();

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

  const [step, set_step] = useState(0);

  const [reportName, set_reportName] = useState('')

  const reportJumphandle = (reportData: any) => {

    let parameter: { [key: string]: any } = {};
    const { redirectParameter = undefined } = reportData;
    const _step = step + 1;

    if (redirectParameter) {
      const tempArr = redirectParameter.split('|');
      tempArr.forEach((element: string) => {
        parameter[`${element}`] = reportData[`${element}`]
      });
    }

    set_breadCrumbList(
      [...breadCrumbList,
      {
        index: _step,
        name: reportData[`report_name`] || reportData[`redirectReportName`],
        params: {
          reportCode: reportData.redirectReportCode,
          parameter: {
            ...parameter,
          }
        }
      }
      ]
    );

    set_step(_step);

    set_tableDataFilterParams({
      ...tableDataFilterParams, reportCode: reportData.redirectReportCode, parameter: {
        compute_date: currentComputeDate,
        ...parameter
      }
    })
  }


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

    const { reportCode, parameter } = params;

    let resp: any = undefined;

    if (step != 0) {
      //报表跳转
      resp = await getRedirReportData(
        reportCode,
        {...parameter,compute_date:computeDate,}
      );
    }

    if (step == 0) {
      //首次获取表格数据
      resp = await getData(
        reportCode,
        {...parameter,compute_date: currentComputeDate,}
      );
    }

    if (resp) {

      const { title, data: assignmentData, reportName } = resp;
      set_reportName(reportName);
      const columns: ProColumns[] = title.map((item: any, index: number) => {
        return {
          title: item.name,
          dataIndex: `${item.columnName}`,
          key: `${item.columnName}`,
          width: item.name.length * 25,
          ellipsis: true,
          fixed: item.freeze?true:false,
          hideInTable: item.hide,
          renderText:(_:string|number, record:any) => {
    
            if (item.redirect) {
              if (item.redirectData && item.redirectData.length > 1) {

                const items: MenuProps['items'] = [
                  ...(item.redirectData.map((a: any, index: number) => ({
                    key: index,
                    label: (
                      <a onClick={() => reportJumphandle({ ...item, ...record, ...a })}>
                        {a.redirectReportName}
                      </a>
                    ),
                  })))
                ];

                return <Dropdown menu={{ items }}>
                  <a onClick={(e) => e.preventDefault()}>
                    <Space>
                      {(item.dataType && item.dataType == 2 && _) ? formatMoneyNumber(Number(Number(_).toFixed(2))) : _}
                      <DownOutlined />
                    </Space>
                  </a>
                </Dropdown>
              } else {
                return <a className='active' onClick={() => reportJumphandle({ ...item.redirectData[0], ...record })}>{(item.dataType && item.dataType == 2 && _) ? Number(Number(_).toFixed(2)) : _}</a>
              }
            }

            return <span >{(item.dataType && item.dataType == 2 && _) ? formatMoneyNumber(Number(Number(_).toFixed(2))) : _}</span>
          }

        }
      });

      set_tableColumn([...columns]);

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

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

        item.forEach((b: any) => {
          const needTitle = title.filter((a: any) => a.code == b.code);
          if (needTitle.length > 0) {
            rowData[`${needTitle[0].columnName}`] = b.value
          }
        });


        return { ...item, ...rowData, id: Math.random(), columns }
      });
      set_tableData(data);
      return {
        data,
        success: true
      }

    }
    return []
  }


  const getCurrentComputeDate = async () => {
    const resp = await getComputeDate();
    set_tableDataFilterParams({ ...tableDataFilterParams, parameter: { ...tableDataFilterParams.parameter, compute_date: resp } });
    set_currentComputeDate(resp);
    computeDate = resp;
  }


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

  const exportHandle = () => {

    //const headers = { name: '姓名', age: '年龄', city: '城市' };
    let headers: { [key: string]: any } = {};
    let data: any[] = [];
    tableColumn.forEach(a => {
      if (a.hideInTable != 1) {
        headers[`${a.dataIndex}`] = a.title;
      }
    });

    tableData.forEach(b => {
      let _temp: { [key: string]: any } = {};
      Object.keys(headers).forEach(key => {
        _temp[`${key}`] = b[`${key}`]
      });
      data.push(_temp);
    });

    //console.log({tableColumn,headers,tableData,data});
    const excelTableData = [
      ...data
    ];

    exportTableToExcel(excelTableData, tableColumn as any[], reportName);
  }


  //面包屑跳转
  const switchHandle = (data: any) => {
    set_step(data.index);
    const _breadCrumbList = breadCrumbList.filter((a: any) => a.index <= data.index);
    set_breadCrumbList([..._breadCrumbList]);
    set_tableDataFilterParams({ ...tableDataFilterParams, ...data.params });
  }


  useEffect(() => {
    // 在这里处理路由参数变化的逻辑
    set_tableDataFilterParams({ reportCode: urlReportCode, parameter: { compute_date: currentComputeDate } });
    set_breadCrumbList([{
      name: '首页',
      index: 0,
      params: { reportCode: urlReportCode, parameter: { compute_date: currentComputeDate } }
    }])

  }, [urlReportCode]);


  useEffect(()=>{
    set_tableDataFilterParams({ reportCode: urlReportCode, parameter: { compute_date: currentComputeDate } });
  },[currentComputeDate])

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

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


  return (
    <BMSPagecontainer className='ReportTemplate' title={false}>

      {
        breadCrumbList.length > 1 && <div className='breadcrumb'>
          {
            breadCrumbList.map((item: any, index: number) => {
              return (
                <>
                  <span className={index != step ? 'tab' : 'tab actived'} key={index} onClick={() => { index != step && switchHandle(item) }}>{item.name}</span>{index == breadCrumbList.length - 1 ? '' : <span style={{ color: '#7A8599' }}> / </span>}
                </>
              )
            })
          }
        </div>
      }
      <div className='contentWrap'>
        {currentComputeDate && (<div className='search'>
          <span>核算年月：</span>
          <DatePicker
            onChange={(data, dateString) => {
              set_currentComputeDate(dateString);
              computeDate = dateString;
            }}
            allowClear={false}
            picker='month'
            locale={locale}
            defaultValue={moment(currentComputeDate, 'YYYY-MM')}
            format='YYYY-MM' placeholder="请选择核算年月" />
        </div>)}
        <div className='export' onClick={() => exportHandle()}>导出</div>

        <div className='content'>
          {currentComputeDate && <BMSTable actionRef={tableRef} rowKey='id' pagination={false} columns={tableColumn as ProColumns[]}
            params={tableDataFilterParams}
            scroll={{ x: 100 * tableColumn.length, y: tableH }}
            request={(params, sort, filter) => getTableData(params, sort, filter)}
          />}
        </div>
      </div>
    </BMSPagecontainer>
  )
}

export default ReportTemplate
