var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/appointmentBooking/components/ConfirmInformation/index.tsx
var ConfirmInformation_exports = {};
__export(ConfirmInformation_exports, {
  default: () => ConfirmInformation_default
});
module.exports = __toCommonJS(ConfirmInformation_exports);
var import_react = __toESM(require("react"));
var import_utils = require("@pisell/utils");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_context = require("../../context");
var import_hooks = require("../../hooks");
var import_Item = __toESM(require("../Cart/Item"));
var import_utils2 = require("../../utils");
var import_utils3 = require("./utils");
var import_index = require("./index.less");
var import_ContactInfoContent = __toESM(require("../../../../plus/contactInfoModal/ContactInfoContent"));
var import_antd = require("antd");
var import_useLoginUser = __toESM(require("../../../../hooks/useLoginUser"));
var ConfirmInformation = (0, import_react.forwardRef)((props, ref) => {
  var _a, _b;
  const hasSubscribedRef = (0, import_react.useRef)(false);
  const context = (0, import_useEngineContext.default)();
  const config = ((_b = (_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.constants) == null ? void 0 : _b.config) || {};
  const utils = (0, import_hooks.contextUtils)();
  const { pubsub } = context.appHelper.utils;
  const { appointmentBooking, summary, isAgreeDepositPolicy, setLoading } = (0, import_context.useAppointmentBookingContext)();
  const { isRetailTemplate, bookingSetting } = (0, import_hooks.useAppointmentBookingSetting)();
  console.log(bookingSetting, "bookingSetting");
  const [form] = import_antd.Form.useForm();
  const userInfo = (0, import_useLoginUser.default)();
  const getContactsInfo = async () => {
    var _a2;
    let contacts_info = null;
    try {
      const res = await ((_a2 = appointmentBooking == null ? void 0 : appointmentBooking.getContactInfo) == null ? void 0 : _a2.call(appointmentBooking, {
        key: "contacts_info"
      }));
      if ((res == null ? void 0 : res.code) == 200 && (res == null ? void 0 : res.data)) {
        contacts_info = res == null ? void 0 : res.data;
      }
    } catch (error) {
      console.log("error", error);
      contacts_info = null;
    }
    const transfromCountryCallingCode = (code) => {
      if (!code) {
        return "";
      }
      return (code == null ? void 0 : code.startsWith("+")) ? code : `+${code}`;
    };
    if (contacts_info) {
      const { first_name, last_name, phone, email } = contacts_info || {};
      form.setFieldsValue({
        first_name,
        last_name,
        phone: {
          phone: phone == null ? void 0 : phone.phone,
          countryCallingCode: transfromCountryCallingCode(
            phone == null ? void 0 : phone.country_calling_code
          ),
          countryCode: phone == null ? void 0 : phone.country_code
        },
        email
      });
    } else {
      console.log("userInfo", userInfo);
      const {
        first_name,
        last_name,
        phone,
        email,
        country_calling_code,
        country_code
      } = userInfo || {};
      form.setFieldsValue({
        first_name,
        last_name,
        phone: {
          phone,
          countryCallingCode: transfromCountryCallingCode(country_calling_code),
          countryCode: country_code
        },
        email
      });
    }
  };
  (0, import_react.useEffect)(() => {
    getContactsInfo();
  }, []);
  const goPaymentFinish = (order_id, amount) => {
    var _a2;
    const url = `/payment-finish/success?order_id=${order_id}&amount=${Number(
      amount
    )}`;
    (_a2 = utils == null ? void 0 : utils.history) == null ? void 0 : _a2.replace(url);
    setLoading(false);
  };
  (0, import_react.useEffect)(() => {
    if (isRetailTemplate) {
      handleForm(false);
    }
  }, [isRetailTemplate]);
  const handleForm = async (isSubmit, extraData) => {
    var _a2;
    const carts = await appointmentBooking.getCart();
    const key = "isRetailFormSubmit";
    const isRetailFormSubmit = appointmentBooking.getOtherData(key);
    const callback = () => {
      if (isSubmit) {
        onCheckout(extraData);
      }
    };
    if (isRetailFormSubmit) {
      return callback();
    }
    const params = (0, import_utils3.getFormParams)(carts);
    (_a2 = utils == null ? void 0 : utils.action) == null ? void 0 : _a2.call(utils, {
      type: "pisell1.goProductForm",
      data: params,
      callback: async (e) => {
        var _a3;
        if ((e == null ? void 0 : e.type) !== "close") {
          await appointmentBooking.updateCart({
            _id: (_a3 = carts == null ? void 0 : carts[0]) == null ? void 0 : _a3._id,
            relationForms: e
          });
          appointmentBooking.setOtherData(key, true);
          callback();
        }
        setLoading(false);
      }
    });
  };
  const handleNext = async (extraData) => {
    var _a2;
    const { deposit } = summary;
    if ((deposit == null ? void 0 : deposit.hasDeposit) && ((_a2 = deposit == null ? void 0 : deposit.protocols) == null ? void 0 : _a2.length) > 0 && !isAgreeDepositPolicy) {
      return (0, import_utils2.Toast)(import_utils.locales.getText("pisell2.appointment.deposit.agree.policy"));
    }
    setLoading(true);
    if (isRetailTemplate) {
      handleForm(true, extraData);
      return;
    }
    onCheckout(extraData);
  };
  const onCheckout = async (extraData) => {
    try {
      const { deposit } = summary;
      const { data } = await appointmentBooking.submitOrder(extraData);
      const { is_deposit, deposit_amount, total_amount, order_id } = data || {};
      const _total = is_deposit ? deposit_amount : total_amount;
      if (_total > 0) {
        utils.action({
          type: "pisell1.payment",
          data: { ...data, total_amount: _total },
          callback: (e) => {
          }
        });
        setTimeout(() => {
          setLoading(false);
        }, 200);
      } else {
        if (deposit == null ? void 0 : deposit.hasDeposit) {
          goPaymentFinish(order_id, _total);
          return;
        }
        const freeResult = await appointmentBooking.getFreeProduct(order_id);
        console.log(freeResult, "freeResult");
        if (freeResult == null ? void 0 : freeResult.status) {
          goPaymentFinish(order_id, total_amount);
        } else {
          (0, import_utils2.Toast)(freeResult == null ? void 0 : freeResult.message);
        }
      }
    } catch (error) {
      (0, import_utils2.Toast)((error == null ? void 0 : error.message) || "");
      setTimeout(() => {
        setLoading(false);
      }, 50);
    }
  };
  const handleSubmit = async () => {
    var _a2, _b2, _c, _d, _e, _f, _g;
    if ((_b2 = (_a2 = utils == null ? void 0 : utils.businessUtils) == null ? void 0 : _a2.isGuestUser) == null ? void 0 : _b2.call(_a2)) {
      if (!hasSubscribedRef.current) {
        pubsub.subscribe("bind.guest.user", handleNext);
        hasSubscribedRef.current = true;
      }
      (_d = (_c = utils == null ? void 0 : utils.businessUtils) == null ? void 0 : _c.openRegisterModal) == null ? void 0 : _d.call(_c, true);
      return;
    }
    let contacts_info = null;
    try {
      if (showContactInfo) {
        contacts_info = await form.validateFields();
        const newPhone = {
          phone: ((_e = contacts_info == null ? void 0 : contacts_info.phone) == null ? void 0 : _e.phone) || "",
          country_calling_code: ((_f = contacts_info == null ? void 0 : contacts_info.phone) == null ? void 0 : _f.countryCallingCode) || "",
          country_code: ((_g = contacts_info == null ? void 0 : contacts_info.phone) == null ? void 0 : _g.countryCode) || ""
        };
        contacts_info.phone = newPhone;
        if ((contacts_info == null ? void 0 : contacts_info.first_name) || (contacts_info == null ? void 0 : contacts_info.last_name)) {
          contacts_info.display_name = `${(contacts_info == null ? void 0 : contacts_info.first_name) || ""} ${(contacts_info == null ? void 0 : contacts_info.last_name) || ""}`;
        } else {
          contacts_info.display_name = "";
        }
        console.log("contacts_info", contacts_info);
      }
    } catch (error) {
      console.log("error", error);
      return;
    }
    handleNext({ contacts_info });
  };
  (0, import_react.useEffect)(() => {
    return () => {
      pubsub.unsubscribe("bind.guest.user", handleNext);
      hasSubscribedRef.current = false;
    };
  }, []);
  (0, import_react.useImperativeHandle)(ref, () => ({
    next: handleSubmit
  }));
  const showContactInfo = (0, import_react.useMemo)(() => {
    let visible = false;
    const { showContactInfo: showContactInfoValue, contactInfoSetting } = bookingSetting || {};
    if (showContactInfoValue === 1 || showContactInfoValue === "1") {
      const { showName, showPhone, showEmail } = contactInfoSetting || {};
      if ((showName === 0 || showName === "0") && (showPhone === 0 || showPhone === "0") && (showEmail === 0 || showEmail === "0")) {
        visible = false;
      } else {
        visible = true;
      }
    } else {
      visible = false;
    }
    return visible;
  }, [bookingSetting == null ? void 0 : bookingSetting.showContactInfo, bookingSetting == null ? void 0 : bookingSetting.contactInfoSetting]);
  const renderContactInfo = () => {
    const {
      emailRequired,
      nameRequired,
      phoneRequired,
      showEmail,
      showName,
      showPhone
    } = (bookingSetting == null ? void 0 : bookingSetting.contactInfoSetting) || {};
    if (!showContactInfo) {
      return null;
    }
    return /* @__PURE__ */ import_react.default.createElement("div", { className: "appointment-confirm-information-contact-info-wrap" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "appointment-confirm-information-contact-info-title" }, import_utils.locales.getText("pisell2.text.contact-info.title")), /* @__PURE__ */ import_react.default.createElement(
      import_ContactInfoContent.default,
      {
        dataSource: null,
        form,
        config: {
          first_name: {
            visible: showName === 0 ? false : true,
            required: nameRequired === "required" ? true : false
            // 姓名默认选填
          },
          last_name: {
            visible: showName === 0 ? false : true,
            required: nameRequired === "required" ? true : false
            // 姓名默认选填
          },
          phone: {
            visible: showPhone === 0 ? false : true,
            required: phoneRequired === "optional" ? false : true
            // 手机号默认必填
          },
          email: {
            visible: showEmail === 0 ? false : true,
            required: emailRequired === "optional" ? false : true
            // 邮箱默认选填
          }
        }
      }
    ));
  };
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "appointment-confirm-information-wrap" }, (0, import_utils.isMobile)() ? /* @__PURE__ */ import_react.default.createElement(import_Item.default, { onNext: handleSubmit, renderContactInfo }) : showContactInfo ? renderContactInfo() : /* @__PURE__ */ import_react.default.createElement("div", { className: "appointment-confirm-information-content" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "image" }, /* @__PURE__ */ import_react.default.createElement(
    "img",
    {
      src: `${config == null ? void 0 : config.awsStatic}/checkout_confirm.png`,
      loading: "lazy"
    }
  )), /* @__PURE__ */ import_react.default.createElement("span", { className: "tips" }, import_utils.locales.getText("pisell2.appointment.tips")), /* @__PURE__ */ import_react.default.createElement("span", { className: "tips-content" }, import_utils.locales.getText("pisell2.appointment.tips.content"))));
});
var ConfirmInformation_default = ConfirmInformation;
