import { ordercontrollerGetordersales } from '@/servers/api/order';
import { sitecontrollerAll } from '@/servers/api/site';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProFormSwitch,
  ProTable,
} from '@ant-design/pro-components';
import { Button } from 'antd';
import dayjs from 'dayjs';
import { saveAs } from 'file-saver';
import { useRef, useState } from 'react';
import * as XLSX from 'xlsx';

const ListPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef();
  const [total, setTotal] = useState(0);
  const [isSource, setIsSource] = useState(false);
  const [yooneTotal, setYooneTotal] = useState({});

  const columns: ProColumns<API.OrderSaleDTO>[] = [
    {
      title: '时间段',
      dataIndex: 'dateRange',
      valueType: 'dateTimeRange',
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请选择时间段',
          },
        ],
      },
    },
    {
      title: '排除套装',
      dataIndex: 'exceptPackage',
      valueType: 'switch',
      hideInTable: true,
    },
    {
      title: '产品名称',
      dataIndex: 'name',
    },
    {
      title: '站点',
      dataIndex: 'siteId',
      valueType: 'select',
      request: async () => {
        const { data = [] } = await sitecontrollerAll();
        return data.map((item) => ({
          label: item.name,
          value: item.id,
        }));
      },
      hideInTable: true,
    },
    // {
    //   title: '分类',
    //   dataIndex: 'categoryName',
    //   hideInSearch: true,
    //   hideInTable: isSource,
    // },
    {
      title: '数量',
      dataIndex: 'totalQuantity',
      hideInSearch: true,
    },
    {
      title: '一单订单数',
      dataIndex: 'firstOrderCount',
      hideInSearch: true,
      render(_, record) {
        if (isSource) return record.firstOrderCount;
        return `${record.firstOrderCount}(${record.firstOrderYOONEBoxCount})`;
      },
    },
    {
      title: '两单订单数',
      dataIndex: 'secondOrderCount',
      hideInSearch: true,
      render(_, record) {
        if (isSource) return record.secondOrderCount;
        return `${record.secondOrderCount}(${record.secondOrderYOONEBoxCount})`;
      },
    },
    {
      title: '三单订单数',
      dataIndex: 'thirdOrderCount',
      hideInSearch: true,
      render(_, record) {
        if (isSource) return record.thirdOrderCount;
        return `${record.thirdOrderCount}(${record.thirdOrderYOONEBoxCount})`;
      },
    },
    {
      title: '三单以上订单数',
      dataIndex: 'moreThirdOrderCount',
      hideInSearch: true,
      render(_, record) {
        if (isSource) return record.moreThirdOrderCount;
        return `${record.moreThirdOrderCount}(${record.moreThirdOrderYOONEBoxCount})`;
      },
    },
    {
      title: '订单数',
      dataIndex: 'totalOrders',
      hideInSearch: true,
    },
  ];
  return (
    <PageContainer ghost>
      <ProTable
        headerTitle="查询表格"
        actionRef={actionRef}
        formRef={formRef}
        rowKey="id"
        params={{ isSource }}
        form={{
          // ignoreRules: false,
          initialValues: {
            dateRange: [dayjs().startOf('month'), dayjs().endOf('month')],
          },
        }}
        request={async ({ dateRange, ...param }) => {
          const [startDate, endDate] = dateRange.values();
          const { data, success } = await ordercontrollerGetordersales({
            startDate,
            endDate,
            ...param,
          });
          if (success) {
            setTotal(data?.totalQuantity || 0);
            setYooneTotal({
              yoone3Quantity: data?.yoone3Quantity || 0,
              yoone6Quantity: data?.yoone6Quantity || 0,
              yoone9Quantity: data?.yoone9Quantity || 0,
              yoone12Quantity: data?.yoone12Quantity || 0,
              yoone12QuantityNew: data?.yoone12QuantityNew || 0,
              yoone15Quantity: data?.yoone15Quantity || 0,
              yoone18Quantity: data?.yoone18Quantity || 0,
              zexQuantity: data?.zexQuantity || 0,
            });
            return {
              total: data?.total || 0,
              data: data?.items || [],
            };
          }
          setTotal(0);
          setYooneTotal({});
          return {
            data: [],
          };
        }}
        columns={columns}
        dateFormatter="number"
        footer={() => `总计: ${total}`}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={async () => {
              const { dateRange, param } = formRef.current?.getFieldsValue();
              const [startDate, endDate] = dateRange.values();
              const { data, success } = await ordercontrollerGetordersales({
                startDate: dayjs(startDate).valueOf(),
                endDate: dayjs(endDate).valueOf(),
                ...param,
                current: 1,
                pageSize: 20000,
              });
              if (!success) return;
              // 表头
              const headers = ['产品名', '数量'];

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

              // 导出
              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>,
          <ProFormSwitch
            label="原产品"
            fieldProps={{
              value: isSource,
              onChange: () => setIsSource(!isSource),
            }}
          />,
        ]}
      />
      <div
        style={{
          background: '#fff',
          display: 'flex',
          flexDirection: 'row',
          justifyContent: 'space-between',
          padding: '10px',
          marginTop: '20px',
        }}
      >
        <div>
          YOONE:{' '}
          {(yooneTotal.yoone3Quantity || 0) +
            (yooneTotal.yoone6Quantity || 0) +
            (yooneTotal.yoone9Quantity || 0) +
            (yooneTotal.yoone12Quantity || 0) +
            (yooneTotal.yoone15Quantity || 0) +
            (yooneTotal.yoone18Quantity || 0) +
            (yooneTotal.zexQuantity || 0)}
        </div>
        <div>YOONE 3MG: {yooneTotal.yoone3Quantity || 0}</div>
        <div>YOONE 6MG: {yooneTotal.yoone6Quantity || 0}</div>
        <div>YOONE 9MG: {yooneTotal.yoone9Quantity || 0}</div>
        <div>YOONE 12MG新: {yooneTotal.yoone12QuantityNew || 0}</div>
        <div>
          YOONE 12MG白:{' '}
          {(yooneTotal.yoone12Quantity || 0) -
            (yooneTotal.yoone12QuantityNew || 0)}
        </div>
        <div>YOONE 15MG: {yooneTotal.yoone15Quantity || 0}</div>
        <div>YOONE 18MG: {yooneTotal.yoone18Quantity || 0}</div>
        <div>ZEX: {yooneTotal.zexQuantity || 0}</div>
      </div>
    </PageContainer>
  );
};

export default ListPage;
