import hocAuth from "@/hocs/auth";
import { CommonComponent } from "@/types/typings";
import Taro from "@tarojs/taro";
import { business } from "@/services";
import { useEffect, useRef, useState } from "react";
import { View } from "@tarojs/components";
import {
  ActionSheet,
  Button,
  Dialog,
  Input,
  SafeArea,
  Toast,
} from "@nutui/nutui-react-taro";
import {
  BasicInfoSection,
  BasicInfoSectionRef,
  CompanyInfoSection,
  CompanyInfoSectionRef,
  CostDifferenceSection,
  CostSummarySection,
  DealerInfoSection,
  DealerInfoSectionRef,
  DeliveryFormSection,
  DeliveryFormSectionRef,
  EmptyBoxInfoSection,
  Icon,
  MarketPriceSection,
  MarketPriceSectionRef,
  MaterialCostSection,
  OrderRejectApprove,
  PackageInfoSection,
  PackagingCostSection,
  ProductionAdvanceSection,
  ProductionLossSection,
  PurchaseCostInfoSection,
  PurchaseFormSection,
  RebateCalcSection,
  State,
  SupplierInfoSection,
  TaxProvisionSection,
  TaxSubsidySection,
  WorkerAdvanceSection,
} from "@/components";
import {
  buildUrl,
  convertOrderToOrderShip,
  generateShortId,
  OrderCalculator,
} from "@/utils";
import classNames from "classnames";
import { DecimalUtils } from "@/utils/classes/calculators/core/DecimalUtils";
import order from "@/constant/order";

// Section ref 类型
type SectionRef =
  | BasicInfoSectionRef
  | CompanyInfoSectionRef
  | DealerInfoSectionRef
  | MarketPriceSectionRef
  | DeliveryFormSectionRef
  | null;

const defaultSections = [
  "marketPrice",
  "supplierInfo",
  "dealerInfo",
  "basicInfo",
  "packageInfo",
  "emptyBoxInfo",
  "foremanAdvance",
  "materialCost",
  "originAdvance",
  "otherCost",
  "productionLoss",
  "taxSubsidy",
  "taxProvision",
  "costDifference",
  "costSummary",
  "rebateCalc",
  "deliveryForm",
];

const defaultMarketSections = [
  "marketPrice",
  "supplierInfo",
  "dealerInfo",
  "basicInfo",
  "packageInfo",
  "emptyBoxInfo",
  "otherCost",
  "productionLoss",
  "taxSubsidy",
  "taxProvision",
  "costDifference",
  "costSummary",
  "rebateCalc",
  "deliveryForm",
];

const xylSections = [
  "marketPrice",
  "supplierInfo",
  "dealerInfo",
  "basicInfo",
  "purchaseCostInfo",
  "purchaseForm",
  "packageInfo",
  "emptyBoxInfo",
  "foremanAdvance",
  "materialCost",
  "originAdvance",
  "otherCost",
  "productionLoss",
  "taxSubsidy",
  "taxProvision",
  "costDifference",
  "costSummary",
  "rebateCalc",
];

