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

/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2025-02-14 17:50:16
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-02-28 14:45:09
 * @FilePath: /MediResourceManaSys/src/pages/dataFilling/fillingMana/generateTableData.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { Input, Modal, Popover, Tooltip } from 'antd';
import AuthHisContent from './authHisttory';
import { ProFormDigit } from '@ant-design/pro-form';
import { useState } from 'react';

type HistoryItem = {
  value: number;
  createTime: string;
};

type ItemDic = {
  code: string;
  name: string;
  type: number;
  unit: string;
  status: number;
  periodType: number;
  description: string;
  dimensionType: number;
};

type ItemData = {
  code: string;
  value: any;
  history?: HistoryItem[];
  itemDic?: ItemDic;
  [key: string]: any;
};

type ItemTitle = {
  currentPeriod: any;
  type: number;
  code: string;
  name: string;
};

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

// 获取当前日期
const currentDate = new Date();

// 获取当前月份
const currentMonth = currentDate.getMonth();

// 获取上一个月的月份（注意：getMonth() 返回的是 0-11 的值，所以需要减去 1）
const _lastMonth = currentMonth === 0 ? 11 : currentMonth - 1;
const lastMonth = _lastMonth + 1; //加 1 是为了将月份转换为 1-12 的格式

function getPreviousQuarter() {
  const date = new Date();
  const currentMonth = date.getMonth();
  let previousQuarter;

  // 根据当前月份确定上一个季度
  if (currentMonth >= 0 && currentMonth <= 2) {
    previousQuarter = 4; // 当前是第一季度，上一个季度是第四季度
  } else if (currentMonth >= 3 && currentMonth <= 5) {
    previousQuarter = 1; // 当前是第二季度，上一个季度是第一季度
  } else if (currentMonth >= 6 && currentMonth <= 8) {
    previousQuarter = 2; // 当前是第三季度，上一个季度是第二季度
  } else {
    previousQuarter = 3; // 当前是第四季度，上一个季度是第三季度
  }

  return previousQuarter;
}

function getPreviousYear() {
  const date = new Date();
  const currentYear = date.getFullYear();

  // 返回上一年度的年份
  return currentYear - 1;
}

