import { createFromIconfontCN } from '@ant-design/icons';

import { ActionType, ProColumns } from '@ant-design/pro-table';
import { Input, Tabs } from 'antd';
import { useEffect, useRef, useState } from 'react';
import 'moment/locale/zh-cn';
import { applyBatchItemValueReq, copyPrePeriodValueReq, generateTableDataReq } from './service';
import './style.less';
import { useModel } from 'umi';
import KCTable from '@/components/kcTable';
import generateTableData from './generateTableData';
import { DATAFILL_PERIODTYPE } from '../fillingMana';

const IconFont = createFromIconfontCN({
  scriptUrl: '../../../../../../public/zhongtaiC.js',
});

type Data = {
  [key: number]: string;
};

type LabelValue = {
  label: string;
  value: number;
};

const defaultYear = new Date().getFullYear();
let total_tableDataSource: any[] = [];

export default function MineFilling() {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');

  const detailTableRef = useRef<ActionType>();

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

  const [reload, set_reload] = useState(false);
  const [currentYear, set_currentYear] = useState(defaultYear);

  const [currentTab, set_currentTab] = useState('1');
  const [disabledState, setDisabledState] = useState<Record<string, boolean>>({});
  const [selectedRows, set_selectedRows] = useState<any[]>([]);

  // 新增：存储本地数据
  const [localData, setLocalData] = useState<{ itemTitles: any[]; itemDatas: any[] }>({ itemTitles: [], itemDatas: [] });

  // 修改：独立的数据生成函数，可以从本地数据生成表格数据
  const generateTableDataFromLocal = () => {
    const { itemTitles, itemDatas } = localData;
    const { columns, dataSource } = generateTableData(itemTitles, itemDatas, { disabledState, setDisabledState, updateTableHandle, currentTab });
    total_tableDataSource = dataSource;

    set_tableColumns(columns);
    set_tableDataSource(dataSource);
  };

  // 修改：获取数据的函数，只负责请求API，不直接依赖generateTableData
  const getGenerateTableData = async () => {
    const resp = await generateTableDataReq({ periodType: currentTab, dataYear: currentYear });
    if (resp) {
      const { itemTitles = [], itemDatas = [] } = resp;
      // 存储数据到本地，避免每次都依赖传入参数
      setLocalData({ itemTitles, itemDatas });
      set_reload(false);
    }
  };

  const updateTableHandle = async (updateData: any, record: any, key: string) => {
    const unEditableColum = tableColumns.filter((a: any) => {
      return !a.editable;
    });

    const result = {
      fillItemCode: record[`${unEditableColum[0].dataIndex}_fillItemCode`],
      dimensionCode: record[`${unEditableColum[0].dataIndex}_dimensionCode`],
      periodCode: key,
      value: updateData,
      dataYear: currentYear,
    };
    const resp = await applyBatchItemValueReq([result]);
    if (resp) {
      set_reload(true);
    }
  };

  const tableDataSearchHandle = (paramName: string) => {
    const result = total_tableDataSource.filter((a: any) => a[`${paramName}`].indexOf(tableDataSearchKeywords) != -1);
    set_tableDataSource(result);
  };

  const tabChangeHandle = (key: string) => {
    // Tab change logic
    set_currentTab(key);
  };

  const copyPrePeriodValueHandle = async () => {
    const result = selectedRows.map((a) => {
      let temp = Object.keys(a)
        .filter((key) => /dimensionCode|fillItemCode/.test(key)) // 只保留包含 "dimensionCode" 或 "fillItemCode" 的键
        .reduce((acc: any, key) => {
          const newKey = key.split('_')[1]; // 移除前缀
          acc[newKey] = a[key]; // 将数据按新键保存
          return acc;
        }, {});

      return {
        fillItemCode: temp.fillItemCode,
        dimensionCode: temp.dimensionCode,
      };
    });

    const resp = await copyPrePeriodValueReq(result);
    if (resp) {
      set_selectedRows([]);
      set_reload(true);
    }
    set_selectedRows([]);
  };

  useEffect(() => {
    getGenerateTableData();
  }, [currentYear, currentTab]);

  useEffect(() => {
    reload && getGenerateTableData();
  }, [reload]);

  useEffect(() => {
    generateTableDataFromLocal();
  }, [disabledState, localData]);

  return (
    <div className="MineFilling">
      <Tabs defaultActiveKey={currentTab} onChange={tabChangeHandle} items={DATAFILL_PERIODTYPE.map((a) => ({ label: a.label, key: `${a.value}` }))} />
      <div className="MineFilling-detail-content">
        <div className="toolBar">
          <div className="filter">
            <div className="filterItem">
              <span className="label" style={{ whiteSpace: 'nowrap' }}>
                {' '}
                检索：
              </span>
              <Input
                placeholder={'填报科室'}
                allowClear
                autoComplete="off"
                suffix={<IconFont type="iconsousuo" style={{ color: '#99A6BF' }} onClick={() => tableDataSearchHandle('fillItemName')} />}
                onChange={(e) => {
                  set_tableDataSearchKeywords(e.target.value);
                  if (e.target.value.length == 0) {
                    set_tableDataSource(total_tableDataSource);
                  }
                }}
                onPressEnter={(e) => {
                  const result = total_tableDataSource.filter((a: any) => a[`fillItemName`].indexOf(tableDataSearchKeywords) != -1);
                  set_tableDataSource(result);
                }}
              />
            </div>
          </div>
          <div className="btnGroup">
            {(currentTab == '1' || currentTab == '2') && (
              <div className="changeBtn">
                <div className="actBtn" onClick={() => set_currentYear(currentYear - 1)}>
                  <IconFont type={'iconshuangzuo'} />
                </div>
                <span style={{ padding: '0 8px' }}>{currentYear}</span>
                <div className="actBtn" onClick={() => set_currentYear(currentYear + 1)}>
                  <IconFont type={'iconshuangyou'} />
                </div>
              </div>
            )}
          </div>
        </div>
        <KCTable
          newVer
          actionRef={detailTableRef}
          columns={[...tableColumns]}
          scroll={{ y: 'calc(100vh - 232px)' }}
          rowKey="id"
          dataSource={tableDataSource}
          pagination={false}
          tableAlertRender={false}
          rowSelection={{
            onChange(selectedRowKeys, selectedRows, info) {
              set_selectedRows(selectedRows);
            },
          }}
        />
      </div>
      {selectedRows.length > 0 && (
        <div className="bottom">
          <div className="info">
            已选择 <span>{selectedRows.length}</span>项，将上期数据带入至本期
          </div>
          <div className="btnGroup">
            <a className="cancel" onClick={() => set_selectedRows([])}>
              取消选择
            </a>
            <a className="confirm" onClick={() => copyPrePeriodValueHandle()}>
              带入上期
            </a>
          </div>
        </div>
      )}
    </div>
  );
}
