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 _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
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, { useState, useMemo, forwardRef, useCallback, useImperativeHandle } from 'react';
import classNames from 'classnames';
import { Col, Form, Select, Button, Alert, Checkbox, Tooltip, Row } from 'antd';
import { Iconfont } from '@pisell/materials';
import MaxLengthSelect from "./MaxLengthSelect";
import Like from "../../../../info/service/like";
import "./index.less";
import { locales } from '@pisell/utils';
import { getErrorList } from "../../../utilsByBooking";
import { isArray } from 'lodash';
import { getAutoAllocationStorage, setAutoAllocationStorage } from "../utils";
import { useUpdate } from 'ahooks';
import { QuestionCircleOutlined } from '@ant-design/icons';
var Resources = function Resources(_ref, ref) {
  var _cacheItem$_data2, _originCacheItem$_dat, _cacheItem$_data5;
  var state = _ref.state,
    cacheItem = _ref.cacheItem,
    originCacheItem = _ref.originCacheItem,
    getCurrentCacheItem = _ref.getCurrentCacheItem,
    onChange = _ref.onChange,
    value = _ref.value,
    originValue = _ref.originValue,
    _ref$config = _ref.config,
    config = _ref$config === void 0 ? {
      // 是否显示自动分配
      autoAllocation: true,
      // 是否显示资源错误图标
      resourceErrorIcon: true,
      disabled: false,
      size: 'large'
    } : _ref$config;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    showError = _useState2[0],
    setShowError = _useState2[1];
  var update = useUpdate();

  // 需要渲染的列表, 资源二级结构数据
  var data = useMemo(function () {
    var _cacheItem$_data;
    return (cacheItem === null || cacheItem === void 0 || (_cacheItem$_data = cacheItem._data) === null || _cacheItem$_data === void 0 ? void 0 : _cacheItem$_data.resources) || [];
  }, [cacheItem === null || cacheItem === void 0 || (_cacheItem$_data2 = cacheItem._data) === null || _cacheItem$_data2 === void 0 ? void 0 : _cacheItem$_data2.resources]);
  var originData = useMemo(function () {
    var _cacheItem$_data3;
    return (cacheItem === null || cacheItem === void 0 || (_cacheItem$_data3 = cacheItem._data) === null || _cacheItem$_data3 === void 0 ? void 0 : _cacheItem$_data3.resources) || [];
  }, [originCacheItem === null || originCacheItem === void 0 || (_originCacheItem$_dat = originCacheItem._data) === null || _originCacheItem$_dat === void 0 ? void 0 : _originCacheItem$_dat.resources]);

  // 同上, 只是map结构,方便计算
  var resourceMaps = useMemo(function () {
    var _cacheItem$_data4;
    return (cacheItem === null || cacheItem === void 0 || (_cacheItem$_data4 = cacheItem._data) === null || _cacheItem$_data4 === void 0 ? void 0 : _cacheItem$_data4.resourceMaps) || [];
  }, [cacheItem === null || cacheItem === void 0 || (_cacheItem$_data5 = cacheItem._data) === null || _cacheItem$_data5 === void 0 ? void 0 : _cacheItem$_data5.resourceMaps]);

  // 默认值
  var defaultValue = useMemo(function () {
    return data.reduce(function (pre, cur) {
      pre[cur.form_id] = [];
      return pre;
    }, {});
  }, [data]);

  // 当前的值
  var _value = useMemo(function () {
    return value || defaultValue;
  }, [value, defaultValue]);
  var handleCheckAutoAllocation = function handleCheckAutoAllocation(id, checked) {
    setAutoAllocationStorage(_defineProperty({}, id, checked));
    update();
  };

  /**
   * @title: 当选择资源时
   * @description:
   * @param {any} val
   * @param {number} form_id
   * @param {string} key
   * @return {*}
   * @Author: zhiwei.Wang
   * @Date: 2024-09-19 21:04
   */
  var _onChange = function _onChange(val, form_id, key) {
    var _val = _objectSpread({}, _value);
    // 将当前数据map化, 减少循环次数
    var maps = _val[form_id] ? _val[form_id].reduce(function (pre, cur) {
      pre[cur.relation_id] = cur;
      return pre;
    }, {}) : {};
    // 重新赋值, 因为select返回的是数字列表, 需要补充额外的数据
    _val[form_id] = val.map(function (d) {
      var _currentForm$renderLi, _currentForm$renderLi2, _currentForm$renderLi3, _currentForm$renderLi4, _currentForm$renderLi5;
      var _d = maps[d];
      if (_d) {
        if (key === 'like_status') {
          d[key].like_status = val;
        }
      }
      var currentForm = (resourceMaps === null || resourceMaps === void 0 ? void 0 : resourceMaps[form_id]) || {};
      return (
        // maps[d] 为真时, 说明是之前已选择, 否则为新增的值,补充数据
        maps[d] || {
          relation_type: ((_currentForm$renderLi = currentForm.renderListMaps[d]) === null || _currentForm$renderLi === void 0 || (_currentForm$renderLi = _currentForm$renderLi.usable) === null || _currentForm$renderLi === void 0 ? void 0 : _currentForm$renderLi.relation_type) || 'form',
          form_id: form_id,
          relation_id: d,
          like_status: 'common',
          children: (_currentForm$renderLi2 = currentForm.renderListMaps) === null || _currentForm$renderLi2 === void 0 || (_currentForm$renderLi2 = _currentForm$renderLi2[d]) === null || _currentForm$renderLi2 === void 0 ? void 0 : _currentForm$renderLi2.children,
          // 新添加的数据补充错误信息
          errors: getErrorList((_currentForm$renderLi3 = currentForm.renderListMaps) === null || _currentForm$renderLi3 === void 0 ? void 0 : _currentForm$renderLi3[d], getCurrentCacheItem()),
          metadata: _objectSpread(_objectSpread({}, (_currentForm$renderLi4 = currentForm.renderListMaps) === null || _currentForm$renderLi4 === void 0 || (_currentForm$renderLi4 = _currentForm$renderLi4[d]) === null || _currentForm$renderLi4 === void 0 ? void 0 : _currentForm$renderLi4.metadata), {}, {
            form_name: currentForm.title,
            resource_name: (_currentForm$renderLi5 = currentForm.renderListMaps[d]) === null || _currentForm$renderLi5 === void 0 ? void 0 : _currentForm$renderLi5.main_field
          })
        }
      );
    });
    setShowError(false);
    onChange === null || onChange === void 0 || onChange(_val);
  };
  var setLikeStatus = function setLikeStatus(val, form_id, key) {
    var _val$form_id;
    var _val = _objectSpread({}, _value);
    if (_val !== null && _val !== void 0 && (_val$form_id = _val[form_id]) !== null && _val$form_id !== void 0 && _val$form_id[0]) {
      _val[form_id][0][key] = val;
      onChange === null || onChange === void 0 || onChange(_val);
    }
  };

  /**
   * @title: 渲染下拉框
   * @description:
   * @return {*}
   * @Author: zhiwei.Wang
   * @Date: 2024-01-09 14:02
   */
  var renderOptions = useCallback(function (array) {
    var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'value';
    var label = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'label';
    var type = arguments.length > 3 ? arguments[3] : undefined;
    return array.map(function (d) {
      var props = {};
      if (type === 'resource') {
        props.labelText = d.labelText;
      }
      return /*#__PURE__*/React.createElement(Select.Option, _extends({
        value: d[value],
        key: d[value]
      }, props, {
        relation_type: d.relation_type
      }), d[label]);
    });
  }, [config === null || config === void 0 ? void 0 : config.resourceErrorIcon]);

  /**
   * @title: 检查当前资源最小选择数量
   * @description:
   * @return {*}
   * @Author: zhiwei.Wang
   * @Date: 2024-09-19 21:08
   */
  var check = function check() {
    var _iterator = _createForOfIteratorHelper(data),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var _value$item$form_id;
        var item = _step.value;
        var _length = (_value$item$form_id = _value[item.form_id]) === null || _value$item$form_id === void 0 ? void 0 : _value$item$form_id.length;
        if (item.select_type.min > _length) {
          setShowError(true);
          return false;
        }
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
    return true;
  };
  useImperativeHandle(ref, function () {
    return {
      check: check
    };
  });
  var getIsAutoAllocation = function getIsAutoAllocation(id) {
    return getAutoAllocationStorage(id);
  };
  var renderItem = function renderItem(item, isOrigin) {
    var _cur$2;
    if (!item) return null;
    var disabled = isOrigin || (config === null || config === void 0 ? void 0 : config.disabled);
    var cur = isOrigin ? originValue[item.form_id] : _value[item.form_id];
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Col, {
      flex: "1 0"
    }, /*#__PURE__*/React.createElement("div", {
      className: "resource-v2 resource-col"
    }, item.select_type.type === 'multiple' ? null : /*#__PURE__*/React.createElement(Button, {
      className: classNames('resource-col-like-wrap', {
        'resource-col-like-wrap-disabled': disabled
      }, (config === null || config === void 0 ? void 0 : config.size) || 'large'),
      size: config === null || config === void 0 ? void 0 : config.size,
      onClick: function onClick() {
        var _cur$;
        if (disabled) {
          return;
        }
        setLikeStatus((cur === null || cur === void 0 || (_cur$ = cur[0]) === null || _cur$ === void 0 ? void 0 : _cur$.like_status) === 'like' ? 'common' : 'like', item.form_id, 'like_status');
      }
    }, /*#__PURE__*/React.createElement(Like, {
      status: cur === null || cur === void 0 || (_cur$2 = cur[0]) === null || _cur$2 === void 0 ? void 0 : _cur$2.like_status,
      className: "".concat(disabled ? 'like-icon-disabled' : '')
    })), /*#__PURE__*/React.createElement(MaxLengthSelect, {
      className: "resource-col-select",
      size: (config === null || config === void 0 ? void 0 : config.size) || 'large',
      maxLength: item.select_type.max,
      mode: item.select_type.type === 'multiple' ? 'multiple' : undefined,
      onChange: function onChange(e) {
        var val = e;
        if (!isArray(e)) {
          if (e || e === 0) {
            val = [e];
          }
        }
        _onChange(val, item.form_id, 'value');
      },
      value: cur === null || cur === void 0 ? void 0 : cur.map(function (d) {
        return d.relation_id;
      }),
      showSearch: true,
      filterOption: function filterOption(str, option) {
        return ((option === null || option === void 0 ? void 0 : option.labelText) || '').toLowerCase().includes((str || '').toLowerCase());
      },
      disabled: disabled
    }, renderOptions(item.renderList, 'id', config !== null && config !== void 0 && config.resourceErrorIcon ? 'label' : 'labelText', 'resource')), config !== null && config !== void 0 && config.autoAllocation ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Checkbox, {
      checked: getIsAutoAllocation(item.form_id),
      onChange: function onChange(e) {
        handleCheckAutoAllocation(item.form_id, e.target.checked);
      }
    }), /*#__PURE__*/React.createElement(Tooltip, {
      title: locales.getText('page.booking.text.resource.check-auto-allocation-tip')
    }, /*#__PURE__*/React.createElement(QuestionCircleOutlined, null))) : null)));
  };
  var renderErrors = function renderErrors(item) {
    var cur = _value[item.form_id];
    var errors = (cur || []).reduce(function (pre, d) {
      return pre.concat((d === null || d === void 0 ? void 0 : d.errors) || []);
    }, []);
    return state.renderType !== 'eventBooking' && (errors || []).map(function (d) {
      return /*#__PURE__*/React.createElement(Alert, {
        key: d.type,
        message: d.label,
        type: "warning",
        showIcon: true,
        style: {
          marginBottom: 12
        }
      });
    });
  };
  return /*#__PURE__*/React.createElement(React.Fragment, null, data.map(function (item) {
    var _cur;
    // 原资源表单信息
    var originItem = originData === null || originData === void 0 ? void 0 : originData.find(function (originDataItem) {
      return originDataItem.form_id === item.form_id;
    });
    return /*#__PURE__*/React.createElement(React.Fragment, {
      key: item.form_id
    }, /*#__PURE__*/React.createElement(Form.Item, {
      label: item.title,
      required: true,
      labelCol: config === null || config === void 0 ? void 0 : config.labelCol,
      extra: showError && item.select_type.min > ((_cur = cur) === null || _cur === void 0 ? void 0 : _cur.length) ? /*#__PURE__*/React.createElement("span", {
        style: {
          color: '#ff4d4f'
        }
      }, locales.getText('page.booking.text.resource.min-length-error')(item.select_type.min, item.title)) : undefined
    }, /*#__PURE__*/React.createElement(Row, {
      gutter: [16, 16],
      wrap: false
    }, renderItem(originItem, true), !!originItem ? /*#__PURE__*/React.createElement(Col, {
      flex: "none",
      style: {
        display: 'flex',
        alignItems: 'center'
      }
    }, /*#__PURE__*/React.createElement(Iconfont, {
      type: "pisell2-arrow-block-right",
      style: {
        fontSize: 24,
        color: '#1b1b1b'
      }
    })) : null, renderItem(item, false))), renderErrors(item));
  }));
};
export default /*#__PURE__*/forwardRef(Resources);