import React, { useState, useRef } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import serviceClient from '@/services/report/settings/index';
import { Button, message } from 'antd';
import type { ReconfirmProps } from '@/components/ReconfirmForm';
import ReconfirmForm, { EmptyReconfirmProps } from '@/components/ReconfirmForm';
import { FooterToolbar, PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { PlusOutlined } from '@ant-design/icons';
import EditForm from '@/pages/report/settings/ReportOperationSetting/components/EditForm';
import ImportForm from '@/components/excel/ImportForm';
import { downloadImportExcelExample, importExcel } from '@/services/mgr/api';
import ExportForm from '@/components/excel/ExportForm';
import moment from 'moment';

const Main: React.FC = () => {
  const intl = useIntl();

  const actionRef = useRef<ActionType>();
  const [editFormVisible, setEditFormVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState<any>();
  const [selectedRows, setSelectedRows] = useState<any[]>([]);
  const [reconfirmProps, setReconfirmProps] = useState<ReconfirmProps>(EmptyReconfirmProps);
  const [reconfirmFormVisible, setReconfirmFormVisible] = useState(false);
  const [criteria, setCriteria] = useState<any>();
  const [importFormVisible, setImportFormVisible] = useState(false);
  const [exportFormVisible, setExportFormVisible] = useState(false);

  const columns: ProColumns<Report.Settings.ReportOperationSettingDto>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '报表类型',
      dataIndex: ['type', 'name'],
      valueType: 'text',
    },
    {
      title: '生产管理员',
      dataIndex: 'fevor',
      valueType: 'text',
    },
    {
      title: '工序',
      dataIndex: 'operation',
      valueType: 'text',
    },
    {
      title: '工厂',
      dataIndex: 'werks',
      valueType: 'text',
    },
    {
      title: '月份',
      dataIndex: 'month',
      valueType: 'dateMonth',
      hideInSearch: true,
    },
    {
      title: '时间范围',
      dataIndex: 'monthRange',
      valueType: 'dateRange',
      hideInTable: true,
      initialValue: [
        moment().startOf('year').format('YYYY-MM-DD'),
        moment().endOf('year').format('YYYY-MM-DD'),
      ],
      colSize: 2,
    },
    {
      title: '日标准产量',
      dataIndex: 'dailyQuantity',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'component.option',
        defaultMessage: '操作',
      }),
      valueType: 'option',
      render: (_, record) => {
        return [
          <a
            key="edit"
            onClick={async () => {
              setCurrentRow(record);
              setEditFormVisible(true);
            }}
          >
            <FormattedMessage id="component.option.edit" defaultMessage="编辑" />
          </a>,
          <a
            key="remove"
            onClick={() => {
              setReconfirmProps({
                title: intl.formatMessage({
                  id: 'component.option.remove.reconfirm.title',
                  defaultMessage: '确定删除？',
                }),
                message: intl.formatMessage({
                  id: 'component.option.remove.reconfirm.message',
                  defaultMessage: '删除后，信息将无法找回。',
                }),
                comfirmHandler: async () => {
                  await serviceClient.reportOperationSettingService.remove(record);
                },
                onSubmitting: async () => {
                  const hide = message.loading(
                    intl.formatMessage({
                      id: 'component.option.remove.loading',
                      defaultMessage: '正在删除...',
                    }),
                  );
                  return {
                    hide,
                  };
                },
                onSuccess: async (params) => {
                  params.hide();
                  setReconfirmFormVisible(false);
                  actionRef.current?.reload();
                },
                onError: async (params) => {
                  params.hide();
                },
              });
              setReconfirmFormVisible(true);
            }}
          >
            <FormattedMessage id="component.option.remove" defaultMessage="删除" />
          </a>,
        ];
      },
    },
  ];

  return (
    <PageContainer
      header={{
        title: null,
      }}
    >
      <ProTable<
        Report.Settings.ReportOperationSettingDto,
        Report.Settings.ReportOperationSettingPageCriteria
      >
        headerTitle=""
        rowKey="id"
        actionRef={actionRef}
        search={{
          labelWidth: 120,
        }}
        manualRequest={true}
        toolBarRender={() => [
          <Button
            key="import"
            type="primary"
            onClick={() => {
              setImportFormVisible(true);
            }}
          >
            <PlusOutlined />
            <FormattedMessage id="component.option.import" defaultMessage="导入" />
          </Button>,
          <Button
            key="export"
            onClick={() => {
              setExportFormVisible(true);
            }}
          >
            <PlusOutlined />
            <FormattedMessage id="component.option.exprot" defaultMessage="导出" />
          </Button>,
        ]}
        request={async (params: Report.Settings.ReportOperationSettingPageCriteria) => {
          setCriteria(params);
          const sr = await serviceClient.reportOperationSettingService.pageQuery(params);
          return {
            data: sr.data,
            total: sr.total,
            success: true,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, rows) => {
            setSelectedRows(rows);
          },
          preserveSelectedRowKeys: false,
        }}
        tableAlertRender={false}
        pagination={{
          pageSize: 20,
        }}
        onLoad={(datasource) => {
          if (selectedRows?.length > 0) {
            setSelectedRows(selectedRows.filter((ele) => datasource.find((i) => i.id === ele.id)));
          }
        }}
      />
      {selectedRows?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="component.option.batch.label.1" defaultMessage="已选择" />
              {selectedRows?.length}
              <FormattedMessage id="component.option.batch.label.2" defaultMessage="项" />
            </div>
          }
        >
          <Button
            type="primary"
            danger
            onClick={() => {
              setReconfirmProps({
                title: intl.formatMessage({
                  id: 'component.option.remove.reconfirm.title',
                  defaultMessage: '确定删除？',
                }),
                message: intl.formatMessage({
                  id: 'component.option.remove.reconfirm.message',
                  defaultMessage: '删除后，信息将无法找回。',
                }),
                comfirmHandler: async () => {
                  for (let i = 0; i < selectedRows.length; i++) {
                    const hide = message.loading(`
                    ${intl.formatMessage({
                      id: 'component.option.batch.loading.1',
                      defaultMessage: '正在执行第',
                    })}
                        ${i + 1}
                        ${intl.formatMessage({
                          id: 'component.option.batch.loading.2',
                          defaultMessage: '项...',
                        })}
                    `);
                    try {
                      await serviceClient.reportOperationSettingService.remove({
                        id: selectedRows[i].id,
                      });
                      hide();
                    } catch {
                      hide();
                    }
                  }
                },
                onSubmitting: async () => {},
                onSuccess: async () => {
                  setReconfirmFormVisible(false);
                  actionRef.current?.reload();
                },
                onError: async () => {},
              });
              setReconfirmFormVisible(true);
            }}
          >
            <FormattedMessage id="component.option.batch.delete" defaultMessage="批量删除" />
          </Button>
        </FooterToolbar>
      )}
      <EditForm
        values={currentRow || {}}
        visible={editFormVisible}
        onVisibleChange={setEditFormVisible}
        onSubmitting={async () => {
          const hide = message.loading(
            intl.formatMessage({
              id: 'component.option.edit.loading',
              defaultMessage: '正在更新...',
            }),
          );
          return {
            hide,
          };
        }}
        onSuccess={async (params) => {
          params.hide();
          setEditFormVisible(false);
          actionRef.current?.reload();
        }}
        onError={async (params) => {
          params.hide();
        }}
      />
      <ReconfirmForm
        visible={reconfirmFormVisible}
        onVisibleChange={setReconfirmFormVisible}
        reconfirmProps={reconfirmProps}
      />
      <ImportForm
        importHandler={async (formdata) => {
          await importExcel('reportOperationSetting', formdata);
        }}
        visible={importFormVisible}
        onVisibleChange={setImportFormVisible}
        onSubmitting={async () => {
          const hide = message.loading(
            intl.formatMessage({
              id: 'component.option.import.loading',
              defaultMessage: '正在导入...',
            }),
          );
          return {
            hide,
          };
        }}
        onSuccess={async (params) => {
          params.hide();
          setImportFormVisible(false);
          actionRef.current?.reload();
        }}
        onError={async (params) => {
          params.hide();
        }}
        excelExample={{
          download: async () => {
            return await downloadImportExcelExample('reportOperationSetting');
          },
          fileNameProvider: async () => {
            return '报表工序设置';
          },
        }}
      />
      <ExportForm
        dataGetter={async (pageParams) => {
          const sr = await serviceClient.reportOperationSettingService.pageQuery({
            ...criteria,
            current: pageParams.current,
            pageSize: pageParams.pageSize,
          });
          return {
            data: sr.data,
            total: sr.total,
            success: true,
          }.data;
        }}
        columnsGetter={async () => {
          const result = columns
            .filter((item) => !!!item.hideInTable && !!!(item.valueType == 'option'))
            .map((item) => ({
              code:
                item.dataIndex instanceof Array
                  ? item.dataIndex.join('.')
                  : (item.dataIndex as string),
              name: item.title as string,
            }));
          return result;
        }}
        fileNameProvider={async () => {
          const data = moment().format('-YYYYMMDDHHmmss');
          return '报表工序设置' + data + '.xlsx';
        }}
        param={criteria || {}}
        visible={exportFormVisible}
        onVisibleChange={setExportFormVisible}
        onSubmitting={async () => {
          const hide = message.loading(
            intl.formatMessage({
              id: 'component.option.exprot.loading',
              defaultMessage: '正在导出...',
            }),
          );
          return {
            hide,
          };
        }}
        onSuccess={async (params) => {
          params.hide();
          setExportFormVisible(false);
        }}
        onError={async (params) => {
          params.hide();
        }}
      />
    </PageContainer>
  );
};

export default Main;
