import React, { useState, useRef } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import serviceClient from '@/services/kanban/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, FileExcelOutlined } from '@ant-design/icons';
import CreateForm from '@/pages/kanban/settings/ProcessDefectRatioDatum/components/CreateForm';
import EditForm from '@/pages/kanban/settings/ProcessDefectRatioDatum/components/EditForm';
import ImportForm from '@/components/excel/ImportForm';
import moment from 'moment';
import { downloadImportExcelExample, importExcel } from '@/services/mgr/api';
import ExportForm from '@/components/excel/ExportForm';

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

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

  const columns: ProColumns<KANBAN.Settings.ProcessDefectRatioDatumDto>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '工序编号',
      dataIndex: 'stepCode',
      valueType: 'text',
      hideInTable: false,
      hideInSearch: false,
    },
    {
      title: '工序名称',
      dataIndex: 'operationName',
      valueType: 'text',
      hideInTable: false,
      hideInSearch: false,
    },
    {
      title: '工厂',
      dataIndex: 'werks',
      valueType: 'text',
      hideInTable: false,
      hideInSearch: false,
    },
    {
      title: '生产管理员',
      dataIndex: 'fevor',
      valueType: 'text',
      hideInTable: false,
      hideInSearch: false,
    },
    {
      title: '基准值',
      dataIndex: 'datumValue',
      valueType: 'digit',
      hideInTable: false,
      hideInSearch: true,
    },
    {
      title: '月份',
      dataIndex: 'datumDate',
      valueType: 'dateMonth',
      hideInTable: false,
      hideInSearch: false,
    },
    {
      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.processDefectRatioDatumService.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<
        KANBAN.Settings.ProcessDefectRatioDatumDto,
        KANBAN.Settings.ProcessDefectRatioDatumPageCriteria
      >
        headerTitle=""
        rowKey="id"
        actionRef={actionRef}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="create"
            onClick={() => {
              setCreateFormVisible(true);
            }}
          >
            <PlusOutlined />
            <FormattedMessage id="component.option.add" defaultMessage="新增" />
          </Button>,
          <Button
            key="import"
            onClick={() => {
              setImportFormVisible(true);
            }}
          >
            <FileExcelOutlined />
            <FormattedMessage id="component.option.import" defaultMessage="导入" />
          </Button>,
          <Button
            key="export"
            onClick={() => {
              setExportFormVisible(true);
            }}
          >
            <FileExcelOutlined />
            <FormattedMessage id="component.option.exprot" defaultMessage="导出" />
          </Button>,
        ]}
        request={async (params: KANBAN.Settings.ProcessDefectRatioDatumPageCriteria) => {
          setCriteria(params);
          const sr = await serviceClient.processDefectRatioDatumService.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)));
          }
        }}
        manualRequest={true}
      />
      {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.processDefectRatioDatumService.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>
      )}
      <CreateForm
        visible={createFormVisible}
        onVisibleChange={setCreateFormVisible}
        onSubmitting={async () => {
          const hide = message.loading(
            intl.formatMessage({
              id: 'component.option.add.loading',
              defaultMessage: '正在新增...',
            }),
          );
          return {
            hide,
          };
        }}
        onSuccess={async (params) => {
          params.hide();
          setCreateFormVisible(false);
          actionRef.current?.reload();
        }}
        onError={async (params) => {
          params.hide();
        }}
      />
      <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();
        }}
      />
      <ImportForm
        importHandler={async (formdata) => {
          await importExcel('processDefectRatioDatum', 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('processDefectRatioDatum');
          },
          fileNameProvider: async () => {
            return '工序一次未通过率基准';
          },
        }}
      />
      <ExportForm
        dataGetter={async (pageParams) => {
          return (
            await serviceClient.processDefectRatioDatumService.pageQuery({
              ...criteria,
              current: pageParams.current,
              pageSize: pageParams.pageSize,
            })
          ).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();
        }}
      />
      <ReconfirmForm
        visible={reconfirmFormVisible}
        onVisibleChange={setReconfirmFormVisible}
        reconfirmProps={reconfirmProps}
      />
    </PageContainer>
  );
};

export default Main;
