import { useMemo, useRef, useState } from "react";
import { Table } from "@nutui/nutui-react-taro";
import { Icon } from "@/components";
import { Input, View } from "@tarojs/components";
import { Decimal } from "decimal.js";

export default function PackageInfoSection(props: {
  orderVO: BusinessAPI.OrderVO;
  onChange?: (orderVO: BusinessAPI.OrderVO) => void;
  readOnly?: boolean;
}) {
  const { orderVO, readOnly, onChange } = props;

  const inputRefs = useRef<Record<string, any>>({});

  // 管理编辑状态: key 为分组键,值为输入值
  const [editingStates, setEditingStates] = useState<
    Record<string, { isEditing: boolean; inputValue: string }>
  >({});
  // 开始编辑
  const startEdit = (key: string, currentValue: number) => {
    const inputValue = currentValue === 0 ? "" : currentValue.toString();
    setEditingStates((prev) => ({
      ...prev,
      [key]: { isEditing: true, inputValue },
    }));

    // 聚焦输入框
    setTimeout(() => {
      if (inputRefs.current[key]) {
        inputRefs.current[key].focus();
      }
    }, 0);
  };

  // 处理输入变化
  const handleInputChange = (key: string, e: any) => {
    const val = e.detail?.value || e.target?.value || "";
    // 只允许数字和小数点
    if (/^\d*\.?\d*$/.test(val) || val === "") {
      setEditingStates((prev) => ({
        ...prev,
        [key]: { ...prev[key], inputValue: val },
      }));
    }
  };

  // 保存编辑
  const saveEdit = (key: string) => {
    const state = editingStates[key];
    if (!state) return;

    let newValue = 0;
    if (state.inputValue !== "" && !Number.isNaN(Number(state.inputValue))) {
      newValue = Number(state.inputValue);
    }

    // 更新 orderVO 中的数据
    const updatedOrderVO = { ...orderVO };
    updatedOrderVO.orderSupplierList?.forEach((supplier) => {
      supplier.orderPackageList?.forEach((pkg) => {
        const pkgKey = `${pkg.boxBrandId}-${pkg.boxProductId}-${pkg.boxSpecId}`;
        if (pkgKey === key) {
          pkg.boxSalePrice = newValue;
        }
      });
    });

    // 触发 onChange 回调
    onChange?.(updatedOrderVO);

    // 退出编辑状态
    setEditingStates((prev) => {
      const newState = { ...prev };
      delete newState[key];
      return newState;
    });
  };

  // 取消编辑
  const cancelEdit = (key: string) => {
    setEditingStates((prev) => {
      const newState = { ...prev };
      delete newState[key];
      return newState;
    });
  };

  const columns = useMemo(() => {
    return [
      {
        title: "纸箱型号",
        key: "boxProductName",
        fixed: "left",
      },
      {
        title: "个数",
        key: "boxProductCount",
      },
      ...(orderVO.type === "PRODUCTION_PURCHASE"
        ? [
            {
              title: "销售单价（元/斤）",
              key: "boxSalePrice",
              render: (
                value: BusinessAPI.OrderPackage & {
                  orderPackageId?: string;
                  isTotalRow?: boolean;
                },
              ) => {
                // 合计行不显示编辑按钮
                if (value.isTotalRow) {
                  return value.boxSalePrice as number;
                }

                // 生成分组键
                const key = `${value.boxBrandId}-${value.boxProductId}-${value.boxSpecId}`;
                const editingState = editingStates[key];
                const isEditing = editingState?.isEditing || false;

                if (isEditing) {
                  return (
                    <View className="flex items-center">
                      <Input
                        ref={(el: any) => {
                          inputRefs.current[key] = el;
                        }}
                        type="digit"
                        value={editingState.inputValue}
                        onInput={(e) => handleInputChange(key, e)}
                        onBlur={() => saveEdit(key)}
                        className="flex-1 border-b border-blue-500 px-1"
                        style={{ minWidth: "80px" }}
                        onClick={(e) => e.stopPropagation()}
                      />
                      <View
                        className="ml-1 cursor-pointer"
                        onClick={(e) => {
                          e.stopPropagation();
                          cancelEdit(key);
                        }}
                      >
                        <Icon name="circle-xmark" size={16} color={"#ef4444"} />
                      </View>
                    </View>
                  );
                }

                return (
                  <View
                    className="flex items-center justify-between"
                    onClick={(e) => {
                      if (!readOnly) {
                        e.stopPropagation();
                        startEdit(key, value.boxSalePrice as number);
                      }
                    }}
                  >
                    <View
                      className={!readOnly ? "cursor-pointer underline" : ""}
                    >
                      {value.boxSalePrice as number}
                    </View>
                    {!readOnly && (
                      <View className="-m-2 ml-2 flex items-center justify-center p-2">
                        <Icon
                          name={"pen-to-square"}
                          size={16}
                          color={"#1a73e8"}
                        />
                      </View>
                    )}
                  </View>
                );
              },
            },
            {
              title: "销售金额（元）",
              key: "boxSalePayment",
            },
          ]
        : []),
      {
        title: "箱重（斤）",
        key: "boxProductWeight",
        render: (
          value: BusinessAPI.OrderPackage & {
            orderPackageId?: string;
            isTotalRow?: boolean;
          },
        ) => value.boxProductWeight,
      },
      {
        title: "品牌",
        key: "boxBrandName",
      },
    ];
  }, [readOnly, editingStates]);

  // 将所有包装信息合并并按品牌、型号、规格分组
  const groupedPackageData = orderVO.orderSupplierList?.reduce(
    (acc, supplier) => {
      supplier.orderPackageList
        ?.filter((pkg) => pkg.boxType === "USED")
        ?.forEach((pkg) => {
          // 生成分组键
          const key = `${pkg.boxBrandId}-${pkg.boxProductId}-${pkg.boxSpecId}`;

          // 转换规格字段
          const boxSpecId = pkg.boxSpecId;
          const boxSpecName = pkg.boxSpecName;

          if (!acc[key]) {
            acc[key] = {
              ...pkg,
              boxSpecId,
              boxSpecName,
              boxProductCount: 0,
            };
          }

          // 累加数量
          acc[key].boxProductCount += pkg.boxCount || 0;
        });

      return acc;
    },
    {} as Record<string, any>,
  );

  // 转换为数组格式
  const packageData = Object.values(groupedPackageData || {});

  // 计算合计数据
  const calculateTotals = () => {
    if (!packageData || packageData.length === 0) {
      return {};
    }

    // 计算各项合计
    let totalBoxProductCount = new Decimal(0);
    let totalBoxSalePayment = new Decimal(0);
    let totalBoxProductWeight = new Decimal(0);

    packageData.forEach((pkg: any) => {
      totalBoxProductCount = totalBoxProductCount.add(pkg.boxProductCount || 0);
      totalBoxSalePayment = totalBoxSalePayment.add(
        new Decimal(pkg?.boxSalePrice || 0)
          .mul(pkg.boxProductCount || 0)
          .toDecimalPlaces(0, Decimal.ROUND_HALF_UP),
      );
      totalBoxProductWeight = totalBoxProductWeight.add(
        new Decimal(pkg?.boxProductWeight || 0)
          .mul(pkg.boxProductCount || 0)
          .toDecimalPlaces(0, Decimal.ROUND_HALF_UP),
      );
    });

    return {
      boxProductName: "合计",
      boxProductCount: totalBoxProductCount.toNumber(),
      boxSalePayment: totalBoxSalePayment.toNumber(),
      boxProductWeight: totalBoxProductWeight.toNumber(),
      isTotalRow: true, // 标记这是合计行
    };
  };

  const totalsData = calculateTotals();

  // 创建包含合计行的数据
  const dataWithTotals = [...packageData];
  if (Object.keys(totalsData).length > 0) {
    dataWithTotals.push(totalsData);
  }

  // 自定义列配置，对合计行特殊处理
  const columnsWithTotalsRender = columns.map((column) => {
    if (column.key === "boxProductName") {
      // 品牌列显示"合计"
      return {
        ...column,
        render: (rowData: any) => {
          if (rowData.isTotalRow) {
            return (
              <span style={{ fontWeight: "bold" }}>
                {rowData.boxProductName}
              </span>
            );
          }
          return rowData.boxProductName;
        },
      };
    } else if (column.key === "boxProductCount") {
      // 个数列显示合计
      return {
        ...column,
        render: (rowData: any) => {
          if (rowData.isTotalRow) {
            return (
              <span style={{ fontWeight: "bold" }}>
                {rowData.boxProductCount}
              </span>
            );
          }
          return rowData.boxProductCount;
        },
      };
    } else if (column.key === "boxSalePrice") {
      // 销售单价列合计行处理
      return {
        ...column,
        render: (rowData: any) => {
          if (rowData.isTotalRow) {
            return (
              <span style={{ fontWeight: "bold" }}>
                {rowData.boxSalePrice as number}
              </span>
            );
          }
          return column?.render?.(rowData);
        },
      };
    } else if (column.key === "boxSalePayment") {
      // 销售金额列显示合计
      return {
        ...column,
        render: (rowData: any) => {
          if (rowData.isTotalRow) {
            return (
              <span style={{ fontWeight: "bold" }}>
                {rowData.boxSalePayment}
              </span>
            );
          }
          return new Decimal(rowData?.boxSalePrice || 0)
            .mul(rowData.boxProductCount)
            .toDecimalPlaces(0, Decimal.ROUND_HALF_UP)
            .toNumber();
        },
      };
    } else if (column.key === "boxProductWeight") {
      // 重量列合计行处理
      return {
        ...column,
        render: (rowData: any) => {
          if (rowData.isTotalRow) {
            return (
              <span style={{ fontWeight: "bold" }}>
                {rowData.boxProductWeight}
              </span>
            );
          }
          return column?.render?.(rowData);
        },
      };
    }

    // 其他列保持原有render函数或者默认显示
    return column;
  });

  return (
    <Table
      className={"table-sum"}
      columns={columnsWithTotalsRender as any}
      data={dataWithTotals}
      striped
    />
  );
}
