import { logisticscontrollerGetlist } from '@/servers/api/logistics';
import { stockcontrollerGetallstockpoints } from '@/servers/api/stock';
import { formatShipmentState } from '@/utils/format';
import { printPDF } from '@/utils/util';
import { CopyOutlined } from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { App, Button } from 'antd';
import { useRef, useState } from 'react';

const ListPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const { message } = App.useApp();
  const [selectedRows, setSelectedRows] = useState([]);

  const columns: ProColumns<API.Service>[] = [
    {
      title: '服务商',
      dataIndex: 'tracking_provider',
      hideInSearch: true,
    },
    {
      title: '仓库',
      dataIndex: 'stockPointId',
      hideInTable: true,
      valueType: 'select',
      request: async () => {
        const { data = [] } = await stockcontrollerGetallstockpoints();
        return data.map((item) => ({
          label: item.name,
          value: item.id,
        }));
      },
    },
    {
      title: '快递单号',
      dataIndex: 'primary_tracking_number',
      render(_, record) {
        return (
          <>
            {record.primary_tracking_number}
            <CopyOutlined
              onClick={async () => {
                try {
                  await navigator.clipboard.writeText(record.tracking_url);
                  message.success('复制成功！');
                } catch (err) {
                  message.error('复制失败！');
                }
              }}
            />
          </>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'state',
      hideInSearch: true,
      render(_, record) {
        return formatShipmentState(record.state);
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      hideInSearch: true,
      valueType: 'dateTime',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      hideInSearch: true,
      render(_, record) {
        if (!record?.labels?.length) return null;
        return (
          <Button
            type="primary"
            onClick={() => {
              // printPDF([record.labels[record.labels.length - 1].url])
              window.open(
                record.labels[record.labels.length - 1].url,
                '_blank',
              );
            }}
          >
            打印
          </Button>
        );
      },
    },
  ];

  const handleBatchPrint = async () => {
    if (selectedRows.length === 0) {
      message.warning('请选择要打印的项');
      return;
    }
    await printPDF(
      selectedRows.map((row) => row.labels[row.labels.length - 1].url),
    );

    setSelectedRows([]);
  };
  return (
    <PageContainer ghost>
      <ProTable
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        request={async (values) => {
          console.log(values);
          const { data, success } = await logisticscontrollerGetlist({
            params: values,
          });
          if (success) {
            return {
              total: data?.total || 0,
              data: data?.items || [],
            };
          }
          return {
            data: [],
          };
        }}
        // rowSelection={{
        //   selectedRowKeys: selectedRows.map((row) => row.id),
        //   onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        // }}
        columns={columns}
        tableAlertOptionRender={() => {
          return (
            <Button onClick={handleBatchPrint} type="primary">
              批量打印
            </Button>
          );
        }}
      />
    </PageContainer>
  );
};
export default ListPage;
