/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-09-25 14:59:23
 * @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 { ModalForm } from '@ant-design/pro-form';
import FormItem from 'antd/es/form/FormItem';
import { Input, message, Modal, Dropdown } from 'antd';
import { useEffect, useRef, useState } from 'react';
import type { MenuProps } from 'antd';

import {
  getData,
  downloadTemplateReq,
  importDataPost,
  getIncomeCostDataImportErrList,
  cancelIncomeCostDataImport,
  rebackIncomeCostDataImport,
} from './service';

import './style.less';
import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import KCIMUpload from '@/components/KCIMUpload';
import { TableDataResponse } from 'typings';
import {
  ActionType,
  ProColumns,
  ProFormSelect,
} from '@ant-design/pro-components';
import { importEmpCostDataPost } from '../empCostDataImport/service';
import { importPatientInfoDataPost } from '../patientInfoImport/service';
import { importPatientChargeItemDataPost } from '../patientChargeItemsImport/service';

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

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

let currentImportkey: any = undefined;

const items: MenuProps['items'] = [
  {
    key: '1',
    label: (
      <a
        target="_blank"
        rel="noopener noreferrer"
        onClick={() => {
          downloadTemplateReq(
            '/gateway/costAccount/excel/getShareParamTemplate',
          );
          currentImportkey = 1;
        }}
      >
        成本分摊参数模板
      </a>
    ),
  },
  {
    key: '2',
    label: (
      <a
        target="_blank"
        rel="noopener noreferrer"
        onClick={() => {
          downloadTemplateReq(
            '/gateway/costAccount/excel/getImportIncomeProductAccountTemplate',
          );
          currentImportkey = 2;
        }}
      >
        收入数据模板
      </a>
    ),
  },
  {
    key: '3',
    label: (
      <a
        target="_blank"
        rel="noopener noreferrer"
        onClick={() => {
          downloadTemplateReq(
            '/gateway/costAccount/excel/getImportCostProductAccountTemplate',
          );
          currentImportkey = 3;
        }}
      >
        成本数据模板
      </a>
    ),
  },
  {
    key: '4',
    label: (
      <a
        target="_blank"
        rel="noopener noreferrer"
        onClick={() => {
          downloadTemplateReq(
            '/gateway/costAccount/computeImport/exportEmpCostList',
          );
          currentImportkey = 4;
        }}
      >
        人事成本数据
      </a>
    ),
  },
  {
    key: '5',
    label: (
      <a
        target="_blank"
        rel="noopener noreferrer"
        onClick={() => {
          downloadTemplateReq(
            '/gateway/costAccount/computeImport/exportPatientInfo',
          );
          currentImportkey = 5;
        }}
      >
        患者信息
      </a>
    ),
  },
  {
    key: '6',
    label: (
      <a
        target="_blank"
        rel="noopener noreferrer"
        onClick={() => {
          downloadTemplateReq(
            '/gateway/costAccount/computeImport/exportPatientItem',
          );
          currentImportkey = 6;
        }}
      >
        患者收费项目
      </a>
    ),
  },
];

let _computeDate: string | undefined = undefined;

