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, useRef, useState } from 'react';
import { getEventDetailBookingOptionsApi, getEventDetailIntroductionApi, getEventDetailSelectDateApi, getEventDetailTeacherApi, getProductDetailApi } from "./serve";
import { useRequest } from 'ahooks';
import { useEvent } from "./index";
import { getIamgeFromMedia } from "../utils";
import useLoginUser from "../../../hooks/useLoginUser";

// 定义步骤数据接口

// 定义上下文接口

// 创建步骤上下文
export var EventDetailContext = /*#__PURE__*/createContext(undefined);
export var EventDetailProvider = function EventDetailProvider(_ref) {
  var children = _ref.children;
  var eventRef = useRef({});
  var detailRef = useRef({});
  var _useState = useState(null),
    _useState2 = _slicedToArray(_useState, 2),
    detail = _useState2[0],
    setDetail = _useState2[1];
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    open = _useState4[0],
    setOpen = _useState4[1];
  var _useState5 = useState(null),
    _useState6 = _slicedToArray(_useState5, 2),
    currentBookingOption = _useState6[0],
    setCurrentBookingOption = _useState6[1];
  var _useEvent = useEvent(),
    selectEvent = _useEvent.selectEvent;
  var customer = useLoginUser();
  var currentBookingOptionRef = useRef(null);
  var _setDetail = function _setDetail(detailData) {
    detailRef.current = _objectSpread(_objectSpread({}, detailRef.current || {}), detailData || {});
    setDetail(_objectSpread({}, detailRef.current));
  };
  var _setCurrentBookingOption = function _setCurrentBookingOption(id) {
    currentBookingOptionRef.current = id;
    setCurrentBookingOption(id);
  };
  var onOpenEventDetail = function onOpenEventDetail(eventItem) {
    var _eventItem$_originDat;
    setOpen(true);

    // 从eventItem数据源中获取展示数据，接口正常更新
    var introduction = {
      title: eventItem.title,
      price: eventItem.price,
      images: eventItem.image ? [eventItem.image] : []
    };
    eventRef.current = eventItem;
    _setDetail({
      introduction: introduction
    });
    getEventDetailIntroduction.run(eventItem.id);
    getEventDetailResource.run({
      event_item_id: eventItem.id
    });
    getEventDetailBookingOptions.run({
      ids: ((_eventItem$_originDat = eventItem._originData) === null || _eventItem$_originDat === void 0 ? void 0 : _eventItem$_originDat.relation_product_ids) || [],
      num: 100,
      skip: 1,
      customer_id: customer === null || customer === void 0 ? void 0 : customer.id,
      open_quotation: 1,
      is_eject: 1
    });
    getEventDetailSelectDate.run(eventItem.id, {
      days: 366
    });
  };
  var onCloseEventDetail = function onCloseEventDetail() {
    setOpen(false);
    _setDetail(null);
    detailRef.current = null;
    setCurrentBookingOption(null);
    currentBookingOptionRef.current = null;
  };

  /**
   * @title:选择活动详情
   * @param productDetail 商品详情
   */
  var onSelectEventDetail = function onSelectEventDetail() {
    var _detail$bookingOption, _detailRef$current;
    selectEvent(_objectSpread(_objectSpread({}, eventRef.current), {}, {
      eventDetail: _objectSpread(_objectSpread({}, detailRef.current || {}), {}, {
        bookingOptionItem: (_detail$bookingOption = detail.bookingOptions) === null || _detail$bookingOption === void 0 || (_detail$bookingOption = _detail$bookingOption.filter(function (v) {
          return v.value === currentBookingOptionRef.current;
        })) === null || _detail$bookingOption === void 0 ? void 0 : _detail$bookingOption[0],
        productDetail: (_detailRef$current = detailRef.current) === null || _detailRef$current === void 0 ? void 0 : _detailRef$current.productDetail
      })
    }));
    onCloseEventDetail();
  };

  /**
   * Introduction数据获取
   */
  var getEventDetailIntroduction = useRequest(getEventDetailIntroductionApi, {
    manual: true,
    onSuccess: function onSuccess(res) {
      var data = res.data;
      _setDetail({
        introduction: _objectSpread(_objectSpread({}, detail.introduction || {}), {}, {
          title: data.title,
          subtitle: data.subtitle,
          description: data.description,
          images: getIamgeFromMedia(data.media),
          _originData: res.data
        })
      });
    }
  });

  /**
   * Schedule Date数据获取
   */
  var getEventDetailSelectDate = useRequest(getEventDetailSelectDateApi, {
    manual: true,
    onSuccess: function onSuccess(res) {
      var _detailRef$current2, _detailRef$current3;
      var data = res.data;
      var dates = _toConsumableArray(data.dates || []);
      var startDateInfo = (_detailRef$current2 = detailRef.current) === null || _detailRef$current2 === void 0 || (_detailRef$current2 = _detailRef$current2.selectDate) === null || _detailRef$current2 === void 0 ? void 0 : _detailRef$current2.startDateInfo;
      var endDateInfo = (_detailRef$current3 = detailRef.current) === null || _detailRef$current3 === void 0 || (_detailRef$current3 = _detailRef$current3.selectDate) === null || _detailRef$current3 === void 0 ? void 0 : _detailRef$current3.endDateInfo;
      var selectDate = {
        dates: dates,
        _originData: {
          dates: dates,
          default_data: data.default_data,
          shop_time: data.shop_time
        },
        startDateInfo: startDateInfo,
        endDateInfo: endDateInfo
      };
      if (!startDateInfo) {
        selectDate.startDateInfo = dates === null || dates === void 0 ? void 0 : dates[0];
      }
      if (!endDateInfo && dates !== null && dates !== void 0 && dates.length) {
        selectDate.endDateInfo = dates === null || dates === void 0 ? void 0 : dates[dates.length - 1];
      }
      _setDetail({
        selectDate: selectDate
      });
    }
  });

  /**
   * 资源获取
   */
  var getEventDetailResource = useRequest(getEventDetailTeacherApi, {
    manual: true,
    onSuccess: function onSuccess(res) {
      var data = res.data || [];
      var resource = [];
      data.forEach(function (item) {
        var _item$resource;
        resource.push({
          title: item.form_name,
          children: item === null || item === void 0 || (_item$resource = item.resource) === null || _item$resource === void 0 ? void 0 : _item$resource.map(function (v) {
            var _v$form_data;
            return {
              id: v.id,
              title: v.resource_name,
              image: getIamgeFromMedia(v === null || v === void 0 || (_v$form_data = v.form_data) === null || _v$form_data === void 0 ? void 0 : _v$form_data.media, 'findOne'),
              _originData: v
            };
          })
        });
      });
      _setDetail({
        resource: resource
      });
    }
  });

  /**
   * BookingOptions数据获取
   */
  var getEventDetailBookingOptions = useRequest(getEventDetailBookingOptionsApi, {
    manual: true,
    onSuccess: function onSuccess(res) {
      var _res$data;
      var list = ((_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.list) || [];
      var current = null;
      var bookingOptions = list.map(function (v) {
        var _current;
        var option = {
          value: v.id,
          label: v.title,
          price: v.price,
          _originData: v
        };
        if (!current || Number(((_current = current) === null || _current === void 0 ? void 0 : _current.price) || 0) > Number(v.price || 0)) {
          current = _objectSpread({}, option);
        }
        return option;
      });
      _setDetail({
        bookingOptions: bookingOptions
      });
      selectEventDetailBookingOptions(current.value);
    }
  });
  var getProductDetailRequest = useRequest(getProductDetailApi, {
    manual: true,
    loadingDelay: 200
  });

  /**
   * @title: 选择活动关联的商品
   * @param id 活动关联的商品id
   */
  var selectEventDetailBookingOptions = function selectEventDetailBookingOptions(id) {
    var _bookingOptions$filte, _option$_originData;
    var _ref2 = detailRef.current || {},
      introduction = _ref2.introduction,
      bookingOptions = _ref2.bookingOptions;
    var option = bookingOptions === null || bookingOptions === void 0 || (_bookingOptions$filte = bookingOptions.filter(function (v) {
      return v.value === id;
    })) === null || _bookingOptions$filte === void 0 ? void 0 : _bookingOptions$filte[0];
    var setSelectedData = function setSelectedData(data) {
      _setDetail({
        introduction: _objectSpread(_objectSpread({}, introduction), {}, {
          price: data === null || data === void 0 ? void 0 : data.price,
          origin_price: data === null || data === void 0 ? void 0 : data.original_price
        }),
        selectedProduct: data // 选中的活动关联的商品
      });
      _setCurrentBookingOption(id);
    };

    // 普通商品需要单独查询商品详情
    if ((option === null || option === void 0 || (_option$_originData = option._originData) === null || _option$_originData === void 0 ? void 0 : _option$_originData.is_eject) === 0) {
      var _introduction$_origin;
      getProductDetailRequest.runAsync(id, {
        open_deposit: 1,
        front_end_cache_id: (introduction === null || introduction === void 0 || (_introduction$_origin = introduction._originData) === null || _introduction$_origin === void 0 ? void 0 : _introduction$_origin.id) + '_' + id
      }).then(function (res) {
        var _res$data2;
        // 定金相关信息
        var custom_deposit_data = res === null || res === void 0 || (_res$data2 = res.data) === null || _res$data2 === void 0 ? void 0 : _res$data2.custom_deposit_data;
        var newOption = _objectSpread({}, option);
        if (custom_deposit_data && newOption._originData) {
          newOption._originData.custom_deposit_data = custom_deposit_data;
        }
        setSelectedData(newOption);
      }).catch(function () {
        setSelectedData(option);
      });
    } else {
      setSelectedData(option);
    }
  };

  /**
   * @title: 选择商品详情
   * @param {any} productDetail 商品详情
   */
  var selectEventDetailProductDetail = function selectEventDetailProductDetail(productDetail) {
    _setDetail({
      productDetail: productDetail
    });
  };

  /**
   * @title: 校验is_eject为1的商品是否有拉起商品详情弹窗选中过
   * @returns boolean
   */
  var checkBeforeSelectEventDetail = function checkBeforeSelectEventDetail() {
    var _selectedProduct$_ori;
    var _ref3 = detailRef.current || {},
      selectedProduct = _ref3.selectedProduct,
      productDetail = _ref3.productDetail;
    console.log('selectedProduct', selectedProduct, productDetail);
    if ((selectedProduct === null || selectedProduct === void 0 || (_selectedProduct$_ori = selectedProduct._originData) === null || _selectedProduct$_ori === void 0 ? void 0 : _selectedProduct$_ori.is_eject) === 1 && !productDetail) {
      return false;
    }
    return true;
  };
  var contextValue = {
    detail: detail,
    open: open,
    onOpenEventDetail: onOpenEventDetail,
    onCloseEventDetail: onCloseEventDetail,
    onSelectEventDetail: onSelectEventDetail,
    selectEventDetailBookingOptions: selectEventDetailBookingOptions,
    getEventDetailSelectDate: getEventDetailSelectDate,
    currentBookingOption: currentBookingOption,
    selectEventDetailProductDetail: selectEventDetailProductDetail,
    checkBeforeSelectEventDetail: checkBeforeSelectEventDetail,
    getProductDetailRequest: getProductDetailRequest
  };
  return /*#__PURE__*/React.createElement(EventDetailContext.Provider, {
    value: contextValue
  }, children);
};

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