import { ordercontrollerPengdingitems } from '@/servers/api/order';
import { stockcontrollerGetallstockpoints } from '@/servers/api/stock';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { App, Button } from 'antd';
import { saveAs } from 'file-saver';
import { useEffect, useRef, useState } from 'react';
import * as XLSX from 'xlsx';

const ListPage: React.FC = () => {
  const { message } = App.useApp();
  const actionRef = useRef<ActionType>();
  const [points, setPoints] = useState<API.StockPoint[]>([]);
  useEffect(() => {
    stockcontrollerGetallstockpoints().then(({ data }) => {
      setPoints(data as API.StockPoint[]);
    });
  }, []);
  const columns: ProColumns<API.StockDTO>[] = [
    {
      title: '产品名称',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      hideInSearch: true,
    },
    {
      title: '订单号',
      dataIndex: 'numbers',
      hideInSearch: true,
      width: 800,
      render: (_, record) => {
        return record?.numbers?.join?.(',');
      },
    },
  ];

  return (
    <PageContainer ghost>
      <ProTable<API.StockDTO>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        request={async (params) => {
          const { data, success } = await ordercontrollerPengdingitems(params);

          return {
            total: data?.total || 0,
            data: data?.items || [],
            success,
          };
        }}
        columns={columns}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={async () => {
              const { data, success } = await ordercontrollerPengdingitems({
                current: 1,
                pageSize: 20000,
              });
              if (!success) return;
              // 表头
              const headers = ['产品名', '数量', '订单号'];

              // 数据行
              const rows = (data?.items || []).map((item) => {
                return [item.name, item.quantity, item.numbers?.join(',')];
              });

              // 导出
              const sheet = XLSX.utils.aoa_to_sheet([headers, ...rows]);
              const book = XLSX.utils.book_new();
              XLSX.utils.book_append_sheet(book, sheet, '待发产品');
              const buffer = XLSX.write(book, {
                bookType: 'xlsx',
                type: 'array',
              });
              const blob = new Blob([buffer], {
                type: 'application/octet-stream',
              });
              saveAs(blob, '待发产品.xlsx');
            }}
          >
            导出
          </Button>,
        ]}
      />
    </PageContainer>
  );
};

export default ListPage;