export default function IncomeCostDataImport({
  date,
  btnPerm,
}: {
  date: string;
  btnPerm: string;
}) {
  const [computeDate, set_computeDate] = useState(date);
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<any>({
    computeDate: currentData,
  });
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState('');
  const tableRef = useRef<ActionType>();
  const [currentEditRow, set_currentEditRow] = useState<undefined | any>(
    undefined,
  );

  const [ifShowGetBtn, set_ifShowGetBtn] = useState(false);
  const [ifShowCancelBtn, set_ifShowCancelBtn] = useState(false);

  const columns: ProColumns[] = [
    {
      title: '文件编号',
      dataIndex: 'id',
      width: '15%',
    },
    {
      title: '文件名称',
      width: '40%',
      dataIndex: 'fileName',
      renderText(text, record, index, action) {
        const { fileUrl } = record;
        const userData = localStorage.getItem('userData');
        const { token } = JSON.parse(userData as string);
        return (
          <a key="download" href={`${fileUrl}?token=${token}`} target="_blank">
            {text}
          </a>
        );
      },
    },
    {
      title: '导入类型',
      width: '15%',
      dataIndex: 'fileType',
    },
    {
      title: '导入人员',
      width: '15%',
      dataIndex: 'userName',
    },
    {
      title: '导入时间',
      width: '15%',
      dataIndex: 'dateTime',
    },
    {
      title: '操作',
      width: '10%',
      dataIndex: 'option',
      renderText(text, record) {
        const { errStatus, rollbackStatus } = record;

        return [
          <span
            key="act"
            style={{ color: '#3377FF', cursor: 'pointer' }}
            onClick={() => {
              optionBtnGrouphandle(errStatus, record);
            }}
          >
            {errStatus == 1
              ? '错误详情'
              : rollbackStatus == 1
              ? '复原导入'
              : '撤销导入'}
          </span>,
        ];
      },
    },
  ];

  const getTableData = async (
    params: any,
  ): Promise<TableDataResponse | any[]> => {
    const resp = await getData({ ...params, ...tableDataFilterParams });
    if (resp) {
      const { list, totalCount, pageSize, current, totalPage } = resp;
      if (totalCount == 0 && current != 1) {
        return getTableData({ ...params, current: current - 1 });
      } else {
        return {
          data: list,
          success: true,
          total: totalCount,
          pageSize: pageSize,
          totalPage: totalPage,
        };
      }
    }
    return [];
  };

  const tableDataSearchHandle = (paramName: string) => {
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      [`${paramName}`]: tableDataSearchKeywords,
    });
  };

  const getErrorInfo = async (id: number) => {
    const resp = await getIncomeCostDataImportErrList({ id });
    if (resp) {
      return {
        data: resp,
        success: true,
      };
    } else {
      return [];
    }
  };

  const optionBtnGrouphandle = async (errStatus: number, record: any) => {
    set_currentEditRow(record);
    const { id, rollbackStatus } = record;
    if (errStatus != 1) {
      let resp = undefined;
      if (rollbackStatus != 1) {
        //撤销
        resp = await cancelIncomeCostDataImport(id, date);
      }
      if (rollbackStatus == 1) {
        //复原
        resp = await rebackIncomeCostDataImport(id, date);
      }

      if (resp) {
        message.success(rollbackStatus == 1 ? '还原成功！' : '撤销成功！');
        tableRef.current?.reload();
      }
    } else {
      Modal.info({
        title: '错误详情',
        icon: '',
        content: (
          <>
            <KCIMTable
              rowKey="id"
              columns={[
                {
                  title: '行数',
                  width: 50,
                  dataIndex: 'total',
                },
                {
                  title: '错误信息',
                  dataIndex: 'errMessage',
                  ellipsis: true,
                },
              ]}
              request={() => getErrorInfo(id)}
            />
          </>
        ),
      });
    }
  };

  const importData = () => {
    return (
      <ModalForm
        width={360}
        title={`导入数据`}
        trigger={
          <a className="import" key="3">
            导入
          </a>
        }
        initialValues={{ dateTime: date }}
        submitter={{
          render: (props, defaultDoms) => {
            const needBtn = defaultDoms.filter((b) => {
              return b.key != 'rest';
            });
            return [
              // <Button
              //     key="ok"
              //     onClick={auditType == '0' ? () => downloadTemplate(index) : () => { }}
              // >
              //     下载模板
              // </Button>,
              ...needBtn,
            ];
          },
        }}
        onFinish={async (values) => {
          try {
            const {
              importFile: { fileList },
              fileType,
            } = values;

            if (fileType <= 3) {
              let formData = new FormData();
              formData.append('file', fileList[0].originFileObj);
              formData.append('dateTime', date);
              formData.append('fileType', fileType);

              const resp = await importDataPost(formData);

              if (resp) {
                tableRef.current?.reload();
                return true;
              }
            } else {
              if (fileType == 4) {
                //人事成本
                let formData = new FormData();
                formData.append('file', fileList[0].originFileObj);
                formData.append('computeDate', date);
                const resp = await importEmpCostDataPost(formData);
                if (resp) {
                  tableRef.current?.reload();
                  return true;
                }
              }
              if (fileType == 5) {
                //患者信息
                let formData = new FormData();
                formData.append('file', fileList[0].originFileObj);
                formData.append('computeDate', date);
                const resp = await importPatientInfoDataPost(formData);
                if (resp) {
                  tableRef.current?.reload();
                  return true;
                }
              }
              if (fileType == 6) {
                //患者收费项目
                let formData = new FormData();
                formData.append('file', fileList[0].originFileObj);
                formData.append('computeDate', date);
                const resp = await importPatientChargeItemDataPost(formData);
                if (resp) {
                  tableRef.current?.reload();
                  return true;
                }
              }
            }
          } catch (err) {
            console.log({ err });
          }
        }}
      >
        {/* <ProFormDatePicker label='数据所属年月：' name='dateTime'
          width={328}
          fieldProps={{
            picker: 'month',
            locale: locale,
            format: 'YYYY-MM'
          }}
          disabled
          placeholder="选择年月"
          rules={[
            {
              required: true,
              message: '请选择年月',
            },
          ]}
        /> */}
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '请选择数据类型',
            },
          ]}
          options={[
            {
              value: 1,
              label: '成本分摊参数值',
            },
            {
              value: 2,
              label: '收入数据',
            },
            {
              value: 3,
              label: '成本数据',
            },
            {
              value: 4,
              label: '人事成本数据',
            },
            {
              value: 5,
              label: '患者信息',
            },
            {
              value: 6,
              label: '患者收费项目',
            },
          ]}
          name="fileType"
          label="选择数据类型"
        />
        <FormItem name={'importFile'}>
          <KCIMUpload ifShowTemplateDownload={false} ifShowTip={false} />
        </FormItem>
      </ModalForm>
    );
  };

  useEffect(() => {
    if (date) {
      set_tableDataFilterParams({
        ...tableDataFilterParams,
        computeDate: date,
      });
      _computeDate = date;
    }
  }, [date]);

  useEffect(() => {
    if (btnPerm) {
      const [a, b] = btnPerm.split('|');
      set_ifShowCancelBtn(b == '1');
      set_ifShowGetBtn(a == '1');
    }
  }, [btnPerm]);

  useEffect(() => {}, []);

  return (
    <div className="IncomeCostDataImport">
      <div className="toolBar">
        <div className="filter">
          <div className="filterItem" style={{ width: 205 }}>
            <span className="label" style={{ whiteSpace: 'nowrap' }}>
              {' '}
              检索：
            </span>
            <Input
              placeholder={'文件名称'}
              allowClear
              autoComplete="off"
              suffix={
                <IconFont
                  type="iconsousuo"
                  style={{ color: '#99A6BF' }}
                  onClick={() => tableDataSearchHandle('fileName')}
                />
              }
              onChange={(e) => {
                set_tableDataSearchKeywords(e.target.value);
                if (e.target.value.length == 0) {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    fileName: '',
                  });
                }
              }}
              onPressEnter={(e) => {
                set_tableDataFilterParams({
                  ...tableDataFilterParams,
                  fileName: (e.target as HTMLInputElement).value,
                });
              }}
            />
          </div>
        </div>
        <div className="btnGroup">
          <>
            <Dropdown menu={{ items }} placement="bottomLeft">
              <span className="normal">模板下载</span>
            </Dropdown>
            {importData()}
          </>
        </div>
      </div>
      <div style={{ marginTop: 16 }}>
        <KCIMTable
          columns={columns}
          actionRef={tableRef}
          rowKey="id"
          scroll={{ y: `calc(100vh - 259px)` }}
          params={tableDataFilterParams}
          request={(params) => getTableData(params)}
        />
      </div>
    </div>
  );
}
