function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { createContext, useMemo, useState } from 'react';
import { useSales } from "../../../businessModel/SalesModel";
import { getHolderListApi, createHolderApi } from "./serve";
import { useRequest } from 'ahooks';
import { useCart } from "../Cart";
import useEngineContext from "../../../hooks/useEngineContext";
import { useCustomer } from "../Customer";

// 定义上下文接口

// 默认步骤状态
var defaultState = {};

// 创建步骤上下文
export var HolderContext = /*#__PURE__*/createContext(undefined);
export var HolderProvider = function HolderProvider(_ref) {
  var _data$holderData3, _data$holderData5;
  var children = _ref.children;
  var _useCustomer = useCustomer(),
    getUserInfo = _useCustomer.getUserInfo;
  var _useSales = useSales(),
    data = _useSales.data,
    setData = _useSales.setData,
    getCurrentData = _useSales.getCurrentData;
  var _useCart = useCart(),
    createCartItemFromHolder = _useCart.createCartItemFromHolder,
    addHolderToCartItem = _useCart.addHolderToCartItem,
    deleteCartItemByHolder = _useCart.deleteCartItemByHolder;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    open = _useState2[0],
    setOpen = _useState2[1];
  var context = useEngineContext();
  var utils = context.appHelper.utils || {};
  var holderData = useMemo(function () {
    return data.holderData || {};
  }, [data]);
  var setHolderData = function setHolderData(newHolderData) {
    setData({
      holderData: _objectSpread(_objectSpread({}, getCurrentData().holderData), newHolderData)
    });
  };
  var getHolderList = useRequest(getHolderListApi, {
    manual: true,
    onSuccess: function onSuccess(res) {
      var _res$data, _res$data$forEach;
      var list = [];
      (_res$data = res.data) === null || _res$data === void 0 || (_res$data = _res$data.list) === null || _res$data === void 0 || (_res$data$forEach = _res$data.forEach) === null || _res$data$forEach === void 0 || _res$data$forEach.call(_res$data, function (v) {
        var selectList = selectedHolderIds || [];
        // 已经选择的holder需要过滤掉
        if (!selectList.includes(v.form_record_id)) {
          list.push(createHolderItem(v));
        }
      });
      setHolderData({
        holderList: list
      });
    }
  });
  var createHolder = useRequest(createHolderApi, {
    manual: true
  });
  var refreshHolder = function refreshHolder() {
    var _getUserInfo, _data$initData, _data$initData2;
    var customerId = (_getUserInfo = getUserInfo()) === null || _getUserInfo === void 0 ? void 0 : _getUserInfo.id;
    getHolderList.run({
      form_id: (_data$initData = data.initData) === null || _data$initData === void 0 || (_data$initData = _data$initData.boardSetting) === null || _data$initData === void 0 || (_data$initData = _data$initData.config) === null || _data$initData === void 0 || (_data$initData = _data$initData.basic) === null || _data$initData === void 0 || (_data$initData = _data$initData.appointment_subject) === null || _data$initData === void 0 ? void 0 : _data$initData.form_id,
      shop_id: (_data$initData2 = data.initData) === null || _data$initData2 === void 0 ? void 0 : _data$initData2.shop_id,
      customer_id: customerId
    });
  };
  var updateHolderList = function updateHolderList(holderItem) {
    if (holderItem) {
      var _getCurrentData$holde;
      var holderList = ((_getCurrentData$holde = getCurrentData().holderData) === null || _getCurrentData$holde === void 0 ? void 0 : _getCurrentData$holde.holderList) || [];
      setHolderData({
        holderList: [createHolderItem(holderItem)].concat(_toConsumableArray(holderList))
      });
    }
  };
  var createHolderItem = function createHolderItem(item) {
    return {
      id: item.form_record_id,
      key: item.form_record_id,
      name: item.main_field,
      label: item.main_field,
      avatar: item.customer_cover,
      _originData: item
    };
  };

  /**
   * @title:
   * @description: 选择holder，分为两种情况：
   * 1.将没有holder信息的商品加上holder信息并更新购物车；
   * 2.用选中的holder信息创建一个购物车商品
   * @param {any} holderItem
   * @param {'addToCart' | 'createCartItem'} type
   * @return {void}
   * @Author: Xxf
   * @Date: 2025-01-20 11:23
   */
  var selectHolder = function selectHolder(holderItem, type) {
    var _data$holderData;
    if (type === 'addToCart') {
      // 将holder赋值到购物车中所有没有holder的商品
      addHolderToCartItem(holderItem);
    } else if (type === 'createCartItem') {
      // 创建一个拥有holder信息的空购物车商品
      createCartItemFromHolder(holderItem);
    }

    // 将当前操作的holder赋值到currentHolderItem
    setHolderData({
      currentHolderItem: holderItem
    });
    var selectedHolderItems = ((_data$holderData = data.holderData) === null || _data$holderData === void 0 ? void 0 : _data$holderData.selectedHolderItems) || [];
    var res = selectedHolderItems.find(function (v) {
      return v.id === holderItem.id;
    });
    if (res === undefined) {
      setHolderData({
        selectedHolderItems: [].concat(_toConsumableArray(selectedHolderItems), [holderItem])
      });
    }
  };
  var onHolderOpen = function onHolderOpen() {
    setOpen(true);
    refreshHolder();
  };
  var onOpenCreateHolder = function onOpenCreateHolder(_ref2) {
    var _data$initData3;
    var form_title = _ref2.form_title,
      callback = _ref2.callback;
    utils.action({
      type: 'pisell1.form',
      data: {
        form_id: (_data$initData3 = data.initData) === null || _data$initData3 === void 0 || (_data$initData3 = _data$initData3.boardSetting) === null || _data$initData3 === void 0 || (_data$initData3 = _data$initData3.config) === null || _data$initData3 === void 0 || (_data$initData3 = _data$initData3.basic) === null || _data$initData3 === void 0 || (_data$initData3 = _data$initData3.appointment_subject) === null || _data$initData3 === void 0 ? void 0 : _data$initData3.form_id,
        form_title: form_title,
        isV2API: true
      },
      callback: callback
    });
  };
  var onHolderClose = function onHolderClose() {
    setOpen(false);
  };
  var deleteHolderById = function deleteHolderById(holderId) {
    var _getCurrentData$holde2;
    var newSelectedHolderItems = (_getCurrentData$holde2 = getCurrentData().holderData) === null || _getCurrentData$holde2 === void 0 || (_getCurrentData$holde2 = _getCurrentData$holde2.selectedHolderItems) === null || _getCurrentData$holde2 === void 0 ? void 0 : _getCurrentData$holde2.filter(function (v) {
      return v.id !== holderId;
    });
    setHolderData({
      selectedHolderItems: newSelectedHolderItems
    });
    // 删除holder后还要删除对应holder的购物车中商品
    deleteCartItemByHolder(holderId);
  };
  var selectedHolderIds = useMemo(function () {
    var _data$holderData2, _data$holderData2$map;
    return (_data$holderData2 = data.holderData) === null || _data$holderData2 === void 0 || (_data$holderData2 = _data$holderData2.selectedHolderItems) === null || _data$holderData2 === void 0 || (_data$holderData2$map = _data$holderData2.map) === null || _data$holderData2$map === void 0 ? void 0 : _data$holderData2$map.call(_data$holderData2, function (v) {
      return v.id;
    });
  }, [(_data$holderData3 = data.holderData) === null || _data$holderData3 === void 0 ? void 0 : _data$holderData3.selectedHolderItems]);

  /**
   * @title: 当前默认选中的holder
   * @description:
   * @param {*} useMemo
   * @return {*}
   * @Author: WangHan
   * @Date: 2025-01-21 17:41
   */
  var defaultSelectedHolder = useMemo(function () {
    var _data$holderData4;
    var lists = ((_data$holderData4 = data.holderData) === null || _data$holderData4 === void 0 ? void 0 : _data$holderData4.holderList) || [];
    return (lists === null || lists === void 0 ? void 0 : lists[0]) || {};
  }, [(_data$holderData5 = data.holderData) === null || _data$holderData5 === void 0 ? void 0 : _data$holderData5.holderList]);
  var contextValue = {
    holderData: holderData,
    getHolderList: getHolderList,
    selectHolder: selectHolder,
    open: open,
    onOpenCreateHolder: onOpenCreateHolder,
    onHolderOpen: onHolderOpen,
    onHolderClose: onHolderClose,
    createHolder: createHolder,
    refreshHolder: refreshHolder,
    deleteHolderById: deleteHolderById,
    selectedHolderIds: selectedHolderIds,
    updateHolderList: updateHolderList,
    defaultSelectedHolder: defaultSelectedHolder
  };
  return /*#__PURE__*/React.createElement(HolderContext.Provider, {
    value: contextValue
  }, children);
};

/**
 * 使用步骤管理的Hook
 * @throws {Error} 如果在StepProvider外部使用会抛出错误
 * @returns {StepContextType} 步骤管理上下文
 */
export var useHolder = function useHolder() {
  var context = React.useContext(HolderContext);
  if (!context) {
    throw new Error('useHolder must be used within a HolderProvider');
  }
  return context;
};
export default {
  defaultState: defaultState
};