import { statisticscontrollerStockforecast } from '@/servers/api/statistics';
import { stockcontrollerGetallstockpoints } from '@/servers/api/stock';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProFormDatePicker,
  ProFormDigit,
  ProTable,
} from '@ant-design/pro-components';
import dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';

const ListPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [points, setPoints] = useState<API.StockPoint[]>([]);
  useEffect(() => {
    stockcontrollerGetallstockpoints().then(({ data }) => {
      setPoints(data as API.StockPoint[]);
    });
  }, []);

  const [real, setReal] = useState({});

  const columns: ProColumns[] = [
    {
      title: '产品名称',
      dataIndex: 'productName',
    },
    {
      title: 'SKU',
      dataIndex: 'productSku',
      hideInSearch: true,
    },
    ...points
      ?.filter((point: API.StockPoint) => !point.ignore)
      ?.map((point: API.StockPoint) => ({
        title: point.name,
        dataIndex: `point_${point.name}`,
        hideInSearch: true,
        render(_: any, record: any) {
          const quantity = record.stockDetails?.find(
            (item: any) => item.id === point.id,
          )?.quantity;
          return quantity || 0;
        },
      })),
    {
      title: '途中库存',
      dataIndex: 'transitStock',
      hideInSearch: true,
    },
    {
      title: '加拿大库存',
      dataIndex: 'caTotalStock',
      hideInSearch: true,
      render(_, record) {
        if (!record.caTotalStock || record.caTotalStock > 400) {
          return record.caTotalStock;
        }
        return <span style={{ color: 'red' }}>{record.caTotalStock}</span>;
      },
    },
    {
      title: '总库存',
      dataIndex: 'totalStock',
      hideInSearch: true,
    },
    {
      title: '30天',
      dataIndex: 'totalSales_30',
      hideInSearch: true,
    },
    {
      title: '2*15天',
      dataIndex: 'totalSales_15',
      hideInSearch: true,
    },
    {
      title: '补货数量',
      dataIndex: 'restockQuantity',
      hideInSearch: true,
    },
    {
      title: '实补数量',
      dataIndex: 'restockQuantityReal',
      hideInSearch: true,
      render(_, record) {
        return (
          <ProFormDigit
            key={record.productSku}
            initialValue={0}
            fieldProps={{
              onChange(value) {
                setReal({
                  ...real,
                  [record.productSku]: value,
                });
              },
            }}
          />
        );
      },
    },
    {
      title: 'B端实补数量',
      dataIndex: 'restockQuantityReal',
      hideInSearch: true,
      render(_, record) {
        return <ProFormDigit key={'b_' + record.productSku} />;
      },
    },
    {
      title: '加拿大剩余天数',
      dataIndex: 'caAvailableDays',
      hideInSearch: true,
      render(_, record) {
        if (!record.caAvailableDays || record.caAvailableDays > 40) {
          return record.caAvailableDays;
        }
        return <span style={{ color: 'red' }}>{record.caAvailableDays}</span>;
      },
    },
    {
      title: '剩余天数',
      dataIndex: 'availableDays',
      hideInSearch: true,
      render(_, record) {
        if (!record.availableDays || record.availableDays > 70) {
          return record.availableDays;
        }
        return <span style={{ color: 'red' }}>{record.availableDays}</span>;
      },
    },
    {
      title: '实补后剩余天数',
      hideInSearch: true,
      render(_, record) {
        if (!record.availableDays) return '-';
        const availableDays = Number(record.availableDays);
        const quantity = real?.[record.productSku] || 0;
        const day =
          availableDays +
          Math.floor(
            quantity /
              (Math.max(record.totalSales_30, record.totalSales_15) / 30),
          );
        return day;
      },
    },
    {
      title: '实补后日期',
      hideInSearch: true,
      render(_, record) {
        if (!record.availableDays) return '-';
        const availableDays = Number(record.availableDays);
        const quantity = real?.[record.productSku] || 0;
        const day =
          availableDays +
          Math.floor(
            quantity /
              (Math.max(record.totalSales_30, record.totalSales_15) / 30),
          );
        return (
          <ProFormDatePicker
            readonly
            fieldProps={{ value: dayjs().add(day, 'd') }}
          />
        );
      },
    },
  ];
  return (
    <PageContainer ghost>
      <ProTable
        // tableStyle={{ height: '80vh', overflow: 'auto' }}
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        request={async (param) => {
          const { data, success } = await statisticscontrollerStockforecast(
            param,
          );
          if (success) {
            return {
              total: data?.total || 0,
              data: data?.items || [],
            };
          }
          return {
            data: [],
          };
        }}
        columns={columns}
        dateFormatter="number"
      />
    </PageContainer>
  );
};

export default ListPage;
