"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useFieldFetchData = exports.proFieldParsingValueEnumToArray = exports.proFieldParsingText = exports.default = exports.ObjToMap = void 0;
require("core-js/modules/es.array.iterator.js");
require("core-js/modules/web.dom-collections.iterator.js");
require("core-js/modules/es.regexp.exec.js");
require("core-js/modules/es.promise.js");
require("core-js/modules/es.array.reduce.js");
var _react = _interopRequireWildcard(require("react"));
var _swr = _interopRequireDefault(require("swr"));
var _useMergedState = _interopRequireDefault(require("rc-util/es/hooks/useMergedState"));
var _SizeContext = _interopRequireDefault(require("antd/es/config-provider/SizeContext"));
var _omit = _interopRequireDefault(require("omit.js"));
var _spin = _interopRequireDefault(require("../spin"));
var _space = _interopRequireDefault(require("../space"));
var _select = _interopRequireDefault(require("../select"));
var _wauProvider = require("../wau-provider");
var _utils = require("../utils");
var _lightSelect = _interopRequireDefault(require("./light-select"));
var _wauStatusField = _interopRequireWildcard(require("../wau-status-field"));
require("./style");
var _jsxRuntime = require("react/jsx-runtime");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
let testId = 0;
const ObjToMap = value => {
  if (getType(value) === 'map') {
    return value;
  }
  return new Map(Object.entries(value || {}));
};

/**
 * 转化 text 和 valueEnum 通过 type 来添加 Status
 *
 * @param text
 * @param valueEnum
 * @param pure 纯净模式，不增加 status
 */
exports.ObjToMap = ObjToMap;
const proFieldParsingText = (text, valueEnumParams) => {
  if (Array.isArray(text)) {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_space.default, {
      children: text.map(value =>
      /*#__PURE__*/
      // @ts-ignore
      (0, _jsxRuntime.jsx)(_react.default.Fragment, {
        children: proFieldParsingText(value, valueEnumParams)
      }, (value === null || value === void 0 ? void 0 : value.value) || value))
    });
  }
  const valueEnum = ObjToMap(valueEnumParams);
  if (!valueEnum.has(text) && !valueEnum.has(`${text}`)) {
    // @ts-ignore
    return (text === null || text === void 0 ? void 0 : text.label) || text;
  }
  const domText = valueEnum.get(text) || valueEnum.get(`${text}`);
  if (!domText) {
    // @ts-ignore
    return (text === null || text === void 0 ? void 0 : text.label) || text;
  }
  const {
    status,
    color
  } = domText;
  const Status = _wauStatusField.default[status || 'Init'];
  // 如果类型存在优先使用类型
  if (Status) {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(Status, {
      children: domText.text
    });
  }

  // 如果不存在使用颜色
  if (color) {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_wauStatusField.ProFieldBadgeColor, {
      color: color,
      children: domText.text
    });
  }
  // 什么都没有使用 text
  return domText.text || domText;
};

/**
 * 获取类型的 type
 *
 * @param obj
 */
exports.proFieldParsingText = proFieldParsingText;
function getType(obj) {
  // @ts-ignore
  const type = Object.prototype.toString.call(obj).match(/^\[object (.*)\]$/)[1].toLowerCase();
  if (type === 'string' && typeof obj === 'object') return 'object'; // Let "new String('')" return 'object'
  if (obj === null) return 'null'; // PhantomJS has type "DOMWindow" for null
  if (obj === undefined) return 'undefined'; // PhantomJS has type "DOMWindow" for undefined
  return type;
}

/**
 * 把 value 的枚举转化为数组
 *
 * @param valueEnum
 */
