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.RptProductionByDayDto = await props.dataGetter();
          if (data == null || data.detailGroups == null || data.detailGroups.length == 0) {
            return;
          }

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

          const excelData: [any][any] = [];
          const row1: [string] = ['日期'];
          data.headers.forEach((t) => {
            row1.push(t.operation);
            row1.push('');
          });
          excelData.push(row1);
          const row2: [string] = [''];
          data.headers.forEach(() => {
            row2.push('计划数量');
            row2.push('完成数量');
          });
          excelData.push(row2);

          for (const group of data.detailGroups) {
            const dataRow: [string] = [group.byDay];
            for (const header of data.headers) {
              const item = group.details.find(
                (t) => t.operation == header.operation && t.fevor == header.fevor,
              );
              if (item != null) {
                dataRow.push(item.dailyQuantity.toString());
                dataRow.push(item.quantity.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;
