import { useEffect, useState } from "react";
import { DeliveryStep1Form, 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 default function DeliveryFormSection(props: {
  orderVO: BusinessAPI.OrderVO;
  onChange?: (orderDealer: BusinessAPI.OrderVO) => void;
  readOnly?: boolean;
}) {
  const { orderVO, onChange, readOnly } = 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] };
      }
      templateList.push(newModule);
    });

    return templateList;
  };

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

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

  if (!template) {
    return;
  }

  const moduleList = updateTemplateConfig(template, convertedData);

  console.log("moduleList", moduleList);
  console.log("orderShip", orderShip);

  return (
    <>
      <DeliveryStep1Form
        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>
    </>
  );
}
