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 } from '@ant-design/icons';
import CreateForm from '@/pages/kanban/settings/ProductProgressSetting/components/CreateForm';
import EditForm from '@/pages/kanban/settings/ProductProgressSetting/components/EditForm';

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

  const actionRef = useRef<ActionType>();
  const [createFormVisible, setCreateFormVisible] = useState(false);
  const [editFormVisible, setEditFormVisible] = useState(false);
  const [currentRow, setCurrentRow] =
    useState<Report.Settings.ProductionProgressKanbanSettingDto>();
  const [selectedRows, setSelectedRows] = useState<any[]>([]);
  const [reconfirmProps, setReconfirmProps] = useState<ReconfirmProps>(EmptyReconfirmProps);
  const [reconfirmFormVisible, setReconfirmFormVisible] = useState(false);

  const columns: ProColumns<Report.Settings.ProductionProgressKanbanSettingDto>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '车间名称',
      dataIndex: 'subTitle1',
      valueType: 'text',
    },
    {
      title: '产品名称',
      dataIndex: 'subTitle2',
      valueType: 'text',
    },
    {
      title: '生产管理员',
      dataIndex: 'fevor',
      valueType: 'text',
    },
    {
      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.productProgressSettingService.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.ProductionProgressKanbanSettingDto,
        Report.Settings.ProductionProgressKanbanSettingCriteria
      >
        headerTitle=""
        rowKey="id"
        actionRef={actionRef}
        search={{
          labelWidth: 120,
        }}
        manualRequest={true}
        toolBarRender={() => [
          <Button
            key="new"
            onClick={() => {
              setCreateFormVisible(true);
            }}
          >
            <PlusOutlined />
            <FormattedMessage id="component.option.new" defaultMessage="新增" />
          </Button>,
        ]}
        request={async (params: KANBAN.Settings.ProductProgressKanbanSettingCriteria) => {
          const sr =
            await serviceClient.productProgressSettingService.pageProductProgressKanbanSetting(
              params,
            );
          return {
            data: sr.data.data,
            total: sr.data.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.productProgressSettingService.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();
        }}
      />
      <ReconfirmForm
        visible={reconfirmFormVisible}
        onVisibleChange={setReconfirmFormVisible}
        reconfirmProps={reconfirmProps}
      />
    </PageContainer>
  );
};

export default Main;
