/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-01-04 14:12:31
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-08-08 15:23:46
 * @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, ProFormDigit, useRefFunction } from '@ant-design/pro-components';
import { Space, Dropdown, MenuProps, DatePicker, Input, Modal } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { getData, getDataParamType, 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 { number } from 'mathjs';
import { editReportTbaleData, getClolumnTableData } from '@/pages/setting/reportSet/reportSetting/service';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
import { arrayMoveImmutable } from 'array-move';
import SetColWidComponent from './SetColWidComponent';

const { RangePicker } = DatePicker;

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

interface TableRecord {
  [key: string]: any;
}

function searchTableData(data: TableRecord[], query: string, searchableColumns: string[]): TableRecord[] {
  if (!query) return data; // If query is empty, return all data
  const queryLower = query.toLowerCase(); // Convert query to lowercase for case-insensitive search
  return data.filter((record) =>
    searchableColumns.some((column) => {
      return record[column].toString().toLowerCase().includes(queryLower)
    }

    )
  );
}

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

const ReportTemplate = ({ noHeader,reportCode,paramsFromProps }: { noHeader: boolean,reportCode:string,paramsFromProps:any }) => {


  const { reportCode: urlReportCode } = noHeader?{reportCode}:useParams();

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

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

  const [tableDataSource, set_tableDataSource] = useState<any[]>([]);

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

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

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

  const tableRef = useRef<ActionType>();

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

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

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

  const [searchItems, set_searchItems] = useState<any[]>([]);

  const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string | undefined>(undefined);
  const [dataPikerType, set_dataPikerType] = useState(0);
  const [dateComputeDateRange, set_dateComputeDateRange] = useState<string[] | undefined>(undefined);



  const reportJumphandle = (reportData: any) => {

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

    set_tableDataSearchKeywords(undefined);

    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,
        start_date: dateComputeDateRange ? dateComputeDateRange[0] : null,
        end_date: dateComputeDateRange ? dateComputeDateRange[1] : null,
        ...parameter
      }
    });
    currentReportCode = reportData.redirectReportCode;
  }

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


    const { reportCode, parameter } = params;
    // console.log({parameter,params});
    if (!parameter) {
      return {
        data: [],
        success: true
      }
    }

    let resp: any = undefined;

    if (tableDataSearchKeywords != undefined && tableDataSearchKeywords.length > 0) {
      const searchableColumns = searchItems.map((a: any) => a.key); // Columns to search in
      const query = tableDataSearchKeywords; // Search query
      const filteredData = searchTableData(tableDataSource, query, searchableColumns);

      set_tableData(filteredData);
      return {
        data: filteredData,
        success: true
      }
    }



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

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

    if (resp) {

      const { title, data: assignmentData, reportName } = resp;
      const tempArr: { name: any; key: any; }[] = [];
      set_reportName(reportName);
      const columns: ProColumns[] = title.map((item: any, index: number) => {
        if (item.search) {
          tempArr.push({ name: item.name, key: item.columnName });
        }
        return {
          title: item.name,
          dataIndex: `${item.columnName}`,
          key: `${item.columnName}`,
          width: item.width ? item.width : 100,
          ellipsis: true,
          fixed: item.freeze ? true : false,
          hideInTable: item.hide,
          sorter: item.sortStatus ? (a: any, b: any) => {
            return (b[`${item.columnName}`]).toString().localeCompare((a[`${item.columnName}`]).toString())
          } : false,
          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]);
      set_searchItems([...tempArr]);

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

  const getDataPikerType = async (urlReportCode: string) => {
    const resp = await getDataParamType(urlReportCode);
    if (resp) {
      set_dataPikerType(resp.dateType ? resp.dateType : 0);
      if (resp.dateType != 0) {
        set_dateComputeDateRange(resp.dateType == 1 ? [computeDate, computeDate] : [`${computeDate}-01`, `${computeDate}-01`]);
      } else {
        set_dateComputeDateRange([]);
      }
    } else {
      set_dataPikerType(0);
      set_dateComputeDateRange([]);
    }
  }

  const updateTableCol = async (newData: any[]) => {
    let newDataSource = newData.map((a: any, index: number) => {
      //更新排序
      return { ...a, sort: index + 1 }
    })
    const resp = await editReportTbaleData(newDataSource);
    if (resp) {
      tableRef.current?.reload();
    }
  }


  useEffect(() => {
    // 在这里处理路由参数变化的逻辑
    console.log({currentComputeDate});
    if (!currentComputeDate) return;
    if (step == 0) {
      set_tableDataFilterParams({
        reportCode: urlReportCode,
        parameter: {
          compute_date: currentComputeDate,
          start_date: dateComputeDateRange ? dateComputeDateRange[0] : null,
          end_date: dateComputeDateRange ? dateComputeDateRange[1] : null,
          ...paramsFromProps
        }
      });
      set_breadCrumbList([{
        name: '首页',
        index: 0,
        params: {
          reportCode: urlReportCode,
          parameter: dateComputeDateRange ? {
            compute_date: currentComputeDate, start_date: dateComputeDateRange[0],
            end_date: dateComputeDateRange[1],
            ...paramsFromProps
          } : { compute_date: currentComputeDate,...paramsFromProps }
        }
      }]);
    } else {
      set_tableDataFilterParams({
        reportCode: currentReportCode,
        parameter: {
          compute_date: currentComputeDate,
          start_date: dateComputeDateRange ? dateComputeDateRange[0] : null,
          end_date: dateComputeDateRange ? dateComputeDateRange[1] : null,
          ...paramsFromProps
        }
      });
    }

    // set_dateComputeDateRange([]);

  }, [dateComputeDateRange]);

  // useEffect(()=>{
  //   console.log({breadCrumbList});
  // },[breadCrumbList]);


  useEffect(() => {
    if (urlReportCode) {
      getDataPikerType(urlReportCode);
      set_step(0);
    }
  }, [urlReportCode]);




  useEffect(() => {
    getCurrentComputeDate();
    if (urlReportCode) getDataPikerType(urlReportCode);
    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'>
        {!noHeader && (
          <>
            {currentComputeDate && (<div className='search' style={{ display: 'inline-flex' }}>
              <span>核算年月：</span>
              {
                dataPikerType == 0 && (
                  <DatePicker
                    onChange={(data, dateString) => {
                      set_currentComputeDate(dateString);
                      set_dateComputeDateRange([dateString, dateString]);
                      computeDate = dateString;
                    }}
                    disabled={step != 0}
                    allowClear={false}
                    picker='month'
                    locale={locale}
                    defaultValue={moment(currentComputeDate, 'YYYY-MM')}
                    format='YYYY-MM' placeholder="请选择核算年月" />
                )
              }
              {
                dataPikerType == 1 && (
                  <RangePicker
                    onChange={(data, dateString) => {
                      set_dateComputeDateRange(dateString);
                      // computeDate = dateString;
                    }}
                    disabled={step != 0}
                    picker="month"
                    allowClear={false}
                    locale={locale}
                    defaultValue={[moment(currentComputeDate, 'YYYY-MM'), moment(currentComputeDate, 'YYYY-MM')]}
                    format='YYYY-MM'
                  />
                )
              }
              {
                dataPikerType == 2 && (
                  <RangePicker
                    onChange={(data, dateString) => {
                      set_dateComputeDateRange(dateString);
                      // computeDate = dateString;
                    }}
                    picker="date"
                    allowClear={false}
                    locale={locale}
                    defaultValue={[moment(currentComputeDate, 'YYYY-MM-DD'), moment(currentComputeDate, 'YYYY-MM-DD')]}
                    format='YYYY-MM-DD'
                  />
                )
              }

            </div>)}
            {
              searchItems.length > 0 && (
                <div style={{ display: 'inline-flex', flexDirection: 'row', alignItems: 'center', marginLeft: 8 }}>
                  <span style={{ display: 'inline-block', whiteSpace: 'nowrap' }}>检索：</span><Input className='searchInput' allowClear placeholder={searchItems.reduce((prev: string, cur: any) => `${prev.length > 0 ? prev + '/' : prev}${cur.name}`, '')} onChange={(e) => {
                    set_tableDataSearchKeywords(e.target.value);
                    if (e.target.value.length == 0 && !e.target.value) {
                      set_tableDataSearchKeywords(undefined);
                      tableRef.current?.reload();
                    }
                  }} suffix={
                    <IconFont type="iconsousuo" onClick={() => tableRef.current?.reload()} />
                  }
                    onPressEnter={(e) => {
                      tableRef.current?.reload();
                    }}
                  />
                </div>
              )
            }
            {/* <div className='export' style={{ right: 80, width: 75 }}>
          {urlReportCode && < SetColWidComponent reportCode={urlReportCode} onOkHandle={updateTableCol} />}
        </div> */}
            <div className='export' onClick={() => exportHandle()}>导出</div>
          </>
        )}


        <div className='content'>
          {dataPikerType != undefined && <BMSTable actionRef={tableRef} rowKey='id' pagination={false} columns={tableColumn as ProColumns[]}
            params={tableDataFilterParams}
            scroll={{ x: (tableColumn.reduce((prev: number, cur: any) => prev + (cur.width ? cur.width : 100), 0)), y: tableH }}
            request={(params, sort, filter) => getTableData(params, sort, filter)}
          />}
        </div>
      </div>
    </BMSPagecontainer>
  )
}

export default ReportTemplate
