import {
  // postServiceOrderQueryServiceOrder,
  postServiceOrderWarningOrderStatistics,
} from '@/services';
import { downloadFile } from '@/services/order';
import { getSalesCodeOptions } from '@/utils/order';
import { getUserInfo } from '@/utils/user';
import {
  ActionType,
  ProFormInstance,
  ProFormSelect,
} from '@ant-design/pro-components';
import { Badge, Button, Radio, message } from 'antd';
import { format } from 'date-fns';
import React, { useEffect, useRef, useState } from 'react';
import OrderList from '../OrderList/OrderList';
import './index.less';
// import { useParams } from '@umijs/max';

const OrderPage = () => {
  const [salesCodeOptions, setSalesCodeOptions] = useState([]);
  const [salesCodeSelect, setSalesCodeSelect] = useState();
  const userInfo = getUserInfo();

  const mainTableRef = useRef<ActionType>();
  const mainTableFormRef = useRef<ProFormInstance>();
  let [searchParams] = useState(Object); //表格的查询条件存储
  console.log(searchParams);
  const [messageApi] = message.useMessage();
  console.log(messageApi);
  const [activeTabKey, setActiveTabKey] = useState(1); // **新增状态**

  //选择天数1
  const options1 = [
    {
      label: '超过7天',
      value: 7,
    },
    {
      label: '超过10天',
      value: 10,
    },
  ];
  const options2 = [
    {
      label: '超过21天',
      value: 21,
    },
    {
      label: '超过40天',
      value: 40,
    },
  ];
  const options3 = [
    {
      label: '超过20天',
      value: 20,
    },
    {
      label: '超过45天',
      value: 45,
    },
  ];
  const options4 = [
    {
      label: '超过5天',
      value: 5,
    },
    {
      label: '超过15天',
      value: 15,
    },
  ];
  const options5 = [
    {
      label: '超过30天',
      value: 30,
    },
    {
      label: '超过75天',
      value: 75,
    },
    {
      label: '超过90天',
      value: 90,
    },
    {
      label: '超过120天',
      value: 120,
    },
  ];
  //选择天数
  const [calDate, setCalDate] = useState<string | null>(null);
  const [value1, setValue1] = useState(0);
  const radioOnChange1 = ({ target: { value } }) => {
    const currentDate = new Date();
    // 创建一个新的日期对象,并在当前日期的基础上加上 daysToAdd 天
    const newDate = new Date(currentDate);
    newDate.setDate(currentDate.getDate() - value);
    const formattedDate = format(newDate, 'yyyy-MM-dd HH:mm:ss');
    setCalDate(formattedDate);
    setValue1(value);
  };
  function setOriginTime(value) {
    const currentDate = new Date();
    // 创建一个新的日期对象,并在当前日期的基础上加上 daysToAdd 天
    const newDate = new Date(currentDate);
    newDate.setDate(currentDate.getDate() - value);
    const formattedDate = format(newDate, 'yyyy-MM-dd HH:mm:ss');
    return formattedDate;
  }
  const [invoiceWarningNum, setInvoiceWarningNum] = useState(0);
  const [invoiceCreateWarningNum, setInvoiceCreateWarningNum] = useState(0);
  const [invoiceRefundWarningNum, setInvoiceRefundWarningNum] = useState(0);
  const [waitConfirmPayment, setWaitConfirmPayment] = useState(0);
  const [waitFeedback, setWaitFeedback] = useState(0);
  const [staticSalesCode, setStaticSalesCode] = useState(userInfo.username);
  const [salesCodePermission, setSalesCodePermission] = useState(false);
  //修改预警数请求salesCode
  const changeSalesCode = () => {
    if (salesCodeSelect === undefined) {
      setStaticSalesCode(userInfo.username);
    } else {
      setStaticSalesCode(salesCodeSelect);
    }
  };
  //选择栏权限
  const permission = () => {
    const { roles } = userInfo;
    const boolean =
      roles?.includes('SALES_MANAGER') || roles?.includes('ADMIN');
    if (boolean) {
      setSalesCodePermission(true);
    }
  };
  async function getInvoiceWarningNum() {
    changeSalesCode();
    const res = await postServiceOrderWarningOrderStatistics({
      data: {
        salesCode: staticSalesCode,
        waitConfirmReiceptStatusDateTimeLe: setOriginTime(options1[0].value),
        waitInvoicingStatusDateTimeLe: setOriginTime(options2[0].value),
        waitFeedbackStatusDateTimeLe: setOriginTime(options3[0].value),
        waitConfirmInvoiceStatusDateTimeLe: setOriginTime(options4[0].value),
        waitConfirmPaymentStatusDateTimeLe: setOriginTime(options5[0].value),
      },
    });
    setInvoiceWarningNum(res.data.waitConfirmInvoice);
    setInvoiceCreateWarningNum(res.data.waitInvoicing);
    setInvoiceRefundWarningNum(res.data.waitConfirmReceipt);
    setWaitConfirmPayment(res.data.waitConfirmPayment);
    setWaitFeedback(res.data.waitFeedback);
  }
  useEffect(() => {
    //预警订单数
    getInvoiceWarningNum();
    permission();
  }, [salesCodeSelect]);
  //biaojiup
  // 监听 calDate 变化,触发请求
  useEffect(() => {
    mainTableRef.current?.reload();
  }, [calDate]);
  useEffect(() => {
    if (
      activeTabKey === 1 ||
      activeTabKey === 2 ||
      activeTabKey === 3 ||
      activeTabKey === 4 ||
      activeTabKey === 5
    ) {
      setValue1(0); // 清空 value1
    }
    mainTableRef.current?.reload(); // **修改位置:在选择第二个标签时请求request2**
  }, [activeTabKey]);
  // 修改位置:监听 value1 的变化
  // useEffect(() => {
  //   // if (value1 === 0) {
  //   //   // 这里执行你希望在 value1 为 0 时的逻辑
  //   //   mainTableRef.current?.reload(); // 重新请求数据
  //   // }

  // }, [value1]); // 添加了 value1 作为依赖

  useEffect(() => {
    // 根据 activeTabKey 设置 value1 为当前选项组的第一个 value
    let options;
    switch (activeTabKey) {
      case 1:
        options = options1;
        break;
      case 2:
        options = options2;
        break;
      case 3:
        options = options3;
        break;
      case 4:
        options = options4;
        break;
      case 5:
        options = options5;
        break;
      default:
        options = []; // 如果没有匹配的选项组,默认为空
    }

    const firstOptionValue = options[0]?.value || 0; // 获取第一个值
    setValue1(firstOptionValue);
    const currentDate = new Date();
    // 创建一个新的日期对象,并在当前日期的基础上加上 daysToAdd 天
    const newDate = new Date(currentDate);
    newDate.setDate(currentDate.getDate() - firstOptionValue);
    const formattedDate = format(newDate, 'yyyy-MM-dd HH:mm:ss');
    setCalDate(formattedDate);
  }, [activeTabKey]);
  //biaojidown2
  //取消单选,将时间设为null
  const handleSetNull = () => {
    setCalDate(null); // 这应该会触发 useEffect
  };
  const selectSalesCode = (value) => {
    setSalesCodeSelect(value); // 这应该会触发 useEffect
  };
  const warningOptions = [
    {
      value: 1,
      label: (
        <span>
          确认收货预警
          <Badge count={invoiceRefundWarningNum} style={{ marginLeft: 8 }} />
        </span>
      ),
    },
    {
      value: 2,
      label: (
        <span>
          开票预警
          <Badge count={invoiceCreateWarningNum} style={{ marginLeft: 8 }} />
        </span>
      ),
    },
    {
      value: 3,
      label: (
        <span>
          回访登记预警
          <Badge count={waitFeedback} style={{ marginLeft: 8 }} />
        </span>
      ),
    },
    {
      value: 4,
      label: (
        <span>
          确认发票预警
          <Badge count={invoiceWarningNum} style={{ marginLeft: 8 }} />
        </span>
      ),
    },
    {
      value: 5,
      label: (
        <span>
          订单回款预警
          <Badge count={waitConfirmPayment} style={{ marginLeft: 8 }} />
        </span>
      ),
    },
  ];
  return (
    <div className="order-page-container">
      <div id="resizeDiv"></div>
      <div key={'activeTabKey'}>
        <Radio.Group
          options={warningOptions}
          onChange={(e) => {
            setActiveTabKey(e.target.value);
            mainTableRef.current?.reload(); // 重新请求数据
          }}
          value={activeTabKey}
          optionType="button"
        />
      </div>
      <div style={{ height: '25px' }}></div>
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          width: '100%',
        }}
      >
        {/* 左边的 Radio.Group */}
        <span style={{ flex: '1' }}>
          {' '}
          {/* 修改:设置 flex 属性 */}
          <Radio.Group value={value1} onChange={radioOnChange1}>
            {(activeTabKey === 1
              ? options1
              : activeTabKey === 2
                ? options2
                : activeTabKey === 3
                  ? options3
                  : activeTabKey === 4
                    ? options4
                    : options5
            ).map((option) => (
              <Radio
                key={option.value}
                value={option.value}
                onClick={(e) => {
                  radioOnChange1(
                    e as unknown as React.ChangeEvent<HTMLInputElement>,
                  );
                  handleSetNull();
                }}
              >
                {option.label}
              </Radio>
            ))}
          </Radio.Group>
        </span>

        {/* 右边的 ProFormSelect */}
        <span style={{ width: '300px', marginLeft: 'auto', marginTop: '30px' }}>
          {' '}
          {/* 修改:设置 width 和 marginLeft */}
          {salesCodePermission && (
            <ProFormSelect
              name="salesCode"
              key="salesCode"
              width="200px"
              actionRef={mainTableRef}
              formRef={mainTableFormRef}
              initialValue={userInfo.username}
              showSearch
              label="销售代表"
              placeholder="请输入销售代表"
              options={salesCodeOptions}
              onChange={(_, option) => {
                if (option === undefined) {
                  selectSalesCode(userInfo.username);
                }
                // if (option.value !== undefined) {
                //   selectSalesCode(option.value);
                // }
                if (option && option.value !== undefined) {
                  selectSalesCode(option.value);
                }
                mainTableRef.current?.reload();
              }}
              request={async () => {
                let options = await getSalesCodeOptions();
                setSalesCodeOptions(options);
                return options;
              }}
            />
          )}
        </span>
        {/* 右边的 ProFormSelect */}
        <span style={{ width: '100px', marginLeft: '' }}>
          {' '}
          <Button
            key="out"
            onClick={() => {
              let initialParams = {};
              initialParams.isDeleteQueryOrder = false;
              initialParams.flag = 50;
              initialParams.current = 1;
              initialParams.pageSize = 10;
              initialParams.condition = 0;
              initialParams.sorted = false;
              // 根据activeTabKey动态扩展参数
              if (activeTabKey === 1) {
                initialParams = {
                  ...initialParams,
                  orderStatus: 'SHIPPED',
                  statusDatetimeLe: calDate,
                };
              } else if (activeTabKey === 2) {
                initialParams = {
                  ...initialParams,
                  warningStatus: 'invoicingWarning',
                  confirmReceiptDatetimeLe: calDate,
                };
              } else if (activeTabKey === 3) {
                initialParams = {
                  ...initialParams,
                  warningStatus: 'waitFeedbackWarning',
                  confirmReceiptDatetimeLe: calDate,
                };
              } else if (activeTabKey === 4) {
                initialParams = {
                  ...initialParams,
                  warningStatus: 'invoiceConfirmWarning',
                  invoicingEndTime: calDate,
                };
              } else if (activeTabKey === 5) {
                initialParams = {
                  ...initialParams,
                  warningStatus: 'paymentReceiptStatusWarning',
                  paymentNotReceipt: true,
                  applyTimeLe: calDate,
                };
              }
              messageApi.open({
                type: 'loading',
                content: '导出中...',
                duration: 0,
              });
              downloadFile(
                '/api/service/order/export',
                '预警订单.xlsx',
                'POST',
                initialParams,
                () => {
                  messageApi.destroy();
                },
              );
            }}
          >
            导出
          </Button>
        </span>
      </div>

      <div style={{ height: '15px' }}></div>
      {/* <OrderList
        params={{
          ...(salesCodePermission && {
            salesCode: salesCodeSelect !==
              undefined && salesCodeSelect !== null ? salesCodeSelect : userInfo.username
          }),
          ...(activeTabKey === 1 && {
            orderStatus: 'SHIPPED',
            warningStatus: 'waitConfirmReicept',
            statusDatetimeLe: calDate,
          }),
          ...(activeTabKey === 2 && {
            warningStatus: 'waitFeedbackWarning',
            confirmReceiptDatetimeLe: calDate,
          }),
          ...(activeTabKey === 3 && {
            warningStatus: 'invoiceConfirmWarning',
            invoicingEndTime: calDate,
          }),
          ...(activeTabKey === 4 && {
            warningStatus: 'paymentReceiptStatusWarning',
            paymentNotReceipt: true,
            applyTimeLe: calDate,
          }),
        }}
        searchShow={false}
        toolbarShow={false} /> */}
      <OrderList
        paramsNew={(function () {
          // 初始化参数
          let initialParams = {};
          initialParams.isDeleteQueryOrderNow = false;
          initialParams.salesCode = userInfo.username;
          if (salesCodePermission) {
            if (salesCodeSelect !== undefined && salesCodeSelect !== null) {
              initialParams.salesCode = salesCodeSelect;
            } else {
              initialParams.salesCode = userInfo.username;
            }
          }
          // 根据activeTabKey动态扩展参数
          if (activeTabKey === 1) {
            initialParams = {
              ...initialParams,
              orderStatus: 'SHIPPED',
              warningStatus: 'waitConfirmReicept',
              statusDatetimeLe: calDate,
            };
          } else if (activeTabKey === 2) {
            initialParams = {
              ...initialParams,
              warningStatus: 'invoicingWarning',
              confirmReceiptDatetimeLe: calDate,
            };
          } else if (activeTabKey === 3) {
            initialParams = {
              ...initialParams,
              warningStatus: 'waitFeedbackWarning',
              confirmReceiptDatetimeLe: calDate,
            };
          } else if (activeTabKey === 4) {
            initialParams = {
              ...initialParams,
              warningStatus: 'invoiceConfirmWarning',
              invoicingEndTime: calDate,
            };
          } else if (activeTabKey === 5) {
            initialParams = {
              ...initialParams,
              warningStatus: 'paymentReceiptStatusWarning',
              paymentNotReceipt: true,
              applyTimeLe: calDate,
            };
          }
          // 返回完整的参数对象
          return initialParams;
        })()}
        searchShow={false}
        toolbarShow={false}
      />
    </div>
  );
};

export default OrderPage;