/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-01-04 14:12:31
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-04-19 15:07:25
 * @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 { Breadcrumb} from 'antd';
import { useEffect, useRef, useState } from 'react';
import { getData, getRedirReportData } from './service';


import './style.less';


import { create, all, string } from 'mathjs'
import { useParams } from '@umijs/max';

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

// const {search} = location;
// const urlparams = new URLSearchParams(search);

// const urlReportCode = urlparams.get('reportCode') as string


const ReportTemplate = () => {


  const { reportCode:urlReportCode } = useParams();

  const [tableColumn, set_tableColumn] = useState<ProColumns[] | 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 reportJumphandle = (reportData:any)=>{
    console.log({reportData});
    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`],
          params:{
            reportCode:reportData.redirectReportCode,
            parameter
          }
        }
      ]
    );
    set_step(_step);
    
    set_tableDataFilterParams({...tableDataFilterParams,reportCode:reportData.redirectReportCode,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
          ); 
    }

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

    if (resp) {

      const { title,data:assignmentData } = resp;
      const columns = title.map((item: any,index:number) => {
        return {
          title: item.name,
          dataIndex: `${item.columnName}`,
          key: `${item.columnName}`,
          width: 100,
          render:(_:any,record:any)=>{
                  if(item.redirect){
                       return <a className='active' onClick={()=>reportJumphandle({...item,...record})}>{_}</a>
                  } 
                  return <span >{_}</span>
          }

        }
      });
      set_tableColumn([ ...columns]);

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

        let rowData: { [key: string]: any } = {};
        
        for (let i = 0; i < item.length; i++) {
          rowData[`${title[i].columnName}`] = item[i].value
        }
        
        return { ...item, ...rowData,id:Math.random(), columns }
      });

      return {
        data,
        success: true
      }

    }
    return []
  }


  const getCurrentComputeDate = async () => {
    const resp = await getComputeDate();
    set_tableDataFilterParams({...tableDataFilterParams,parameter:{...tableDataFilterParams.parameter,compute_date:resp}});
    set_currentComputeDate(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 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:'首页',
      params:{reportCode:urlReportCode,parameter:{compute_date:currentComputeDate}}
  }])
  }, [urlReportCode]);


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

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


  return (
    <BMSPagecontainer className='ReportTemplate' title={`核算年月：${currentComputeDate}`}>
      <div className='breadcrumb'>
          {
            breadCrumbList.length>1&&breadCrumbList.map((item:any,index:number)=>{
                 return (
                     
                     <span className={index != step?'tab':'tab actived'} key={index} onClick={()=>{index != step && switchHandle(item)}}>{item.name}{index == breadCrumbList.length - 1?'':' / '}</span>
                 )
            })
          }
      </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>

    </BMSPagecontainer>
  )
}

export default ReportTemplate
