import React, { useRef } from 'react';
import { useIntl } from 'umi';
import type { ProFormInstance } from '@ant-design/pro-form';
import { ModalForm, ProFormRadio } from '@ant-design/pro-form';
import * as XLSX from 'xlsx';

export type ExportFormProps = {
  dataGetter: () => Promise<any>;
  fileNameProvider?: () => Promise<string>;
  visible: boolean;
  onVisibleChange: (visible: boolean) => void;
  onSubmitting: () => Promise<any>;
  onSuccess: (params: any) => Promise<void>;
  onError: (params: any, error: unknown) => Promise<void>;
};

const ExportForm: React.FC<ExportFormProps> = (props) => {
  const intl = useIntl();
  const formRef = useRef<ProFormInstance>();

  return (
    <ModalForm
      formRef={formRef}
      title={intl.formatMessage({
        id: 'component.option.exprot.excel',
        defaultMessage: '导出到Excel',
      })}
      width="600px"
      visible={props.visible}
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          formRef?.current?.setFieldsValue({
            type: 'all',
          });
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async () => {
        const params = await props.onSubmitting();
        try {
          const data: Report.RptProductionProgressDto = await props.dataGetter();
          if (data == null || data.groupByDays == null || data.groupByDays.length == 0) {
            return;
          }

          let fileName;
          if (props.fileNameProvider) {
            fileName = await props.fileNameProvider();
          } else {
            fileName = 'Data.xlsx';
          }

          const excelData: [any][any] = [];

          const row1: [string] = ['SAP订单号'];
          row1.push('物料编码');
          row1.push('物料描述');
          row1.push('订单数量');
          row1.push('产品施工号');
          row1.push('日期');
          data.operations.forEach((t) => {
            row1.push(t.operation);
            row1.push('');
          });
          excelData.push(row1);

          const row2: [string] = [''];
          row2.push('');
          row2.push('');
          row2.push('');
          row2.push('');
          row2.push('');
          data.operations.forEach(() => {
            row2.push('计划');
            row2.push('实际');
          });
          excelData.push(row2);

          for (const group of data.groupByDays) {
            const dataRow: [string] = [group.aufnr];
            dataRow.push(group.partCode);
            dataRow.push(group.partName);
            dataRow.push(group.sapOrderQuantity.toString());
            dataRow.push(group.sgNo);
            dataRow.push(group.byDay);
            for (const operation of data.operations) {
              const item = group.details.find((t) => t.operation == operation.operation);
              if (item != null) {
                dataRow.push(item.plannedQuantity.toString());
                dataRow.push(item.finishedQuantity.toString());
              } else {
                dataRow.push('');
                dataRow.push('');
              }
            }
            excelData.push(dataRow);
          }

          const workBook = XLSX.utils.book_new();
          const workSheet = XLSX.utils.aoa_to_sheet(excelData);
          XLSX.utils.book_append_sheet(workBook, workSheet);
          XLSX.writeFile(workBook, fileName, { bookType: 'xlsx' });
          await props.onSuccess(params);
        } catch (error) {
          await props.onError(params, error);
        }
      }}
    >
      <ProFormRadio.Group
        name="type"
        options={[
          {
            label: intl.formatMessage({
              id: 'component.option.exprot.type.all',
              defaultMessage: '所有页',
            }),
            value: 'all',
          },
        ]}
      />
    </ModalForm>
  );
};

export default ExportForm;