const proFieldParsingValueEnumToArray = (valueEnumParams = new Map()) => {
  const enumArray = [];
  const valueEnum = ObjToMap(valueEnumParams);
  valueEnum.forEach((_, key) => {
    const value = valueEnum.get(key) || valueEnum.get(`${key}`);
    if (!value) {
      return;
    }
    if (typeof value === 'object' && value !== null && value !== void 0 && value.text) {
      enumArray.push({
        text: value === null || value === void 0 ? void 0 : value.text,
        value: key,
        disabled: value.disabled
      });
      return;
    }
    enumArray.push({
      text: value,
      value: key
    });
  });
  return enumArray;
};
exports.proFieldParsingValueEnumToArray = proFieldParsingValueEnumToArray;
const useFieldFetchData = props => {
  var _props$fieldProps;
  /** Key 是用来缓存请求的，如果不在是有问题 */
  const [cacheKey] = (0, _react.useState)(() => {
    if (props.proFieldKey) {
      return props.proFieldKey;
    }
    if (props.request) {
      testId += 1;
      return testId;
    }
    return 'no-fetch';
  });
  const proFieldKeyRef = (0, _react.useRef)(cacheKey);
  const getOptionsFormValueEnum = (0, _react.useCallback)(valueEnum => {
    return proFieldParsingValueEnumToArray(ObjToMap(valueEnum)).map(({
      value,
      text,
      ...rest
    }) => ({
      label: text,
      value,
      key: value,
      ...rest
    }));
  }, []);
  const [options, setOptions] = (0, _useMergedState.default)(() => {
    if (props.valueEnum) {
      return getOptionsFormValueEnum(props.valueEnum);
    }
    return [];
  }, {
    value: (_props$fieldProps = props.fieldProps) === null || _props$fieldProps === void 0 ? void 0 : _props$fieldProps.options
  });
  (0, _utils.useDeepCompareEffect)(() => {
    var _props$fieldProps2;
    // 优先使用 fieldProps?.options
    if (!props.valueEnum || (_props$fieldProps2 = props.fieldProps) !== null && _props$fieldProps2 !== void 0 && _props$fieldProps2.options) return;
    setOptions(getOptionsFormValueEnum(props.valueEnum));
  }, [props.valueEnum]);
  const [loading, setLoading] = (0, _react.useState)(false);
  const {
    data,
    mutate
  } = (0, _swr.default)([proFieldKeyRef.current, JSON.stringify(props.params)], async () => {
    if (props.request) {
      setLoading(true);
      const fetchData = await props.request(props.params, props);
      setLoading(false);
      return fetchData;
    }
    return [];
  }, {
    revalidateOnFocus: false
  });
  return [loading, props.request ? data : options, async () => {
    if (!props.request) return;
    setLoading(true);
    const fetchData = await props.request(props.params, props);
    setLoading(false);
    mutate(fetchData, false);
  }];
};

/**
 * 可以根据 valueEnum 来进行类型的设置
 *
 * @param
 */
exports.useFieldFetchData = useFieldFetchData;
const FieldSelect = (props, ref) => {
  const {
    mode,
    valueEnum,
    render,
    renderFormItem,
    fieldProps,
    light,
    // eslint-disable-next-line
    proFieldKey,
    ...rest
  } = props;
  const inputRef = (0, _react.useRef)();
  const intl = (0, _wauProvider.useIntl)();
  (0, _react.useEffect)(() => {
    testId += 1;
  }, []);
  const [loading, options, fetchData] = useFieldFetchData(props);
  const size = (0, _react.useContext)(_SizeContext.default);
  (0, _react.useImperativeHandle)(ref, () => ({
    ...(inputRef.current || {}),
    fetchData: () => fetchData()
  }));
  if (loading) {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_spin.default, {});
  }
  if (mode === 'read') {
    var _rest$text;
    const optionsValueEnum = options !== null && options !== void 0 && options.length ? options === null || options === void 0 ? void 0 : options.reduce((pre, cur) => {
      return {
        ...pre,
        [cur.value]: cur.label
      };
    }, {}) : undefined;
    // 如果有 label 直接就用 label
    // @ts-ignore
    if ((_rest$text = rest.text) !== null && _rest$text !== void 0 && _rest$text.label) {
      var _rest$text2;
      // @ts-ignore
      return (_rest$text2 = rest.text) === null || _rest$text2 === void 0 ? void 0 : _rest$text2.label;
    }
    const dom = /*#__PURE__*/(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
      children: proFieldParsingText(rest.text, ObjToMap(valueEnum || optionsValueEnum))
    });
    if (render) {
      return render(rest.text, {
        mode,
        ...fieldProps
      }, dom) || null;
    }
    return dom;
  }
  if (mode === 'edit' || mode === 'update') {
    const renderDom = () => {
      if (light) {
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(_lightSelect.default, {
          loading: loading,
          ref: inputRef,
          allowClear: true,
          size: size,
          ...(0, _omit.default)(rest, ['request']),
          options: options,
          ...fieldProps
        });
      }
      return /*#__PURE__*/(0, _jsxRuntime.jsx)(_select.default, {
        style: {
          minWidth: 100
        },
        loading: loading,
        ref: inputRef,
        allowClear: true,
        ...(0, _omit.default)(rest, ['request']),
        placeholder: intl.getMessage('tableForm.selectPlaceholder', '请选择'),
        options: options,
        ...fieldProps
      });
    };
    const dom = renderDom();
    if (renderFormItem) {
      return renderFormItem(rest.text, {
        mode,
        ...fieldProps,
        options
      }, dom) || null;
    }
    return dom;
  }
  return null;
};
var _default = /*#__PURE__*/_react.default.forwardRef(FieldSelect);
exports.default = _default;