/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-07-11 14:47:55
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/pubDicTypeMana/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

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

import { ActionType } from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormDatePicker,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormRadio,
  ProFormDependency,
} from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { message, Popconfirm, DatePicker, Modal } from 'antd';
import { useEffect, useRef, useState } from 'react';

import {
  afterImport,
  getData,
  getSpecialImportTable,
  tableDataImport,
  importMultipleSheets,
} from './service';
import FormItem from 'antd/es/form/FormItem';

import './style.less';
import '../../utils/zhongtaiA';
import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import { getComputeDate } from '@/pages/Home/service';
import KCIMUpload from '@/components/KCIMUpload';
import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import { useModel } from '@umijs/max';

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

const currentDate = `${new Date().getFullYear()}-${(new Date().getMonth() + 1)
  .toString()
  .padStart(2, '0')}`;

export default function DicClassfication() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >();
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');
  const { initialState, setInitialState } = useModel('@@initialState');
  const [currentComputeDate, set_currentComputeDate] = useState<
    string | undefined
  >(initialState ? initialState.computeDate : undefined);
  const tableRef = useRef<ActionType>();

  const columns: ProColumns[] = [
    {
      title: '所属年月',
      dataIndex: 'computeDate',
      ellipsis: true,
    },
    {
      title: '数据库表名称',
      dataIndex: 'tableNameDisplay',
      ellipsis: true,
    },
    {
      title: '文件名称',
      dataIndex: 'fileName',
      ellipsis: true,
      renderText(text, record, index, action) {
        return (
          <a href={record.url} target="_blank">
            {record.fileName}
          </a>
        );
      },
    },
    {
      title: '导入时间',
      dataIndex: 'createTime',
      ellipsis: true,
    },
    {
      title: '导入人员',
      dataIndex: 'createUserName',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'option',
      width: 120,
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <Popconfirm
            title={`是否${record.importStatus == 1 ? '复原导入' : '撤销导入'}?`}
            key="del"
            onConfirm={() => afterImportHandle(record)}
          >
            <a>{record.importStatus == 1 ? '复原导入' : '撤销导入'}</a>
          </Popconfirm>,
        ];
      },
    },
  ];

  const afterImportHandle = async (record: any) => {
    const { importStatus } = record;
    const resp = await afterImport(
      record.id,
      importStatus ? 'RECOVERY' : 'CANCEL',
    );
    if (resp) {
      message.success('操作成功！');
      tableRef.current?.reload();
    }
  };

  // 显示导入错误详情的Modal
  const showImportErrorModal = (failedImports: any[], successCount: number) => {
    const errorContent = failedImports.map((item, index) => (
      <div
        key={index}
        style={{
          marginBottom: 12,
          padding: 12,
          backgroundColor: '#fff2f0',
          border: '1px solid #ffccc7',
          borderRadius: 6,
        }}
      >
        <div style={{ fontWeight: 'bold', color: '#cf1322', marginBottom: 4 }}>
          Sheet: {item.sheetName}
        </div>
        <div style={{ color: '#595959', fontSize: 13 }}>
          错误信息: {item.errorMessage}
        </div>
      </div>
    ));

    Modal.error({
      title: '导入结果详情',
      width: 600,
      content: (
        <div>
          {successCount > 0 && (
            <div
              style={{
                marginBottom: 16,
                padding: 12,
                backgroundColor: '#f6ffed',
                border: '1px solid #b7eb8f',
                borderRadius: 6,
              }}
            >
              <span style={{ color: '#52c41a', fontWeight: 'bold' }}>
                成功导入: {successCount} 个Sheet
              </span>
            </div>
          )}
          <div
            style={{ marginBottom: 8, fontWeight: 'bold', color: '#cf1322' }}
          >
            失败导入: {failedImports.length} 个Sheet
          </div>
          <div style={{ maxHeight: 400, overflowY: 'auto' }}>
            {errorContent}
          </div>
        </div>
      ),
      okText: '知道了',
    });
  };

  const getTableData = async (params: any) => {
    const { computeDate } = params;
    const resp = await getData({
      ...params,
      computeDate: computeDate ? computeDate : currentComputeDate,
    });
    if (resp) {
      return {
        data: resp.list,
        success: true,
        total: resp.totalCount,
        pageSize: resp.pageSize,
        totalPage: resp.totalPage,
      };
    }
    return [];
  };

  const importData = () => {
    function downloadTemplate(): void {}

    return (
      <ModalForm
        className="SpecialDataImport-Modal"
        width={368}
        title={`导入数据`}
        trigger={
          <span key="3" className="importBtn">
            导入
          </span>
        }
        submitter={{
          render: (props, defaultDoms) => {
            const needBtn = defaultDoms.filter((b) => {
              return b.key != 'rest';
            });
            return [...needBtn];
          },
        }}
        onFinish={async (values) => {
          // console.log({values});
          const {
            importFile: { fileList },
            importMode,
          } = values;

          let formData = new FormData();
          formData.append('file', fileList[0].originFileObj);
          formData.append('computeDate', values.computeDate);

          let resp;
          if (importMode === 'single') {
            // 单页导入
            formData.append('tableName', values.tableName);
            resp = await tableDataImport(formData);
            if (resp) {
              message.success('导入成功！');
              tableRef.current?.reload();
              return true;
            } else {
              message.error('导入失败，请检查文件格式和内容');
            }
          } else {
            // 多页导入
            resp = await importMultipleSheets(formData);
            if (resp && Array.isArray(resp)) {
              // 检查是否有失败的导入
              const failedImports = resp.filter(
                (item) => item.success === false,
              );
              const successImports = resp.filter(
                (item) => item.success === true,
              );

              if (failedImports.length > 0) {
                // 有失败的导入，显示详细错误信息
                showImportErrorModal(failedImports, successImports.length);
              } else {
                // 全部成功
                message.success('所有Sheet导入成功！');
              }

              tableRef.current?.reload();
              return true;
            }
          }

          return false;
        }}
      >
        <div className="tip">
          本操作为追加导入，会保留已有的数据并将文件的所有记录追加到数据表
        </div>
        <ProFormDatePicker.Month
          label="所属年月"
          name="computeDate"
          width={326}
          rules={[{ required: true, message: '所属年月不能为空!' }]}
          fieldProps={{ autoComplete: 'off' }}
        />

        <ProFormRadio.Group
          name="importMode"
          label="导入方式"
          tooltip="单页导入：一个Excel文件中对应一个目标数据表，需要手动选择数据库表名称；多页导入：一个Excel文件的个Sheet页对应一个目标数据表，Sheet页名称需要和数据库表名完全一致"
          initialValue="single"
          options={[
            { label: '单页导入', value: 'single' },
            { label: '多页导入', value: 'multiple' },
          ]}
        />

        <ProFormDependency name={['importMode']}>
          {({ importMode }) => {
            if (importMode === 'single') {
              return (
                <ProFormSelect
                  label="数据库表名称"
                  name="tableName"
                  width={326}
                  request={async () => {
                    const resp = await getSpecialImportTable();
                    if (resp) {
                      return resp.map((a: any) => ({
                        label: a.name,
                        value: a.code,
                      }));
                    }
                    return [];
                  }}
                  rules={[{ required: true, message: '数据库表名称不能为空!' }]}
                />
              );
            }
            return null;
          }}
        </ProFormDependency>

        <FormItem name={'importFile'}>
          {currentComputeDate && (
            <KCIMUpload
              downloadTemplateFile={() => downloadTemplate()}
              ifShowTip={false}
              ifShowTemplateDownload={false}
            />
          )}
        </FormItem>
      </ModalForm>
    );
  };

  return (
    <KCIMPagecontainer className="SpecialDataImport" title={false}>
      <div className="toolBar">
        <div className="filter">
          <div className="filterItem">
            {
              <div className="search">
                <span>所属年月：</span>
                <DatePicker
                  onChange={(data, dateString) => {
                    set_tableDataFilterParams({
                      ...tableDataFilterParams,
                      computeDate: dateString,
                    });
                    setInitialState((s: any) => ({
                      ...s,
                      currentComputeDate: dateString,
                    }));
                  }}
                  picker="month"
                  locale={locale}
                  autoComplete="off"
                  defaultValue={moment(currentComputeDate, 'YYYY-MM')}
                  format="YYYY-MM"
                  placeholder="选择年月"
                />
              </div>
            }
          </div>
          <div className="filterItem" style={{ marginLeft: 16 }}>
            <span className="label">表名称：</span>
            <ProFormSelect
              noStyle
              allowClear
              placeholder="请选择"
              style={{ width: 160, marginRight: 16 }}
              request={async () => {
                const resp = await getSpecialImportTable();
                if (resp) {
                  return resp.map((a: any) => ({
                    label: a.name,
                    value: a.code,
                  }));
                }
                return [];
              }}
              fieldProps={{
                onChange(value, option) {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    tableName: value,
                  });
                },
              }}
            />
          </div>
        </div>
        <div className="btnGroup">{importData()}</div>
      </div>
      <div style={{ marginTop: 16 }}>
        {currentComputeDate && (
          <KCIMTable
            scroll={{ y: `calc(100vh - 230px)` }}
            columns={columns as ProColumns[]}
            actionRef={tableRef}
            rowKey="id"
            params={tableDataFilterParams}
            request={(params, sort, filter) => getTableData(params)}
          />
        )}
      </div>
    </KCIMPagecontainer>
  );
}
