import { Text, View } from "@tarojs/components";
import { OrderCalculator, ProfitTableRow } from "@/utils";
import { Icon, ImagePreview, PriceEditor } from "@/components";
import { Button, Popup } from "@nutui/nutui-react-taro";
import { useState } from "react";
import dayjs from "dayjs";
import { business } from "@/services";
import { ProfitCalculationService } from "@/utils/classes/calculators";

export function CostDifferenceSection(props: {
  orderVO: BusinessAPI.OrderVO;
  onChange?: (orderVO: BusinessAPI.OrderVO) => void;
  readOnly?: boolean;
  calculator: OrderCalculator;
}) {
  const { orderVO, onChange, readOnly, calculator } = props;
  const orderDealer = orderVO.orderDealer;

  const [previewVisible, setPreviewVisible] = useState(false);

  // 获取当前月份
  const currentMonth = dayjs(orderVO.orderVehicle.deliveryTime).format(
    "YYYY-MM-01",
  );
  const [profitData, setProfitData] = useState<ProfitTableRow[]>([]);

  const init = async (currentMonth: string) => {
    // 查询本月的所有订单数据
    let {
      data: { data: orderVOList = [] },
    } = await business.order.listOrder({
      orderListQry: {
        dealerId: orderVO.orderDealer.dealerId,
        month: currentMonth,
        state: "COMPLETED", // 只查询已完成的订单
      },
    });

    orderVOList.push(orderVO);
    // 获取当前车次
    const currentVehicleNo = orderVO.orderVehicle.vehicleNo;

    // 筛选截止到当前车次之前的数据
    const profitData: ProfitTableRow[] = [];
    let includeNext = true;

    // orderVOList 根据车次正序
    orderVOList.sort((a, b) => {
      return (
        Number(a.orderVehicle.vehicleNo) - Number(b.orderVehicle?.vehicleNo)
      );
    });

    for (const order of orderVOList) {
      // 如果还没有到达当前车次，继续
      if (includeNext) {
        const profitRow = ProfitCalculationService.calculateOrderProfit(order);
        profitData.push(profitRow);

        // 如果是当前车次，停止添加
        if (order.orderVehicle.vehicleNo === currentVehicleNo) {
          includeNext = false;
        }
      }
    }

    setProfitData(profitData);
  };

  // 预览发货单操作
  const handlePreview = () => {
    init(currentMonth);
    setPreviewVisible(true);
  };

  // 计算合计
  const totalOriginCost = profitData.reduce(
    (sum, row) => sum + row.originCost,
    0,
  );
  const totalQuoteAmount = profitData.reduce(
    (sum, row) => sum + row.quoteAmount,
    0,
  );
  const totalProfit = profitData.reduce((sum, row) => sum + row.profit, 0);

  return (
    <View className={"flex flex-col gap-2.5"}>
      {/* 卡片形式展示分成信息 */}
      <View className="bg-primary/3 rounded-lg border-b border-gray-100 p-2.5">
        <View className="mb-2">
          <Text className="text-sm font-medium">待分红金额</Text>
        </View>

        <View className="flex">
          <PriceEditor
            value={
              orderDealer.costDifference === null ||
              orderDealer.costDifference === undefined
                ? calculator.getCostDifference()
                : orderDealer.costDifference
            }
            onSave={(newValue) => {
              onChange?.({
                ...orderVO,
                orderDealer: {
                  ...orderDealer,
                  costDifference: newValue,
                  profitSharing: calculator.getShareProfit(),
                },
              });
            }}
            readOnly={readOnly}
            label={"调整的金额"}
            unit="元"
            hint="点击金额可直接编辑"
            negative
          />

          <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>
            </View>
            <View className="flex items-center justify-between">
              <Text className="text-primary text-2xl font-bold text-nowrap">
                ￥ {calculator.getShareProfit() || 0}
              </Text>
            </View>
          </View>
        </View>
      </View>

      {/* 预览利润表 */}
      <View className={"flex-1"}>
        <Button
          icon={<Icon name="eye" size={18} />}
          size={"large"}
          type="primary"
          fill="outline"
          block
          onClick={handlePreview}
        >
          预览利润表
        </Button>
      </View>

      {/* 预览发货单 */}
      <Popup
        duration={150}
        style={{
          minHeight: "auto",
        }}
        className={"!bg-[#D1D5DB]"}
        visible={previewVisible}
        position="bottom"
        onClose={() => {
          setPreviewVisible(false);
        }}
        closeable
        destroyOnClose
        title={"预览利润单"}
      >
        <View className={"overflow-hidden p-2.5"}>
          <ImagePreview>
            <View className="table-border">
              <View className="table-title flex items-end justify-center text-base">
                诚信志远利润明细
              </View>
              <View className={"grid w-full grid-cols-5 gap-0 text-base"}>
                <View className={"col-span-1 flex items-end justify-center"}>
                  车次
                </View>
                <View className={"col-span-1 flex items-end justify-center"}>
                  发货日期
                </View>
                <View className={"col-span-1 flex items-end justify-center"}>
                  产地成本
                </View>
                <View className={"col-span-1 flex items-end justify-center"}>
                  报价金额
                </View>
                <View className={"col-span-1 flex items-end justify-center"}>
                  利润
                </View>
              </View>

              {profitData.map((row, index) => (
                <View
                  className={"grid w-full grid-cols-5 gap-0 text-base"}
                  key={index}
                >
                  <View className={"col-span-1 flex items-end justify-center"}>
                    {row.vehicleNo}
                  </View>
                  <View className={"col-span-1 flex items-end justify-center"}>
                    {row.shippingDate}
                  </View>
                  <View className={"col-span-1 flex items-end justify-center"}>
                    {row.originCost}
                  </View>
                  <View className={"col-span-1 flex items-end justify-center"}>
                    {row.quoteAmount}
                  </View>
                  <View className={"col-span-1 flex items-end justify-center"}>
                    {row.profit.toFixed(2)}
                  </View>
                </View>
              ))}
              <View className={"grid w-full grid-cols-5 gap-0 text-base"}>
                <View
                  className={
                    "col-span-2 flex items-end justify-center bg-yellow-500"
                  }
                >
                  {dayjs(currentMonth).format("MMMM")}合计
                </View>
                <View className={"col-span-1 flex items-end justify-center"}>
                  {totalOriginCost.toFixed(2)}
                </View>
                <View className={"col-span-1 flex items-end justify-center"}>
                  {totalQuoteAmount.toFixed(2)}
                </View>
                <View className={"col-span-1 flex items-end justify-center"}>
                  {totalProfit.toFixed(2)}
                </View>
              </View>
            </View>
          </ImagePreview>
        </View>
      </Popup>
    </View>
  );
}