export default function generateTableData(itemTitles: ItemTitle[], itemDatas: ItemData[][], sideHandle: { [key: string]: any }) {
  const { disabledState, setDisabledState, updateTableHandle, currentTab } = sideHandle;

  const columns: any[] = itemTitles.map((title, index) => ({
    title: title.name,
    dataIndex: title.code,
    key: title.code,
    width: index > 0 ? 120 : 320,
    editable: title.type == 2,
    valueType: title.type == 2 ? 'digit' : 'text',
    fixed: title.code == 'fillItemName' || title.code == 'dimensionName' ? 'left' : false,
    columnType: 1,
    render: (val: any, record: any) => {
      let editVal: number | string | null = null;
      const itemDicStr = record[`${title.code}_itemDic`] ? record[`${title.code}_itemDic`].description : '';
      const isDisabled = typeof disabledState[`${title.code}_${record.id}`] == 'boolean' ? disabledState[`${title.code}_${record.id}`] : true;

      let history = record[`${title.code}_history`] ? record[`${title.code}_history`] : [];
      let content = <AuthHisContent hisList={[...history]} />;

      let flag = title.currentPeriod;

      return flag ? (
        <>
          {flag ? (
            <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center' }}>
              <ProFormDigit
                disabled={isDisabled}
                noStyle
                width={80}
                placeholder={''}
                fieldProps={{
                  defaultValue: typeof val == 'object' ? val.props.text : val,
                  onChange(value) {
                    editVal = value;
                  },
                }}
              />
              <div
                style={{
                  marginLeft: 4,
                  width: 24,
                  height: 24,
                  background: '#FAFCFF',
                  borderRadius: 4,
                  border: '1px solid #DAE2F2',
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  cursor: 'pointer',
                }}
                onClick={() => {
                  !isDisabled && updateTableHandle(editVal, record, title.code);
                  setDisabledState((prevState: Record<string, boolean>) => ({
                    ...prevState,
                    [`${title.code}_${record.id}`]: !isDisabled, // 切换状态
                  }));
                }}
              >
                <IconFont style={{ fontSize: 16 }} type={isDisabled ? 'iconbianji' : 'iconqueren'} />
              </div>

              {history.length > 0 && (
                <Popover className="qualificationAuth-popover" overlayInnerStyle={{ borderRadius: 4 }} content={content} title={false}>
                  <IconFont type={'icon-qingliangtishi'} style={{ marginLeft: 10 }} />
                </Popover>
              )}
            </div>
          ) : (
            <span>{title.type == 2 ? (typeof val == 'number' ? val : '-') : val}</span>
          )}

          {itemDicStr && itemDicStr.length > 0 && (
            <Popover className="qualificationAuth-popover" overlayInnerStyle={{ borderRadius: 4 }} content={itemDicStr} title={false}>
              <IconFont type={'icon-qingliangtishi'} style={{ marginLeft: 10 }} />
            </Popover>
          )}
          {/* {
          title.type == 2 && (
            <Tooltip title="prompt text">
              <IconFont type={'iconfuzhi'} style={{ marginLeft: 10 }} />
            </Tooltip>
          )
        } */}
        </>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center' }}>
          {!isDisabled && (
            <ProFormDigit
              noStyle
              width={80}
              fieldProps={{
                defaultValue: val && val,
                onChange(value) {
                  editVal = value;
                },
              }}
            />
          )}
          {record[`${title.code}_pending`] && (
            <div
              style={{
                marginLeft: 4,
                width: 24,
                height: 24,
                background: '#FAFCFF',
                borderRadius: 4,
                border: '1px solid #DAE2F2',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                cursor: 'pointer',
              }}
              onClick={() => {
                if (!isDisabled) {
                  Modal.confirm({
                    title: '修改确认',
                    content: '确认后不可修改，是否保存？',
                    okText: '确定',
                    cancelText: '取消',
                    onOk(...args) {
                      updateTableHandle(editVal, record, title.code);
                    },
                    onCancel(...args) {},
                  });
                }
                setDisabledState((prevState: Record<string, boolean>) => ({
                  ...prevState,
                  [`${title.code}_${record.id}`]: !isDisabled, // 切换状态
                }));
              }}
            >
              <IconFont style={{ fontSize: 16 }} type={isDisabled ? 'iconbianji' : 'iconqueren'} />
            </div>
          )}
          {!record[`${title.code}_pending`] && <span>{typeof val == 'object' ? val.props.text : val}</span>}
          {itemDicStr && itemDicStr.length > 0 && (
            <Popover className="qualificationAuth-popover" overlayInnerStyle={{ borderRadius: 4 }} content={itemDicStr} title={false}>
              <IconFont type={'icon-qingliangtishi'} style={{ marginLeft: 10 }} />
            </Popover>
          )}
          {history.length > 0 && (
            <Popover className="qualificationAuth-popover" overlayInnerStyle={{ borderRadius: 4 }} content={content} title={false}>
              <IconFont type={'icon-qingliangtishi'} style={{ marginLeft: 10 }} />
            </Popover>
          )}
        </div>
      );
    },
  }));

  const dataSource = itemDatas.map((row, rowIndex) => {
    // 用 Record<string, any> 类型来解决动态属性问题
    const rowData: Record<string, any> = { id: `row_${rowIndex}` };

    row.forEach((item) => {
      // 处理每个对象的 `value`
      rowData[`${item.code}`] = item.value;

      // 遍历当前 item 的所有属性
      Object.keys(item).forEach((key) => {
        if (key !== 'code' && key !== 'value') {
          // 排除 code 和 value
          rowData[`${item.code}_${key}`] = item[key]; // 将其他属性添加到 rowData 中
        }
      });
    });

    return rowData;
  });

  return { columns, dataSource };
}
