import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import { DeliveryStep1Form, DeliveryStep2Preview } from "@/components";
import {
  convertPurchaseOrderToShipOrder,
  convertShipOrderVOToExamplesFormat,
} from "@/utils";
import { business } from "@/services";
import { Popup } from "@nutui/nutui-react-taro";
import { View } from "@tarojs/components";

export interface DeliveryFormSectionRef {
  handlePreview: () => void;
}

export default forwardRef<
  DeliveryFormSectionRef,
  {
    purchaseOrderVO: BusinessAPI.PurchaseOrderVO;
    onChange?: (orderDealer: BusinessAPI.PurchaseOrderVO) => void;
    readOnly?: boolean;
  }
>((props, ref) => {
  const { purchaseOrderVO, onChange, readOnly } = props;
  const [moduleList, setModuleList] = useState<any[]>([]);

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

  const orderShip = convertPurchaseOrderToShipOrder(purchaseOrderVO);

  const init = async (purchaseOrderVO: BusinessAPI.PurchaseOrderVO) => {
    const { data } = await business.dealer.showDealer({
      dealerShowQry: {
        dealerId: purchaseOrderVO.orderDealer.dealerId,
      },
    });

    if (data.data?.deliveryTemplate!) {
      const template = JSON.parse(data.data?.deliveryTemplate!);
      // 将 shipOrderVO 转换为 examples 的数据格式，然后再替换 moduleList 里面的 config 数据
      const convertedData = convertShipOrderVOToExamplesFormat(
        purchaseOrderVO,
        orderShip,
      );
      const updatedTemplate = await updateTemplateConfig(
        template,
        convertedData,
      );
      setModuleList(updatedTemplate);
    } else {
      setModuleList([]);
    }
  };

  // 更新模板配置
  const updateTemplateConfig = async (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] };
      }
      templateList.push(newModule);
    });

    return templateList;
  };

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

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

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    handlePreview,
  }));

  if (!orderShip) {
    return;
  }

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

      {/* 预览发货单 */}
      <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>
    </>
  );
});