const fullSections = [
  // 市场报价
  {
    name: "marketPrice",
    component: MarketPriceSection,
    title: "市场报价",
  },
  // 我方入账公司
  {
    name: "supplierInfo",
    component: CompanyInfoSection,
    title: "我方入账公司",
  },
  // 下游经销商信息
  {
    name: "dealerInfo",
    component: DealerInfoSection,
    title: "下游经销商",
  },
  // 基础信息
  {
    name: "basicInfo",
    component: BasicInfoSection,
    title: "基础信息",
  },
  // 瓜农信息
  {
    name: "farmerInfo",
    component: SupplierInfoSection,
    title: "瓜农信息",
  },
  // 采购成本
  {
    name: "purchaseCostInfo",
    component: PurchaseCostInfoSection,
    title: "采购成本复核",
  },
  // 分单发货复核
  {
    name: "purchaseForm",
    component: PurchaseFormSection,
    title: "分单发货复核",
  },
  // 包装纸箱费
  {
    name: "packageInfo",
    component: PackageInfoSection,
    title: "包装纸箱费复核",
  },
  // 空箱费用
  {
    name: "emptyBoxInfo",
    component: EmptyBoxInfoSection,
    title: "空箱费用复核",
  },
  // 人工费用复核
  {
    name: "foremanAdvance",
    component: WorkerAdvanceSection,
    title: "人工费用复核",
  },
  // 辅料费用复核
  {
    name: "materialCost",
    component: MaterialCostSection,
    title: "辅料费复核",
  },
  // 产地费用复核
  {
    name: "originAdvance",
    component: ProductionAdvanceSection,
    title: "产地费用复核",
  },
  // 其他费用复核
  {
    name: "otherCost",
    component: PackagingCostSection,
    title: "其他费用复核",
  },
  // 产地损耗复核
  {
    name: "productionLoss",
    component: ProductionLossSection,
    title: "产地损耗复核",
  },
  // 公司返点复核
  {
    name: "taxSubsidy",
    component: TaxSubsidySection,
    title: "公司返点复核",
  },
  // 计提税金复核
  {
    name: "taxProvision",
    component: TaxProvisionSection,
    title: "计提税金复核",
  },
  // 待分红金额复核
  {
    name: "costDifference",
    component: CostDifferenceSection,
    title: "待分红金额复核",
  },
  // 成本合计复核
  {
    name: "costSummary",
    component: CostSummarySection,
    title: "成本合计复核",
  },
  // 个人返点复核
  {
    name: "rebateCalc",
    component: RebateCalcSection,
    title: "个人返点复核",
  },
  // 发货单复核
  {
    name: "deliveryForm",
    component: DeliveryFormSection,
    title: "发货单复核",
  },
];

