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 { locales } from "@pisell/utils";
import { useRequest } from "ahooks";
import { Button } from "antd";
import React, { useContext, useRef } from "react";
import CustomSelect from "../../../../../../booking/components/customSelect";
import { Context } from "../../../../../model";
import { getSchedules } from "../../../../serve";
import useComponents from "../../../../../../../hooks/useComponents";
import useEngineContext from "../../../../../../../hooks/useEngineContext";
import "./index.less";
var AddSchedules = function AddSchedules(_ref) {
  var _state$schedules3;
  var value = _ref.value,
    onChange = _ref.onChange,
    drawerContainer = _ref.drawerContainer,
    isSelf = _ref.isSelf;
  var modalRef = useRef(null);
  var _useContext = useContext(Context),
    state = _useContext.state,
    dispatch = _useContext.dispatch;
  var _useEngineContext = useEngineContext(),
    appHelper = _useEngineContext.appHelper;
  var createSchedules = useRef();
  var AllCreateScheduleRef = useRef(null);
  var _useComponents = useComponents({
      components: ["ScheduleCreateType", "AllCreateSchedule"]
    }),
    _useComponents2 = _slicedToArray(_useComponents, 2),
    ScheduleCreateType = _useComponents2[0],
    AllCreateSchedule = _useComponents2[1];
  var _getScheduleList = useRequest(getSchedules, {
    manual: true,
    onSuccess: function onSuccess(res) {}
  });
  var onFinish = function onFinish(e) {
    var scheduleList = isSelf ? _getScheduleList === null || _getScheduleList === void 0 ? void 0 : _getScheduleList.data : state.schedules.list;
    var idMap = (scheduleList === null || scheduleList === void 0 ? void 0 : scheduleList.reduce(function (p, c) {
      return _objectSpread(_objectSpread({}, p), {}, _defineProperty({}, c.id, c));
    }, {})) || {};
    onChange(e.map(function (item) {
      return idMap[item.id];
    }));
  };
  var handleCreateSchedule = function handleCreateSchedule() {
    var _createSchedules$curr, _createSchedules$curr2;
    (_createSchedules$curr = createSchedules.current) === null || _createSchedules$curr === void 0 || (_createSchedules$curr2 = _createSchedules$curr.open) === null || _createSchedules$curr2 === void 0 || _createSchedules$curr2.call(_createSchedules$curr, {
      getContainer: undefined
    });
  };
  var handleAddSchedule = function handleAddSchedule(data) {
    if (isSelf) {
      _getScheduleList.mutate(function (oldData) {
        return [data].concat(_toConsumableArray(oldData || []));
      });
    } else {
      var _state$schedules;
      dispatch({
        type: "setSchedules",
        payload: _objectSpread(_objectSpread({}, state.schedules), {}, {
          list: [data].concat(_toConsumableArray((state === null || state === void 0 || (_state$schedules = state.schedules) === null || _state$schedules === void 0 ? void 0 : _state$schedules.list) || []))
        })
      });
    }
    modalRef.current.setValue(function (v) {
      return [].concat(_toConsumableArray(v), [data]);
    });
    setTimeout(function () {
      var _document$getElementB, _document$getElementB2;
      (_document$getElementB = document.getElementById(data.id)) === null || _document$getElementB === void 0 || (_document$getElementB2 = _document$getElementB.scrollIntoView) === null || _document$getElementB2 === void 0 || _document$getElementB2.call(_document$getElementB, {
        block: "center",
        behavior: "smooth"
      });
    });
  };
  var handleEdit = function handleEdit(e, id) {
    var _AllCreateScheduleRef, _AllCreateScheduleRef2;
    e.stopPropagation();
    (_AllCreateScheduleRef = AllCreateScheduleRef.current) === null || _AllCreateScheduleRef === void 0 || (_AllCreateScheduleRef2 = _AllCreateScheduleRef.open) === null || _AllCreateScheduleRef2 === void 0 || _AllCreateScheduleRef2.call(_AllCreateScheduleRef, {
      id: id
    });
  };
  var handleChangeResData = function handleChangeResData(data) {
    var updateOldData = function updateOldData(oldData) {
      return (oldData || []).map(function (item) {
        if (item.id === data.id) {
          var _appHelper$utils;
          return _objectSpread(_objectSpread({}, data), {}, {
            name: (appHelper === null || appHelper === void 0 || (_appHelper$utils = appHelper.utils) === null || _appHelper$utils === void 0 ? void 0 : _appHelper$utils.translationShop(data.name)) || data.name
          });
        }
        return item;
      });
    };
    if (isSelf) {
      _getScheduleList.mutate(updateOldData);
    } else {
      var _state$schedules2;
      dispatch({
        type: "setSchedules",
        payload: _objectSpread(_objectSpread({}, state.schedules), {}, {
          list: updateOldData(state === null || state === void 0 || (_state$schedules2 = state.schedules) === null || _state$schedules2 === void 0 ? void 0 : _state$schedules2.list)
        })
      });
    }
  };
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Button, {
    ghost: true,
    type: "primary",
    className: "product-detail-card-module-add-button",
    onClick: function onClick() {
      var _modalRef$current;
      (_modalRef$current = modalRef.current) === null || _modalRef$current === void 0 || _modalRef$current.open();
      if (isSelf) {
        _getScheduleList.run({
          num: 999,
          skip: 1
        });
      }
    }
  }, locales.getText("pisell2.text.schedules.assign-schedule")), /*#__PURE__*/React.createElement(CustomSelect, {
    ref: modalRef,
    rowKey: "id",
    options: isSelf ? _getScheduleList.data || [] : (state === null || state === void 0 || (_state$schedules3 = state.schedules) === null || _state$schedules3 === void 0 ? void 0 : _state$schedules3.list) || [],
    createItemText: locales.getText('pisell2.text.schedules.create-new-schedule'),
    loading: _getScheduleList.loading,
    value: value,
    onValueChange: onFinish,
    handleCreateItem: handleCreateSchedule,
    isPreview: false,
    drawerProps: _objectSpread({
      title: locales.getText("pisell2.text.schedules.assign-schedule"),
      destroyOnClose: true,
      width: 480,
      getContainer: drawerContainer || document.querySelector(".pisell-lowcode__schedules-component-products") || document.body,
      rootStyle: {
        position: "absolute"
      },
      contentWrapperStyle: {
        boxShadow: "none"
      },
      titleNoWrap: true
    }, isSelf ? {
      zIndex: 1000
    } : {}),
    mode: "multiple",
    optionRender: function optionRender(item) {
      return /*#__PURE__*/React.createElement("div", {
        className: "pisell-lowcode__add-schedule-list-item"
      }, /*#__PURE__*/React.createElement("div", {
        className: "pisell-lowcode__add-schedule-list-item-content"
      }, /*#__PURE__*/React.createElement("div", {
        className: "pisell-lowcode__add-schedule-list-item-color",
        style: {
          backgroundColor: item.color
        }
      }), item.name), /*#__PURE__*/React.createElement("div", {
        className: "pisell-lowcode__add-schedule-list-item-action-wrap"
      }, /*#__PURE__*/React.createElement("div", {
        className: "pisell-lowcode__add-schedule-list-item-action-edit",
        onClick: function onClick(e) {
          return handleEdit(e, item.id);
        }
      }, locales.getText("pisell2.text.edit"))));
    }
    // onVirtualListScroll={onScroll}
    // loadMore={loadMore}
    ,
    filterItem: function filterItem(d, search) {
      return d.name.toLowerCase().indexOf(search.toLowerCase()) !== -1;
    }
  }), ScheduleCreateType && /*#__PURE__*/React.createElement(ScheduleCreateType, {
    ref: createSchedules,
    onChange: handleAddSchedule
  }), AllCreateSchedule && /*#__PURE__*/React.createElement(AllCreateSchedule, {
    ref: AllCreateScheduleRef,
    onChange: handleChangeResData
  }));
};
export default AddSchedules;