import { Text, View } from "@tarojs/components";
import { Radio } from "@nutui/nutui-react-taro";
import { OrderCalculator } from "@/utils";
import { Icon, PriceEditor } from "@/components";
import classNames from "classnames";
import { forwardRef, useImperativeHandle } from "react";

export interface MarketPriceSectionRef {
  validateForm: () => string | null;
}

export default forwardRef<
  MarketPriceSectionRef,
  {
    orderVO: BusinessAPI.OrderVO;
    onChange?: (orderVO: BusinessAPI.OrderVO) => void;
    readOnly?: boolean;
    calculator: OrderCalculator;
  }
>((props, ref) => {
  const { orderVO, onChange, readOnly, calculator } = props;

  // 暴露 validateForm 方法
  useImperativeHandle(ref, () => ({
    validateForm: () => {
      // 校验报价方式
      if (!orderVO?.pricingMethod) {
        return "请选择市场报价的报价方式";
      }

      // 校验销售单价
      for (const supplier of orderVO.orderSupplierList || []) {
        if (!supplier.salePrice || supplier.salePrice <= 0) {
          return `请填写${supplier.name}的销售单价`;
        }
      }

      return null;
    },
  }));

  // 销售金额
  const saleAmount = calculator.getSalesAmount();

  // 市场报价
  const marketPrice = calculator.getMarketPrice();

  // 计算平均单价（所有供应商单价的平均值）
  const averagePurchasePrice = calculator.getAverageSalesPrice();

  return (
    <>
      <View className="flex flex-col gap-2.5">
        <View className="flex !h-8 flex-row items-center justify-between">
          <View className="text-neutral-dark flex flex-shrink-0 flex-row text-sm">
            <Icon name="chart-line" size={16} className="mr-1" />
            报价方式
          </View>
          <View className="text-neutral-darkest text-sm font-medium">
            {readOnly ? (
              <View>
                {orderVO.pricingMethod === "BY_GROSS_WEIGHT"
                  ? "按毛重报价"
                  : orderVO.pricingMethod === "BY_NET_WEIGHT"
                    ? "按净重报价"
                    : "未选择"}
              </View>
            ) : (
              <Radio.Group
                direction={"horizontal"}
                //@ts-ignore
                value={orderVO.pricingMethod}
                onChange={(value) =>
                  onChange?.({
                    ...orderVO,
                    pricingMethod:
                      value as BusinessAPI.OrderVO["pricingMethod"],
                  })
                }
              >
                <Radio value="BY_GROSS_WEIGHT">按毛重报价</Radio>
                <Radio value="BY_NET_WEIGHT">按净重报价</Radio>
              </Radio.Group>
            )}
          </View>
        </View>

        {/* 卡片形式展示供应商报价信息 */}
        {orderVO.orderSupplierList?.map((supplier, index) => {
          return (
            <View
              key={supplier.orderSupplierId}
              className="bg-primary/3 rounded-lg border-b border-gray-100 p-2.5"
            >
              <View className="mb-2 flex flex-row items-center justify-between">
                <Text className="text-sm font-medium">
                  {`${supplier.type === "FARMER" ? "瓜农" : "档口"} ${index + 1} （${supplier.name}）${supplier.productName}`}
                </Text>
                {supplier.type === "STALL" && (
                  <View
                    className={classNames(
                      "flex items-center justify-center rounded-full px-3 py-1 shadow-sm",
                    )}
                    style={{
                      backgroundColor: "#CBF0D9",
                      boxShadow: `0 0 0 1px #CBF0D920, 0 1px 3px 0 #CBF0D930`,
                    }}
                  >
                    <Text
                      className="text-xs font-medium"
                      style={{ color: "#00BEA9" }}
                    >
                      自家档口
                    </Text>
                  </View>
                )}
                {supplier.type === "OTHER_STALL" && (
                  <View
                    className={classNames(
                      "flex items-center justify-center rounded-full px-3 py-1 shadow-sm",
                    )}
                    style={{
                      backgroundColor: "#FDC6AA",
                      boxShadow: `0 0 0 1px #FDC6AA20, 0 1px 3px 0 #FDC6AA30`,
                    }}
                  >
                    <Text
                      className="text-xs font-medium"
                      style={{ color: "#D16731" }}
                    >
                      其他家档口
                    </Text>
                  </View>
                )}
              </View>

              <View className="flex flex-1">
                <PriceEditor
                  value={supplier.salePrice || 0}
                  onSave={(newValue) => {
                    onChange?.({
                      ...orderVO,
                      orderSupplierList: orderVO.orderSupplierList.map(
                        (item) => {
                          if (
                            item.orderSupplierId === supplier.orderSupplierId
                          ) {
                            return {
                              ...item,
                              salePrice: newValue,
                            };
                          }
                          return item;
                        },
                      ),
                    });
                  }}
                  readOnly={readOnly}
                />

                <View className="flex flex-1 flex-col gap-2 pl-4">
                  <View className="flex items-center justify-between">
                    <Text className="text-sm text-gray-500">毛重</Text>
                    <Text className="text-sm font-medium">
                      {supplier.grossWeight || 0} 斤
                    </Text>
                  </View>
                  <View className="flex items-center justify-between">
                    <Text className="text-sm text-gray-500">净重</Text>
                    <Text className="text-sm font-medium">
                      {supplier.netWeight || 0} 斤
                    </Text>
                  </View>
                  <View className="flex items-center justify-between">
                    <Text className="text-sm text-gray-500">箱重</Text>
                    <Text className="text-sm font-medium">
                      {calculator
                        .getSupplierCalculator(supplier)
                        .getBoxWeight()}{" "}
                      斤
                    </Text>
                  </View>
                  {/* 是否包纸箱 */}
                  {supplier.type === "FARMER" && (
                    <View className="flex items-center justify-between">
                      <Text className="text-sm text-gray-500">包纸箱</Text>
                      <Text className="text-sm font-medium">
                        {supplier.pricingMethod === "BY_GROSS_WEIGHT"
                          ? "包"
                          : "不包"}
                      </Text>
                    </View>
                  )}
                  {supplier.type === "STALL" && (
                    <View className="flex items-center justify-between">
                      <Text className="text-sm text-gray-500">采购报价</Text>
                      <Text className="text-sm font-medium">
                        {supplier.pricingMethod === "BY_GROSS_WEIGHT"
                          ? "毛重"
                          : "净重"}
                      </Text>
                    </View>
                  )}
                  <View className="flex items-center justify-between">
                    <Text className="text-sm text-gray-500">采购成本</Text>
                    <Text className="text-sm font-medium">
                      {supplier.invoiceAmount} 元
                    </Text>
                  </View>
                  <View className="flex items-center justify-between">
                    <Text className="text-sm text-gray-500">采购单价</Text>
                    <Text className="text-sm font-medium">
                      {supplier.purchasePrice} 元/斤
                    </Text>
                  </View>
                  {supplier.isDepositPaid && (
                    <View className="flex items-center justify-between">
                      <Text className="text-sm text-red-500">定金金额</Text>
                      <Text className="text-sm font-medium text-red-500">
                        {calculator.getDepositAmount()} 元
                      </Text>
                    </View>
                  )}
                  <View className="flex items-center justify-between">
                    <Text className="text-sm text-gray-500">销售金额</Text>
                    <Text className="text-sm font-medium">
                      {orderVO.pricingMethod
                        ? `${calculator.calculateSupplierAmount(supplier)} 元`
                        : "-"}
                    </Text>
                  </View>
                </View>
              </View>
            </View>
          );
        })}

        <View className="flex !h-8 flex-row items-center justify-between">
          <View className="text-neutral-dark flex flex-shrink-0 flex-row text-sm">
            <Icon name="money-bill" size={16} className="mr-1" />
            销售金额
          </View>
          <View className="text-neutral-darkest text-sm font-medium">
            {orderVO.pricingMethod ? `${saleAmount} 元` : "-"}
          </View>
        </View>
        <View className="flex !h-8 flex-row items-center justify-between">
          <View className="text-neutral-dark flex flex-shrink-0 flex-row text-sm">
            <Icon name="chart-bar" size={16} className="mr-1" />
            平均单价
          </View>
          <View className="text-neutral-darkest text-sm font-medium">
            {orderVO.pricingMethod ? `${averagePurchasePrice} 元/斤` : "-"}
          </View>
        </View>
        <View className="flex !h-8 flex-row items-center justify-between bg-yellow-200">
          <View className="text-neutral-dark flex flex-shrink-0 flex-row text-sm">
            <Icon name="chart-line" size={16} className="mr-1" />
            市场报价（
            {orderVO.orderDealer?.includePackingFlag
              ? "销售金额 + 包装费"
              : "销售金额"}
            ）
          </View>
          <View className="text-neutral-darkest text-sm font-medium">
            {orderVO.pricingMethod ? `${marketPrice} 元` : "-"}
          </View>
        </View>
      </View>
    </>
  );
});