export default hocAuth(function Page(props: CommonComponent) {
  const { router, isInitialized, setIsInitialized, setLoading } = props;

  const orderId = router.params.orderId as BusinessAPI.OrderVO["orderId"];
  const auditId = router.params.auditId as BusinessAPI.AuditVO["auditId"];

  // Section refs 映射
  const sectionRefs = useRef<Record<string, SectionRef>>({});

  // 费用项目列表
  const [costList, setCostList] = useState<BusinessAPI.CostVO[]>([]);

  const [auditVO, setAuditVO] = useState<BusinessAPI.AuditVO>();
  const [orderVO, setOrderVO] = useState<BusinessAPI.OrderVO>();

  console.log("orderVO", orderVO);

  const [originPrincipal, setOriginPrincipal] = useState("");

  // 暂存和提交审核的Dialog状态
  const [saveDialogVisible, setSaveDialogVisible] = useState(false);
  const [submitDialogVisible, setSubmitDialogVisible] = useState(false);
  const [provisionZeroConfirmVisible, setProvisionZeroConfirmVisible] =
    useState(false);

  // 控制更多操作的ActionSheet显示状态
  const [moreActionVisible, setMoreActionVisible] = useState(false);

  // 控制快速导航的显示状态
  const [quickNavExpanded, setQuickNavExpanded] = useState(false);

  // 暂存操作
  const handleSave = () => {
    setSaveDialogVisible(true);
  };

  // 确认暂存
  const confirmSave = async () => {
    // 关闭对话框
    setSaveDialogVisible(false);

    // 这里应该调用暂存API
    console.log("暂存数据:", orderVO);

    const { data } = await business.order.approveOrder({
      ...orderVO!,
      auditId: auditId,
      draft: true,
    });

    if (data.success) {
      Toast.show("toast", {
        icon: "success",
        title: "提示",
        content: "暂存成功",
      });
      // 返回采购单页面
      Taro.redirectTo({ url: "/pages/audit/pending" });
    }
  };

  // 检查计提费是否为0
  const checkProvisionFeeZero = () => {
    const provisionCost = orderVO?.orderCostList.find(
      (item) => item.name === "计提费" && item.type === "OTHER_TYPE",
    );

    // 如果没有计提费或者计提费金额为0，返回true
    return !provisionCost || provisionCost.price === 0;
  };

  // 提交老板审核操作
  const handleSubmit = () => {
    // 检查计提费是否为0
    if (checkProvisionFeeZero()) {
      // 计提费为0，弹出确认对话框
      setProvisionZeroConfirmVisible(true);
    } else {
      // 计提费不为0，直接弹出提交确认对话框
      setSubmitDialogVisible(true);
    }
  };

  // 确认提交老板审核
  const confirmSubmit = async () => {
    // 关闭对话框
    setSubmitDialogVisible(false);

    // 先调用所有 section 的 validateForm 方法进行校验
    const sectionErrors: string[] = [];
    Object.entries(sectionRefs.current).forEach(
      ([_sectionName, sectionRef]) => {
        if (sectionRef && sectionRef.validateForm) {
          const error = sectionRef.validateForm();
          if (error) {
            sectionErrors.push(error);
          }
        }
      },
    );

    if (sectionErrors.length > 0) {
      Toast.show("toast", {
        icon: "fail",
        title: "校验失败",
        content: sectionErrors[0],
      });
      return;
    }

    if (!orderVO) {
      Toast.show("toast", {
        icon: "fail",
        title: "提示",
        content: "提交失败",
      });
      return;
    }

    // 公司返点（税费补贴）
    if (
      (orderVO.orderDealer.taxSubsidy === null ||
        orderVO.orderDealer.taxSubsidy === undefined) &&
      orderVO.orderDealer.enableCompanyRebate
    ) {
      orderVO.orderDealer.taxSubsidy = calculator.getTaxSubsidy();
    }

    // 利润分成
    if (
      (orderVO.orderDealer.profitSharing === null ||
        orderVO.orderDealer.profitSharing === undefined) &&
      orderVO.orderDealer.shareAdjusted
    ) {
      orderVO.orderDealer.profitSharing = calculator.getNetProfit();
    }

    // 损失金额
    if (
      (orderVO.orderDealer.lossAmount === null ||
        orderVO.orderDealer.lossAmount === undefined) &&
      orderVO.orderDealer.enableLoss
    ) {
      orderVO.orderDealer.lossAmount = calculator.getLossAmount();
    }

    // 计提税金
    if (
      (orderVO.orderDealer.taxProvision === null ||
        orderVO.orderDealer.taxProvision === undefined) &&
      orderVO.orderDealer.enableAccrualTax
    ) {
      orderVO.orderDealer.taxProvision = calculator.getTaxProvision();
    }

    const {
      data: { data: auditVO, success, errMessage },
    } = await business.order.approveOrder({
      ...orderVO!,
      auditId: auditId,
      draft: false,
    });

    if (success) {
      Toast.show("toast", {
        icon: "success",
        title: "提示",
        content: "提交审核成功",
      });
      // 跳转到提交结果页面
      Taro.redirectTo({
        url: buildUrl("/pages/audit/result", {
          orderId: orderVO!.orderId,
          auditId: auditVO!.auditId,
        }),
      });
    } else {
      Toast.show("toast", {
        icon: "fail",
        title: "提示",
        content: errMessage,
      });
    }
  };

  // 确认计提费为0仍继续提交
  const confirmProvisionZeroSubmit = () => {
    setProvisionZeroConfirmVisible(false);
    confirmSubmit();
  };

  // 取消提交（当计提费为0时）
  const cancelProvisionZeroSubmit = () => {
    setProvisionZeroConfirmVisible(false);
  };

  // 跳转到指定section
  const scrollToSection = (sectionKey: string) => {
    if (process.env.TARO_ENV === "h5") {
      // H5环境使用DOM API
      const element = document.getElementById(`section-${sectionKey}`);
      if (element) {
        element.scrollIntoView({ behavior: "smooth", block: "start" });
      }
    } else {
      // 小程序环境使用Taro的节点查询
      Taro.createSelectorQuery()
        .select(`#section-${sectionKey}`)
        .boundingClientRect((rect) => {
          if (rect) {
            Taro.pageScrollTo({
              //@ts-ignore
              scrollTop: rect.top,
              duration: 300,
            });
          }
        })
        .exec();
    }
  };

  const init = async (
    orderId: BusinessAPI.OrderVO["orderId"],
    auditId: BusinessAPI.AuditVO["auditId"],
  ) => {
    const {
      data: { data: auditVO, success: auditSuccess },
    } = await business.audit.showAudit({
      auditShowQry: {
        auditId,
      },
    });

    if (auditSuccess && auditVO) {
      setAuditVO(auditVO);
    }

    const {
      data: { data: orderVO, success: orderSuccess },
    } = await business.order.showOrder({
      orderShowQry: {
        orderId,
      },
    });

    if (orderSuccess && orderVO) {
      if (!orderVO.orderShipList || orderVO.orderShipList.length === 0) {
        orderVO.orderShipList = [convertOrderToOrderShip(orderVO)];
      }

      if (!orderVO.orderRebate && orderVO.type === "PRODUCTION_PURCHASE") {
        const {
          data: { data: dealerRebateCustomerVOList },
        } = await business.dealerRebateCustomer.listDealerRebateCustomer({
          dealerRebateCustomerListQry: {
            dealerId: orderVO?.orderDealer?.dealerId!,
            status: true,
          },
        });

        if (
          dealerRebateCustomerVOList &&
          dealerRebateCustomerVOList.length > 0
        ) {
          orderVO.orderRebate = dealerRebateCustomerVOList[0] as any;
        }
      }

      orderVO.orderCostList.map((item) => {
        if (!item.price) {
          item.price = orderVO.orderCostItemList
            .filter((orderCost) =>
              item.costItemIds?.includes(orderCost.costItemId!),
            )
            ?.reduce(
              (acc, cur) =>
                DecimalUtils.add(
                  acc,
                  DecimalUtils.multiply(cur.price || 0, cur.count || 0),
                ),
              0,
            );
        }
        item.selected = true;

        return item;
      });

      const {
        data: { data: costList },
      } = await business.cost.listCost({
        costListQry: {
          status: true,
        },
      });

      setCostList(costList || []);

      const cost1 = costList?.find(
        (cost) => cost.name === "计提费" && cost.type === "OTHER_TYPE",
      );
      const orderCost1 = orderVO?.orderCostList?.find(
        (cost) => cost.name === "计提费" && cost.type === "OTHER_TYPE",
      );

      if (!orderCost1 && cost1) {
        orderVO.orderCostList.push({
          orderCostId: generateShortId(),
          costId: cost1.costId || "",
          name: cost1.name || "",
          price: cost1.price || 0,
          unit: cost1.unit || "元",
          count: 1,
          type: "OTHER_TYPE",
          costItemIds: [],
          belong: cost1.belong,
          selected: true,
        });
      }

      const costName =
        orderVO?.orderVehicle.priceType === "SHORT_TRANSPORT"
          ? "短驳费"
          : "主运费";
      const cost2 = costList?.find(
        (cost) => cost.name === costName && cost.type === "LOGISTICS_TYPE",
      );
      const orderCost2 = orderVO?.orderCostList?.find(
        (cost) => cost.name === costName && cost.type === "LOGISTICS_TYPE",
      );
      // 加运费
      if (orderVO.orderVehicle.price && !orderCost2 && cost2) {
        orderVO.orderCostList.push({
          orderCostId: generateShortId(),
          costId: cost2.costId || "",
          name: cost2.name || "",
          price: orderVO.orderVehicle.price,
          unit: cost2.unit || "元",
          count: 1,
          type: "LOGISTICS_TYPE",
          costItemIds: [],
          belong: cost2.belong,
          selected: true,
        });
      }

      const cost3 = costList?.find(
        (cost) => cost.name === "草帘费" && cost.type === "LOGISTICS_TYPE",
      );
      const orderCost3 = orderVO?.orderCostList?.find(
        (cost) => cost.name === "草帘费" && cost.type === "LOGISTICS_TYPE",
      );
      // 加草帘
      if (orderVO.orderVehicle.openStrawCurtain && !orderCost3 && cost3) {
        orderVO.orderCostList.push({
          orderCostId: generateShortId(),
          costId: cost3.costId || "",
          name: cost3.name || "",
          price: orderVO.orderVehicle.strawCurtainPrice!,
          unit: cost3.unit || "元",
          count: 1,
          type: "LOGISTICS_TYPE",
          costItemIds: [],
          belong: cost3.belong,
          selected: true,
        });
      }

      const cost4 = costList?.find(
        (cost) => cost.name === "付瓜农定金" && cost.type === "PRODUCTION_TYPE",
      );
      const orderCost4 = orderVO?.orderCostList?.find(
        (cost) => cost.name === "付瓜农定金" && cost.type === "PRODUCTION_TYPE",
      );

      const calculator = new OrderCalculator(orderVO);
      const depositAmount = calculator.getDepositAmount();
      if (!orderCost4 && cost4 && depositAmount > 0) {
        orderVO.orderCostList.push({
          orderCostId: generateShortId(),
          costId: cost4.costId || "",
          name: cost4.name || "",
          price: depositAmount,
          unit: cost4.unit || "元",
          count: 1,
          type: "PRODUCTION_TYPE",
          costItemIds: [],
          belong: cost4.belong,
          selected: true,
        });
      }

      setOrderVO(orderVO);
    }
  };

  useEffect(() => {
    if (orderId && auditId && !isInitialized) {
      setLoading(true);
      init(orderId, auditId).then(() => {
        setIsInitialized(true);
        setLoading(false);
      });
    }
  }, []);

  if (!orderVO || !costList) {
    return;
  }

  const calculator = new OrderCalculator(orderVO);
  const personalProfit = calculator.getNetProfit();

  const sections = (
    orderVO.orderDealer.shortName === "信誉楼"
      ? xylSections
      : orderVO.type === "PRODUCTION_PURCHASE"
        ? defaultSections
        : defaultMarketSections
  )
    .map((sectionKey) => {
      const section = fullSections.find(
        (section) => section.name === sectionKey,
      );

      if (!section) {
        return false;
      }

      const orderDealer = orderVO.orderDealer;

      if (!orderDealer?.enableCompanyRebate && sectionKey === "taxSubsidy") {
        return false;
      }

      if (!orderDealer?.enableAccrualTax && sectionKey === "taxProvision") {
        return false;
      }

      if (!orderDealer?.shareAdjusted && sectionKey === "costDifference") {
        return false;
      }

      if (!orderDealer?.enableLoss && sectionKey === "productionLoss") {
        return false;
      }

      // 如果没有返点人这个模块，则不渲染
      if (!orderVO.orderRebate && sectionKey === "rebateCalc") {
        return false;
      }

      if (
        (!orderVO.orderPackageList || orderVO?.orderPackageList.length === 0) &&
        sectionKey === "emptyBoxInfo"
      ) {
        return false;
      }

      if (
        sectionKey === "purchaseForm" &&
        orderVO.orderDealer.shortName !== "信誉楼"
      ) {
        return false;
      }

      if (
        sectionKey === "deliveryForm" &&
        orderVO.orderDealer.shortName === "信誉楼"
      ) {
        return false;
      }

      return section;
    })
    .filter(Boolean);

  console.log("orderVO", orderVO);
  return (
    <>
      <View
        className={"overflow-x-hidden overflow-y-auto bg-[#D1D5DB]"}
        id={"purchase-order-audit"}
        onClick={() => {
          // 点击页面其他区域时收起导航菜单
          if (quickNavExpanded) {
            setQuickNavExpanded(false);
          }
        }}
      >
        <View className={"flex flex-col gap-2.5 p-2.5"}>
          {auditVO?.state === "AUDIT_REJECTED" && (
            <View className="flex flex-col gap-2 rounded-lg border-2 border-red-200 bg-red-50 p-3 shadow-sm">
              <View className="flex items-center gap-2">
                <Icon name="exclamation" color="red" size={16} />
                <View className="text-base font-bold text-red-700">
                  驳回原因
                </View>
              </View>
              <View className="pl-6 text-sm text-red-600">
                {auditVO?.auditReason || "暂无驳回原因"}
              </View>
            </View>
          )}
          {/* 顶部导航 */}
          <View className="relative flex flex-col gap-2.5 rounded-md bg-white p-2.5 shadow-sm">
            <View className={"flex flex-row justify-between gap-2.5"}>
              <View className="text-lg font-bold">
                {orderVO?.orderDealer?.shortName || "-"} 第
                {orderVO?.orderVehicle?.vehicleNo || "-"}车
              </View>

              {orderVO?.auditState && (
                <State
                  state={orderVO?.auditState}
                  stateMap={order.auditStateMap}
                />
              )}
            </View>
            <View className="text-neutral-darker text-sm font-medium">
              {orderVO?.orderVehicle.origin || "-"} 至{" "}
              {orderVO?.orderVehicle.destination || "-"}
            </View>

            {/* 展示产地负责人*/}
            <View className="flex flex-row items-center gap-2.5">
              <View className="flex-shrink-0 text-base font-bold text-gray-900">
                {orderVO.type === "PRODUCTION_PURCHASE"
                  ? "产地负责人"
                  : "市场负责人"}
              </View>

              <View
                className={`flex h-10 flex-1 items-center rounded-md border-4 border-gray-300`}
              >
                <Input
                  clearable
                  type="text"
                  disabled={
                    !(
                      orderVO.state === "AUDITING" &&
                      (orderVO.auditState === "PENDING_QUOTE_APPROVAL" ||
                        orderVO.auditState === "BOSS_REJECTED")
                    )
                  }
                  placeholder="请输入姓名"
                  value={originPrincipal || orderVO.createdByName}
                  onChange={(value) => setOriginPrincipal(value)}
                  onBlur={() => {
                    // 更新采购订单中的产地负责人
                    setOrderVO((prev) => ({
                      ...prev!,
                      originPrincipal: originPrincipal,
                    }));
                  }}
                  className="w-full bg-transparent"
                />
              </View>
            </View>
          </View>

          {/* 循环渲染各部分内容 */}
          {sections.map((section: any) => {
            return (
              <View
                key={section.name}
                id={`section-${section.name}`}
                className={"flex flex-col gap-2.5"}
              >
                <View className="text-sm font-bold">{section.title}</View>
                <View
                  className={`overflow-x-auto rounded-md rounded-b-lg bg-white p-2.5 shadow-sm`}
                >
                  <section.component
                    ref={(ref: SectionRef) => {
                      if (ref) {
                        sectionRefs.current[section.name] = ref;
                      }
                    }}
                    readOnly={
                      !(
                        orderVO.state === "AUDITING" &&
                        (orderVO.auditState === "PENDING_QUOTE_APPROVAL" ||
                          orderVO.auditState === "BOSS_REJECTED")
                      )
                    }
                    orderVO={orderVO}
                    onChange={(orderVO: BusinessAPI.OrderVO) => {
                      setOrderVO({
                        ...orderVO,
                        orderShipList: [convertOrderToOrderShip(orderVO)],
                      });
                    }}
                    // @ts-ignore
                    costList={costList}
                    calculator={calculator}
                  />
                </View>
              </View>
            );
          })}
        </View>
      </View>

      {/* 按钮操作 */}
      <View className={"sticky bottom-0 z-30 bg-white"}>
        {/* 个人利润固定栏 */}
        <View
          style={{
            background: "linear-gradient(100deg, #FFF2E8 25%, #FFE7D9 75%)",
          }}
        >
          <View className="flex items-center justify-between px-4 py-3">
            <View className="text-base font-bold text-gray-700">利润</View>
            <View
              className={classNames("text-2xl font-bold", {
                "text-primary": personalProfit > 0,
                "text-red-500": personalProfit < 0,
              })}
            >
              ￥ {personalProfit || "0"}
            </View>
          </View>
        </View>
        <View className="flex justify-between gap-2 border-t border-gray-200 p-2.5">
          {orderVO.state === "AUDITING" &&
          (orderVO.auditState === "PENDING_QUOTE_APPROVAL" ||
            orderVO.auditState === "BOSS_REJECTED") ? (
            <>
              <View className={"flex-1"}>
                <Button
                  block
                  type={"default"}
                  size={"large"}
                  onClick={() => setMoreActionVisible(true)}
                >
                  更多操作
                </Button>
              </View>

              {auditVO &&
                auditVO?.type === "REVIEWER_AUDIT" &&
                (auditVO.state === "WAITING_AUDIT" ||
                  auditVO.state === "AUDIT_REJECTED") && (
                  <View className={"flex-1"}>
                    <OrderRejectApprove
                      size={"large"}
                      auditVO={auditVO}
                      onFinish={() => {
                        Taro.navigateTo({
                          url: buildUrl("/pages/audit/pending"),
                        });
                      }}
                    />
                  </View>
                )}
              <View className={"flex-1"}>
                <Button
                  block
                  type={"primary"}
                  size={"large"}
                  className="bg-primary text-white"
                  onClick={handleSubmit}
                >
                  提交审批
                </Button>
              </View>
            </>
          ) : (
            <View className={"flex-1"}>
              <Button
                block
                type={"default"}
                size={"large"}
                onClick={() => {
                  Taro.redirectTo({ url: "/pages/main/index/index" });
                }}
              >
                返回首页
              </Button>
            </View>
          )}
        </View>
        <SafeArea position={"bottom"} />
      </View>

      {/* 暂存确认对话框 */}
      <Dialog
        visible={saveDialogVisible}
        title="确认暂存"
        content="确定要暂存当前采购订单吗？"
        onCancel={() => setSaveDialogVisible(false)}
        onConfirm={confirmSave}
      />

      {/* 计提费为0确认对话框 */}
      <Dialog
        visible={provisionZeroConfirmVisible}
        title="计提费确认"
        content="检测到计提费为0，请确认是否需要继续提交给老板审核？"
        confirmText={"确认并提交"}
        onCancel={cancelProvisionZeroSubmit}
        onConfirm={confirmProvisionZeroSubmit}
      />

      {/* 提交审核确认对话框 */}
      <Dialog
        visible={submitDialogVisible}
        title="提交审核"
        content="确定要提交给老板审核吗？"
        onCancel={() => setSubmitDialogVisible(false)}
        onConfirm={confirmSubmit}
      />

      {/* 更多操作ActionSheet */}
      <ActionSheet
        title="更多操作"
        visible={moreActionVisible}
        options={[
          {
            name: "暂存审核",
          },
          {
            name: "返回首页",
          },
        ]}
        onCancel={() => setMoreActionVisible(false)}
        onSelect={(item) => {
          setMoreActionVisible(false);
          if (item.name === "暂存审核") {
            // 暂存操作
            handleSave();
          } else if (item.name === "返回首页") {
            // 返回首页
            Taro.redirectTo({ url: "/pages/main/index/index" });
          }
        }}
        cancelText="取消"
      />

      {/* 快速导航目录 */}
      <View
        className={`fixed right-4 z-50 bg-white shadow-lg transition-all duration-300 ${
          quickNavExpanded ? "bottom-32 w-48" : "bottom-32 h-10 w-10"
        } rounded-lg`}
      >
        {/* 导航触发按钮 */}
        <View
          className="relative flex h-10 w-10 cursor-pointer items-center justify-center"
          onClick={() => setQuickNavExpanded(!quickNavExpanded)}
        >
          <Icon
            name="compass"
            className={`text-blue-600 transition-transform duration-300 ${
              quickNavExpanded ? "rotate-180" : ""
            }`}
          ></Icon>
        </View>

        {/* 展开的导航菜单 */}
        {quickNavExpanded && (
          <View
            className="absolute right-10 bottom-0 w-48 rounded-lg border border-gray-200 bg-white shadow-lg"
            onClick={(e) => e.stopPropagation()} // 防止事件冒泡
          >
            <View className="border-b border-gray-200 px-3 py-2">
              <View className="text-xs font-medium text-gray-700">
                快速导航
              </View>
            </View>
            <View className="max-h-96 overflow-y-auto">
              {sections.map((section: any) => (
                <View
                  key={section.name}
                  className="cursor-pointer border-b border-gray-100 px-3 py-2 text-sm text-gray-600 transition-colors last:border-b-0 hover:bg-blue-50 hover:text-blue-600"
                  onClick={() => {
                    scrollToSection(section.name);
                    setQuickNavExpanded(false); // 跳转后自动收起
                  }}
                >
                  {section.title}
                </View>
              ))}
            </View>
            {/* 收起按钮 */}
            <View
              className="text-neutral-darker cursor-pointer border-t border-gray-200 px-3 py-2 text-xs hover:bg-gray-50"
              onClick={() => setQuickNavExpanded(false)}
            >
              收起导航
            </View>
          </View>
        )}
      </View>
    </>
  );
});
