import { Button, Upload, notification } from 'antd';
import React, { useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { connect } from 'dva';
import { POP_BATCH_DELIVERY } from '@/../config/permission.config';
import {
  queryToBatchSend,
  uploadFile,
  downTemplate,
  downUploadeOrder,
} from '../pendingDeliveryOrder/service';

const TableList = props => {
  const actionRef = useRef(null);
  const { permissions } = props;
  const canEditable = permissions[POP_BATCH_DELIVERY.EDITABLE];

  const columns = [
    {
      title: $t('batch.no'),
      dataIndex: 'batchNo',
      key: 'batchNo',
      align: 'center',
    },
    {
      title: $t('time'),
      key: 'dateTimeRange',
      dataIndex: 'createdAtRange',
      valueType: 'dateTimeRange',
      width: 300,
      hideInTable: true,
      initialValue: [],
      align: 'center',
    },
    {
      title: $t('operation.time'),
      dataIndex: 'createdAt',
      key: 'createdAt',
      hideInSearch: true,
      align: 'center',
    },
    // {
    //   title: '操作人',
    //   dataIndex: 'userName',
    //   key: 'userName',
    //   hideInSearch: true,
    //   width: 120,
    //   align: 'center',
    // },
    {
      title: $t('shipment.count'),
      dataIndex: 'totalNum',
      key: 'totalNum',
      hideInSearch: true,
      width: 120,
      align: 'center',
    },
    {
      title: $t('successful.shipments'),
      dataIndex: 'succNum',
      key: 'succNum',
      hideInSearch: true,
      width: 120,
      align: 'center',
    },
    {
      title: $t('status'),
      dataIndex: 'status',
      key: 'status',
      width: 120,
      align: 'center',
      filters: [],
      valueEnum: {
        0: { text: $t('all.failed') },
        1: { text: $t('all.successful') },
        2: { text: $t('partial.success') },
        99: { text: $t('all') },
      },
      initialValue: 1,
    },
    {
      title: $t('actions'),
      dataIndex: 'option',
      key: 'option',
      valueType: 'option',
      align: 'center',
      render: (_, record) => (
        <React.Fragment>
          <Button
            type="primary"
            style={{
              marginRight: '10px',
            }}
            onClick={async () => {
              downUploadeOrder({ batchNo: record.batchNo, status: 2 });
            }}
          >{$t('export.all')}</Button>
          {record.status === 1 ? (
            ''
          ) : (
            <Button
              type="primary"
              style={{
                marginRight: '10px',
              }}
              onClick={() => {
                downUploadeOrder({ batchNo: record.batchNo, status: 0 });
              }}
            >{$t('export.failed.data')}</Button>
          )}
        </React.Fragment>
      ),
    },
  ];
  const reload = () => {
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };
  const uploadProps = {
    name: 'file',
    async customRequest(info) {
      const result = await uploadFile(info.file);
      if (result.businessCode === '0000') {
        reload();
        notification.success({ message: $t('import.success') });
      }
    },
    accept: '.xlsx',
    showUploadList: false,
  };

  const searchRender = ({ searchText, resetText }, { form }) => {
    const exportBtn = [
      <Upload {...uploadProps}>
        <Button type="primary" style={{ marginRight: '10px' }} key="export">{$t('batch.shipping')}</Button>
      </Upload>,
      <Button
        type="primary"
        key="exportTemplate"
        onClick={downTemplate}
        style={{ marginRight: '10px' }}
      >{$t('template.download')}</Button>,
    ];
    if (!canEditable) {
      exportBtn.splice(0, 1);
    }
    return [
      <Button
        key="search"
        type="primary"
        style={{ marginRight: '10px' }}
        onClick={() => {
          // eslint-disable-next-line no-unused-expressions
          form?.submit();
        }}
      >
        {searchText}
      </Button>,
      <Button
        key="rest"
        style={{ marginRight: '10px' }}
        onClick={() => {
          // eslint-disable-next-line no-unused-expressions
          form?.resetFields();
          // eslint-disable-next-line no-unused-expressions
          form?.submit();
        }}
      >
        {resetText}
      </Button>,
      [...exportBtn],
    ];
  };
  return (
    <PageHeaderWrapper>
      <ProTable
        actionRef={actionRef}
        request={params => queryToBatchSend({ ...params })}
        columns={columns}
        rowKey={r => r.batchNo}
        search={{
          collapsed: false,
          optionRender: searchRender,
        }}
        bordered
        scroll={{ x: 1500 }}
      />
    </PageHeaderWrapper>
  );
};

export default connect(({ menu }) => ({
  permissions: menu.permissions,
}))(TableList);
