import {
  logisticscontrollerDeleteshipment,
  logisticscontrollerGetlist,
  logisticscontrollerGetshipmentlabel,
  logisticscontrollerUpdateshipmentstate,
} from '@/servers/api/logistics';
import { stockcontrollerGetallstockpoints } from '@/servers/api/stock';
import { formatUniuniShipmentState } from '@/utils/format';
import { printPDF } from '@/utils/util';
import {
  CopyOutlined,
  DeleteFilled,
  FilePdfOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { useParams } from '@umijs/max';
import { App, Button, Divider, Popconfirm, Space } from 'antd';
import React, { useRef, useState } from 'react';
import { ToastContainer } from 'react-toastify';

const LogisticsPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const { message } = App.useApp();
  const [selectedRows, setSelectedRows] = useState<API.Service[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const { siteId } = useParams<{ siteId: string }>();

  React.useEffect(() => {
    actionRef.current?.reload();
  }, [siteId]);

  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,
        }));
      },
    },
    // Site column removed
    {
      title: '订单号',
      dataIndex: 'externalOrderId',
    },
    {
      title: '快递单号',
      dataIndex: 'return_tracking_number',
      render(_, record) {
        return (
          <>
            {record.return_tracking_number}
            <CopyOutlined
              onClick={async () => {
                try {
                  await navigator.clipboard.writeText(
                    record.return_tracking_number,
                  );
                  message.success('复制成功!');
                } catch (err) {
                  message.error('复制失败!');
                }
              }}
            />
          </>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'state',
      hideInSearch: true,
      render(_, record) {
        return formatUniuniShipmentState(record.state);
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      hideInSearch: true,
      valueType: 'dateTime',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      hideInSearch: true,
      render(_, record) {
        return (
          <>
            <Button
              type="primary"
              title="打印标签"
              icon={<FilePdfOutlined />}
              disabled={isLoading}
              onClick={async () => {
                setIsLoading(true);
                const { data } = await logisticscontrollerGetshipmentlabel({
                  shipmentId: record.id,
                });
                const content = data.content;
                printPDF([content]);
                setIsLoading(false);
              }}
            />
            <Divider type="vertical" />
            <Button
              type="primary"
              title="刷新状态"
              icon={<ReloadOutlined />}
              disabled={isLoading}
              onClick={async () => {
                setIsLoading(true);
                const res = await logisticscontrollerUpdateshipmentstate({
                  shipmentId: record.id,
                });
                console.log('res', res);

                setIsLoading(false);
              }}
            />
            <Divider type="vertical" />
            <Popconfirm
              disabled={isLoading}
              title="删除"
              description="确认删除?"
              onConfirm={async () => {
                try {
                  setIsLoading(true);
                  const { success, message: errMsg } =
                    await logisticscontrollerDeleteshipment({ id: record.id });
                  if (!success) {
                    throw new Error(errMsg);
                  }
                  setIsLoading(false);
                  actionRef.current?.reload();
                } catch (error: any) {
                  setIsLoading(false);
                  message.error(error.message);
                }
              }}
            >
              <Button
                type="primary"
                danger
                title="删除"
                icon={<DeleteFilled />}
              />
            </Popconfirm>
            <ToastContainer />
          </>
        );
      },
    },
  ];

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

    setSelectedRows([]);
  };
  return (
    <PageContainer ghost header={{ title: null, breadcrumb: undefined }}>
      <ProTable
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        request={async (values) => {
          console.log(values);
          const params = { ...values };
          if (siteId) {
            params.siteId = Number(siteId);
          }
          const {
            data,
            success,
            message: errMsg,
          } = await logisticscontrollerGetlist({
            params,
          });
          if (success) {
            return {
              total: data?.total || 0,
              data: data?.items || [],
            };
          }
          message.error(errMsg || '获取物流列表失败');
          return {
            data: [],
            success: false,
          };
        }}
        rowSelection={{
          selectedRowKeys: selectedRows.map((row) => row.id),
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
        columns={columns}
        tableAlertOptionRender={() => {
          return (
            <Space>
              <Button onClick={handleBatchPrint} type="primary">
                批量打印
              </Button>
              <Button
                danger
                type="primary"
                onClick={async () => {
                  try {
                    setIsLoading(true);
                    let ok = 0;
                    for (const row of selectedRows) {
                      const { success } =
                        await logisticscontrollerDeleteshipment({ id: row.id });
                      if (success) ok++;
                    }
                    message.success(`成功删除 ${ok} 条`);
                    setIsLoading(false);
                    actionRef.current?.reload();
                    setSelectedRows([]);
                  } catch (e) {
                    setIsLoading(false);
                  }
                }}
              >
                批量删除
              </Button>
            </Space>
          );
        }}
      />
    </PageContainer>
  );
};
export default LogisticsPage;
