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


import './style.less';

import { useParams } from '@umijs/max';
import { createFromIconfontCN, DownOutlined } from '@ant-design/icons';

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 KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import { getStringWidth } from '@/utils/tooljs';

import ExportProgressModal from './ExportProgressModal';
import { getParamsDataBySysId } from '@/services/getDic';
import { useModel } from '@umijs/max';


const IconFont = createFromIconfontCN({
  scriptUrl: '',
});

interface Searchable {
  [key: string]: string;
}


let searchKeys: any[] = [];
let totalTableData: any[] = [];
let tableDataSearchKeywords: undefined | string = undefined;
let currentPage = 0;
let maxFetchCount = 0;



const ReportExport = () => {


  const { reportCode: urlReportCode } = useParams();

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

  const [tableScrollX, set_tableScrollX] = useState<number>(1000);

  const { initialState,setInitialState } = useModel('@@initialState');
  const [currentComputeDate, set_currentComputeDate] = useState<string | undefined>(initialState?initialState.computeDate:undefined);

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

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

  const tableRef = useRef<ActionType>();

  const [loading, set_loading] = useState(false);

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

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

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

  const [pageSize, set_pageSize] = useState(20);
  const [openProcessModal, set_openProcessModal] = useState(false);


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

    totalTableData = [];
    currentPage = 0;
  }


  const getTableData = async (params: any) => {

    const { systemId } = JSON.parse(localStorage.getItem('currentSelectedTab') as string)
    const paramsData = await getParamsDataBySysId(systemId, '1806523783696224256');
    const pageSize = paramsData.value?Number(paramsData.value):100;
    set_pageSize(pageSize);    
    const { parameter, current, reportCode } = params;
    
    searchKeys = [];
    let resp: any = undefined;


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

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

    if (resp) {

      const { title, data: assignmentData, reportName, current, totalCount, totalPage, pageSize } = resp;
      set_reportName(reportName);

      let scrollX = 0;
      const columns: ProColumns[] = title.map((item: any, index: number) => {
        if (item.search) {
          searchKeys.push({ name: item.name, key: item.columnName });
        }
        const wid = (item.name.length * 17) > 100 ? (item.name.length * 17): 100;
        scrollX = scrollX + wid;
        // console.log({[`${item.name}`]:wid});
        return {
          title: item.name,
          dataIndex: `${item.columnName}`,
          key: `${item.columnName}`,
          width:wid ,
          ellipsis: true,
          fixed: item.freeze ? true : false,
          hideInTable: item.hide,
          sorter: item.sortStatus ? (a: any, b: any) => {
            if (item.dataType == 3) {
              //数值
              return b[`${item.columnName}`] - (a[`${item.columnName}`]);
            } else {
              return b[`${item.columnName}`]?.localeCompare(a[`${item.columnName}`]);
            }
          } : undefined,
          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 == 3 && _) && formatMoneyNumber(Number(Number(_).toFixed(item.decimalPlace ? item.decimalPlace : 2)))}
                      {(item.dataType && item.dataType == 2 && _ && typeof _ == 'number') && `${(_ * 100).toFixed(item.decimalPlace ? item.decimalPlace : 2)}%`}
                      {(item.dataType != 2 && item.dataType != 3) && _}
                      <DownOutlined />
                    </Space>
                  </a>
                </Dropdown>
              } else {
                return <a className='active' onClick={() => reportJumphandle({ ...item.redirectData[0], ...record })}>
                  {(item.dataType && item.dataType == 3 && _) && formatMoneyNumber(Number(Number(_).toFixed(item.decimalPlace ? item.decimalPlace : 2)))}
                  {(item.dataType && item.dataType == 2 && _ && typeof _ == 'number') && `${(_ * 100).toFixed(item.decimalPlace ? item.decimalPlace : 2)}%`}
                  {(item.dataType != 2 && item.dataType != 3) && _}
                </a>
              }
            }

            return <span >
              {(item.dataType && item.dataType == 3 && _) && formatMoneyNumber(Number(Number(_).toFixed(item.decimalPlace ? item.decimalPlace : 2)))}
              {(item.dataType && item.dataType == 2 && _ && typeof _ == 'number') && `${(_ * 100).toFixed(item.decimalPlace ? item.decimalPlace : 2)}%`}
              {(item.dataType != 2 && item.dataType != 3) && _}
            </span>
          }

        }
      });

      set_tableColumn([...columns]);
      set_tableScrollX(scrollX);

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

      const exportdata = 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) {
            if (needTitle[0].dataType == 2 && typeof b.value == 'number') {
              rowData[`${needTitle[0].columnName}`] = `${(b.value * 100).toFixed(needTitle[0].decimalPlace ? needTitle[0].decimalPlace : 2)}%`
            } else {
              rowData[`${needTitle[0].columnName}`] = b.value
            }
          }
        });


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

      // set_tableData(data);
      set_loading(false);



      if (openProcessModal) {
        totalTableData = [...totalTableData, ...exportdata];
        return {
          currentCount: totalTableData.length,
          totalCount,
          totalPage
        }
      }

      if (!openProcessModal) {
        return {
          data: data,
          success: true,
          total: totalCount,
          pageSize: pageSize,
          totalPage: totalPage,
        }
      }

    }
    return openProcessModal ? { currentCount: 0, totalCount: 0 } : []
  }


  // const tableDataSearchHandle = () => {
  //   if (tableDataSearchKeywords) {
  //     const keys = searchKeys.map(a => a.key);
  //     const result = multiAttributeSearchOptimized(totalTableData, keys, [tableDataSearchKeywords as string]);
  //     set_tableData(result);

  //   } else {
  //     set_tableData(totalTableData);
  //   }

  // }



  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 = () => {
    // set_openProcessModal(true);

    let headers: { [key: string]: any } = {};
    let data: any[] = [];

    tableColumn.forEach(a => {
      if (a.hideInTable != 1) {
        headers[`${a.dataIndex}`] = a.title;
      }
    });

    totalTableData.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
    ];

    const _columns = tableColumn.filter(a => a.hideInTable != 1);

    exportTableToExcel(excelTableData, _columns as any[], reportName);
    currentPage = 0;
    maxFetchCount = 0;
    totalTableData = [];
    // tableRef.current?.reload();
  }


  const fetchExportData = async () => {

    currentPage = currentPage + 1;

    const resp: any = await getTableData({ ...tableDataFilterParams, current: currentPage });

    if (resp) {
      const { currentCount = 0, totalCount = 0, totalPage } = resp;

      maxFetchCount = totalPage;
      return { currentCount, totalCount };
    } else {
      return { currentCount: 0, totalCount: 0 };
    }
  };

  const handleCompletion = () => {
    set_openProcessModal(false);
    exportHandle();

  }


  //面包屑跳转
  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(() => {

    if (currentComputeDate) {
      set_tableDataFilterParams({ ...tableDataFilterParams, parameter: { ...(tableDataFilterParams?.parameter ?? {}), compute_date: currentComputeDate } });
    }
  }, [currentComputeDate]);





  useEffect(() => {

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

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


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

      <ExportProgressModal
        visible={openProcessModal}
        onCancel={() => set_openProcessModal(false)}
        fetchData={fetchExportData}
        onCompletion={handleCompletion}
      />

      {
        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);
              setInitialState((s:any)=>({...s,computeDate:dateString}))
            }}
            allowClear={false}
            picker='month'
            locale={locale}
            value={moment(currentComputeDate, 'YYYY-MM')}
            format='YYYY-MM' placeholder="请选择核算年月" />

          {/* <div style={{ display:searchKeys.length>0?'flex':'none', flexDirection: 'row', alignItems: 'center', marginLeft: 16 }}>
            <span style={{ whiteSpace: 'nowrap' }}>检索：</span>
            <ProFormText
              noStyle
              // style={{width:(searchKeys.length)*20}}
              width={(searchKeys.length)*100}
              placeholder={`${searchKeys.reduce((prev, cur) => `${prev.length>0?prev+'/':prev}` + cur.name, '')}`}
              fieldProps={{
                suffix:
                  < IconFont type="iconsousuo" style={{ color: '#99A6BF' }} onClick={() => tableDataSearchHandle()} />
                ,
                onChange: (e) => {
                    if(e.target.value){
                      tableDataSearchKeywords = e.target.value
                    }else{
                      tableDataSearchKeywords = undefined;
                      tableDataSearchHandle();
                    }
                },
                onPressEnter: (e) => tableDataSearchHandle()
              }}
            />
          </div> */}

        </div>)}
        <div className='export' onClick={() => set_openProcessModal(true)}>导出</div>

        <div className='content'>
          {currentComputeDate && <KCIMTable actionRef={tableRef} rowKey='id' columns={tableColumn as ProColumns[]}
            params={tableDataFilterParams}
            // loading={loading}
            scroll={{ x: tableScrollX, y: tableH }}
            // dataSource={tableData}
            pagination={{ pageSizeOptions: [10, 20, 50, 100, 1000], showSizeChanger: true,pageSize }}
            request={(params, sort, filter) => getTableData(params)}
          />}
        </div>
      </div>
    </KCIMPagecontainer>
  )
}

export default ReportExport
