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/booking/forms/index.tsx
var forms_exports = {};
__export(forms_exports, {
  default: () => forms_default
});
module.exports = __toCommonJS(forms_exports);
var import_react = __toESM(require("react"));
var import_tabPane = __toESM(require("../components/tabPane"));
var import_model = require("./model");
var import_antd = require("antd");
var import_emptyBooking = __toESM(require("../components/emptyBooking"));
var import_index = require("./index.less");
var import_utils = require("@pisell/utils");
var import_forms = __toESM(require("./forms"));
var import_utils2 = require("../utils");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_footer = __toESM(require("./footer"));
var relation_type = "appointment_booking";
var Forms = (0, import_model.Provider)((props) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
  const { globalState } = props;
  const [loading, setLoading] = (0, import_react.useState)(true);
  const { state, dispatch } = (0, import_react.useContext)(import_model.Context);
  const context = (0, import_useEngineContext.default)();
  const { isTerminal } = ((_a = context.appHelper) == null ? void 0 : _a.utils) || {};
  const params = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2;
    return (_c2 = (_b2 = (_a2 = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _a2.config) == null ? void 0 : _b2.basic) == null ? void 0 : _c2.appointment_subject;
  }, [(_d = (_c = (_b = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _b.config) == null ? void 0 : _c.basic) == null ? void 0 : _d.appointment_subject]);
  (0, import_react.useEffect)(() => {
    var _a2, _b2;
    if (!!((_b2 = (_a2 = state.bookingDetail) == null ? void 0 : _a2.bookings) == null ? void 0 : _b2.id)) {
      geForms();
    }
  }, [(_f = (_e = state.bookingDetail) == null ? void 0 : _e.bookings) == null ? void 0 : _f.id, (_h = (_g = state.client) == null ? void 0 : _g.value) == null ? void 0 : _h.id]);
  const getFranchiseeCompositeData = async ({ request, params: params2 }) => {
    let arr = [];
    arr.push(request(params2));
    if (state.isFranchisee) {
      arr.push(request({ ...params2, source_shop_customer: 1 }));
    }
    const res = await Promise.all(arr);
    return res;
  };
  const getFranchiseeForms = async (params2) => {
    const res = await getFranchiseeCompositeData({
      request: state.apis.getForms,
      params: params2
    });
    if (state.isFranchisee) {
      let arr = [];
      res.forEach((item, index) => {
        arr = arr.concat(
          (item || []).map((d) => {
            return {
              ...d,
              is_franchisor: index === 1 ? 1 : 0
            };
          })
        );
      });
      return arr;
    }
    return res[0];
  };
  const getFormDataById = async (item) => {
    var _a2, _b2;
    let _params = {
      form_id: item.form_id,
      skip: 1,
      num: 999,
      source_shop_customer: item.is_franchisor ? 1 : 0
    };
    let options = [];
    const isCustomerForm = item.data_range === "customer" && !(0, import_utils2.isWalkIn)((_b2 = (_a2 = state.client) == null ? void 0 : _a2.value) == null ? void 0 : _b2.id);
    if (item.data_range !== "customer" || isCustomerForm) {
      if (isCustomerForm) {
        _params.customer_id = state.client.value.id;
      }
      const data = await state.apis.getPetsData(_params);
      options = (data == null ? void 0 : data.list) || [];
    }
    return {
      ...item,
      options
    };
  };
  const getFormData = async (formList = []) => {
    let all = [];
    all = formList.map((d) => getFormDataById(d));
    return Promise.all(all);
  };
  const getFormValues = (data) => {
    let _values = {};
    for (let item of data) {
      _values[item.form_id] = item.form_record;
    }
    return _values;
  };
  const geForms = async () => {
    setLoading(true);
    try {
      let data = await getFranchiseeForms({
        relation_type,
        relation_id: state.bookingDetail.bookings.id
        // _config: { useCache: true },
      });
      data = data || [];
      if (params.type === "form") {
        data = data.filter((d) => d.form_id !== (params == null ? void 0 : params.form_id));
      }
      console.log("datadata", data);
      const formData = await getFormData(data);
      dispatch({
        type: "setForm",
        payload: {
          forms: formData,
          value: getFormValues(data)
        }
      });
      setLoading(false);
    } catch (err) {
      setLoading(false);
      console.log("form_error", err);
    }
  };
  (0, import_react.useEffect)(() => {
    document.body.id = "body";
  }, []);
  (0, import_react.useEffect)(() => {
    dispatch({
      type: "setState",
      payload: {
        setGlobalState: props.setGlobalState
      }
    });
  }, []);
  (0, import_react.useEffect)(() => {
    var _a2, _b2, _c2, _d2;
    const isFranchisee = (_d2 = (_c2 = (_b2 = (_a2 = context == null ? void 0 : context.appHelper) == null ? void 0 : _a2.utils) == null ? void 0 : _b2.businessUtils) == null ? void 0 : _c2.getAppByModal) == null ? void 0 : _d2.call(_c2, "franchisee");
    dispatch({
      type: "setState",
      payload: {
        ...globalState,
        isFranchisee
      }
    });
  }, [globalState]);
  const saveBookingFormData = async (params2) => {
    try {
      const data = await state.apis.saveBookingFormData(params2);
      import_antd.message.success(
        import_utils.locales.getText("pisell2.text.forms") + import_utils.locales.getText("pisell2.text.updated")
      );
      state == null ? void 0 : state.callback({ order_id: state.bookingId, afterCloseUpdate: true });
    } catch (err) {
    }
  };
  const onValueChange = (data) => {
    const { values, current } = data;
    dispatch({
      type: "setForm",
      payload: {
        value: values
      }
    });
    let _arr = current.value || [];
    saveBookingFormData({
      relation_type,
      relation_id: state.bookingDetail.bookings.id,
      form_id: current.field.form_id,
      form_record_ids: _arr.map((d) => d.form_record_id)
    });
  };
  const addCallback = async (form) => {
    let _data = [...state.form.forms];
    const data = await getFormDataById(form);
    _data = _data.map((d) => d.form_id === form.form_id ? data : d);
    dispatch({
      type: "setForm",
      payload: {
        forms: _data
      }
    });
  };
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, !!state.setGlobalState ? /* @__PURE__ */ import_react.default.createElement(
    import_tabPane.default,
    {
      header: import_utils.locales.getText("pisell2.text.forms"),
      loading: loading && globalState.bookingId,
      bodyClassName: "booking-forms-body",
      footer: state.bookingId && ((_i = state == null ? void 0 : state.form) == null ? void 0 : _i.forms.length) && /* @__PURE__ */ import_react.default.createElement(import_footer.default, { state: globalState, reload: geForms })
    },
    !globalState.bookingId ? /* @__PURE__ */ import_react.default.createElement(import_emptyBooking.default, null) : /* @__PURE__ */ import_react.default.createElement(
      import_forms.default,
      {
        forms: state.form.forms,
        action: state.action,
        modalOpen: state.modalOpen,
        value: state.form.value,
        onChange: onValueChange,
        addCallback,
        client: state.client.value,
        customSelectProps: {
          autoFocus: !state.isTerminal
        }
      }
    )
  ) : null);
});
var forms_default = Forms;
