import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from "react";
import {
  DeliveryStep1Form,
  DeliveryStep1FormRef,
  DeliveryStep2Preview,
  Icon,
} from "@/components";
import { convertOrderShipVOToExamplesFormat } from "@/utils";
import { business } from "@/services";
import { Button, Popup } from "@nutui/nutui-react-taro";
import { View } from "@tarojs/components";

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

export default forwardRef<
  DeliveryFormSectionRef,
  {
    orderVO: BusinessAPI.OrderVO;
    onChange?: (orderDealer: BusinessAPI.OrderVO) => void;
    readOnly?: boolean;
    costList: BusinessAPI.CostVO[];
  }
>((props, ref) => {
  const { orderVO, onChange, readOnly, costList } = props;
  const [template, setTemplate] = useState<any[]>([]);

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

  const orderShip = orderVO.orderShipList[0];

  const init = async (orderId: BusinessAPI.OrderVO["orderId"]) => {
    const { data } = await business.dealer.showDealer({
      dealerShowQry: {
        dealerId: orderId,
      },
    });

    if (data.data?.deliveryTemplate!) {
      const template = JSON.parse(data.data?.deliveryTemplate!);
      setTemplate(template);
    }
  };

  // 将 orderShipVO 转换为 examples 的数据格式，然后再替换 moduleList 里面的 config 数据
  const convertedData = convertOrderShipVOToExamplesFormat(orderVO);

  // 更新模板配置
  const updateTemplateConfig = (template: any[], data: any) => {
    let templateList: any[] = [];
    template?.map(async (module: any) => {
      let newModule = { ...module };
      if (data[module.type]) {
        newModule.config = { ...module.config, ...data[module.type] };
      }
      // 特殊处理： otherFees 要更新为最新的数据
      if (module.type === "otherFees") {
        newModule = {
          ...module,
          config: {
            ...module.config,
            feeItems: orderVO.orderCostList,
            feeLabels: costList?.reduce((acc: any, item: any) => {
              acc[item.costId] = item.name;
              return acc;
            }, {}),
          },
          schemas: [
            {
              title: "显示配置",
              valueType: "group",
              columns: [
                {
                  dataIndex: "feeItems",
                  title: "显示费用项目",
                  valueType: "checkbox",
                  valueEnum: costList?.reduce((acc: any, item: any) => {
                    acc[item.itemId] = item.name;
                    return acc;
                  }, {}),
                },
              ],
            },
          ],
        };
      }
      templateList.push(newModule);
    });

    return templateList;
  };

  useEffect(() => {
    if (orderVO.orderDealer.dealerId) {
      init(orderVO.orderDealer.dealerId);
    }
  }, [orderVO.orderDealer.dealerId]);

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

  const step1FormRef = useRef<DeliveryStep1FormRef>(null);

  // 暴露 validateForm 方法
  useImperativeHandle(ref, () => ({
    validateForm: () => {
      // 调用 step1FormRef 的 validateForm 方法
      if (step1FormRef.current && step1FormRef.current.validateForm) {
        if (!step1FormRef.current.validateForm()) {
          return "发货单复核填写错误";
        }
      }
      return null;
    },
  }));

  if (!template) {
    return;
  }

  const moduleList = updateTemplateConfig(template, convertedData);

  return (
    <>
      <DeliveryStep1Form
        ref={step1FormRef}
        readOnly={readOnly}
        moduleList={moduleList}
        orderShip={orderShip}
        setOrderShip={(orderShip) => {
          onChange?.({
            ...orderVO,
            orderShipList: [orderShip],
          });
        }}
      />

      {/* 预览发货单 */}
      <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"}>
          <DeliveryStep2Preview moduleList={moduleList} />
        </View>
      </Popup>
    </>
  );
});
