var _excluded = ["type", "value", "render", "infoItem", "record", "actionRef", "dataSource", "context", "props"];

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 _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(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

import TeamixIcon from '@teamix/icon';
import ProField from '../../../field';
import { usePrefixCls, getTargetValue, request } from '@teamix/utils';
import PopConfirm from '@teamix/pop-confirm';
import React, { useMemo, useState } from 'react';
import './index.scss';
import ProForm, { createForm, formilyReactive } from '../../../form';
import { Message } from '@alicloudfe/components';
import { ProActionGroup } from '../../../actions';
var cls = usePrefixCls('teamix-pro-info');
var toJS = formilyReactive.toJS;

var InfoValueItem = function InfoValueItem(props) {
  var _props$type = props.type,
      type = _props$type === void 0 ? 'text' : _props$type,
      value = props.value,
      render = props.render,
      infoItem = props.infoItem,
      record = props.record,
      actionRef = props.actionRef,
      dataSource = props.dataSource,
      context = props.context,
      fieldProps = props.props,
      others = _objectWithoutProperties(props, _excluded);

  var dataIndex = infoItem.dataIndex,
      isEdit = infoItem.isEdit,
      editOnCancel = infoItem.editOnCancel,
      editOnOk = infoItem.editOnOk,
      editUrl = infoItem.editUrl,
      editFormatParams = infoItem.editFormatParams,
      _infoItem$editMethod = infoItem.editMethod,
      editMethod = _infoItem$editMethod === void 0 ? 'post' : _infoItem$editMethod,
      _infoItem$successMess = infoItem.successMessage,
      successMessage = _infoItem$successMess === void 0 ? 'success' : _infoItem$successMess,
      actions = infoItem.actions,
      extra = infoItem.extra,
      valueType = infoItem.valueType,
      _infoItem$editProForm = infoItem.editProFormProps,
      editProFormProps = _infoItem$editProForm === void 0 ? {} : _infoItem$editProForm; // 获取配置

  var getInfoItemProps = function getInfoItemProps(prop) {
    if (typeof prop === 'function') {
      return prop === null || prop === void 0 ? void 0 : prop(value, record);
    }

    return prop;
  }; // 获取处理过的 render


  var getRender = function getRender() {
    var _processRenderFunctio;

    if (typeof render === 'function') {
      return function () {
        return render(value, record);
      };
    }

    var newRender = processBuriedPoint((_processRenderFunctio = processRenderFunction(render !== null && render !== void 0 ? render : {}, value, record)) !== null && _processRenderFunctio !== void 0 ? _processRenderFunctio : {}, value, record);

    if (valueType === 'selectGroup') {
      newRender = _objectSpread(_objectSpread({
        maxShowNumber: 'auto',
        foldText: 'more'
      }, newRender), {}, {
        ellipsis: false
      });
    }

    return newRender;
  };

  var getFieldProps = function getFieldProps() {
    if (valueType === 'selectGroup') {
      return _objectSpread({
        valueAlias: {
          value: 'TagValue',
          key: 'TagKey'
        },
        layout: 'compact'
      }, fieldProps);
    }

    return fieldProps;
  }; // 获取处理过的 dataSource


  var getDataSource = function getDataSource() {
    var newDataSource = null;

    if (typeof dataSource === 'function') {
      newDataSource = dataSource === null || dataSource === void 0 ? void 0 : dataSource(value, record);
    } else {
      newDataSource = (dataSource !== null && dataSource !== void 0 ? dataSource : []).map(function (item) {
        return Object.fromEntries(Object.entries(item).map(function (_ref) {
          var _ref2 = _slicedToArray(_ref, 2),
              k = _ref2[0],
              v = _ref2[1];

          return [k, getTargetValue(v, _objectSpread(_objectSpread({}, record), {}, {
            value: value
          }, context))];
        }));
      });
    }

    return newDataSource;
  }; // 浮层的显隐状态


  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      popConfirmVisible = _useState2[0],
      setPopConfirmVisible = _useState2[1]; // 确认按钮的loading状态


  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      confirmLoading = _useState4[0],
      setConfirmLoading = _useState4[1]; // edit 的显隐状态


  var _useState5 = useState(false),
      _useState6 = _slicedToArray(_useState5, 2),
      editVisible = _useState6[0],
      setEditVisible = _useState6[1];

  var requestDataKey = editMethod.toLowerCase() === 'get' ? 'params' : 'data';
  var dataFilterForm = useMemo(function () {
    return createForm();
  }, []);

  var renderAction = function renderAction() {
    if (actions) {
      return /*#__PURE__*/React.createElement(ProActionGroup, {
        actions: actions,
        type: "text",
        style: {
          marginLeft: '8px'
        },
        context: _objectSpread({}, context)
      });
    }

    return /*#__PURE__*/React.createElement(React.Fragment, null);
  };
  /**
   * 处理 render 配置项是函数的情况
   * @param render ProFieldRender
   * @param value table cell value
   * @param record table cell record
   * @returns
   */


  var processRenderFunction = function processRenderFunction(render, value, record) {
    var external = ['linkOnClick', 'link', 'value'];
    return Object.fromEntries(Object.entries(render).map(function (_ref3) {
      var _ref4 = _slicedToArray(_ref3, 2),
          k = _ref4[0],
          v = _ref4[1];

      if (typeof v === 'function') {
        var _v;

        if (external.includes(k)) {
          return [k, function () {
            for (var _len = arguments.length, others = new Array(_len), _key = 0; _key < _len; _key++) {
              others[_key] = arguments[_key];
            }

            return v === null || v === void 0 ? void 0 : v.apply(void 0, [value, record].concat(others));
          }];
        }

        return [k, (_v = v === null || v === void 0 ? void 0 : v(value, record)) !== null && _v !== void 0 ? _v : ''];
      }

      return [k, v];
    }));
  };
  /**
   * 处理 render 数据，取出 {{xxx}} 匹配值
   * @param render ProFieldRender
   * @param record table cell record
   * @returns
   */


  var processBuriedPoint = function processBuriedPoint(render, value, record) {
    return Object.fromEntries([// 默认 ellipsis、descriptionEllipsis 为 true
    // emptyText 默认为 '-'
    ['ellipsis', true], ['descriptionEllipsis', true], ['emptyText', '-']].concat(_toConsumableArray(Object.entries(render).map(function (_ref5) {
      var _ref6 = _slicedToArray(_ref5, 2),
          k = _ref6[0],
          v = _ref6[1];

      return [k, getTargetValue(v, _objectSpread(_objectSpread({}, record), {}, {
        record: record,
        value: value
      }))];
    }))));
  }; // 重写编辑逻辑替代field原有逻辑


  if (getInfoItemProps(isEdit)) {
    // 渲染表单
    var renderContent = function renderContent() {
      return /*#__PURE__*/React.createElement(ProForm, _objectSpread({
        schema: [{
          name: dataIndex,
          component: 'Input',
          required: true,
          default: value
        }],
        form: dataFilterForm
      }, getInfoItemProps(editProFormProps)));
    }; // 表单提交


    var onConfirm = function onConfirm(e) {
      var formData = toJS(dataFilterForm.values); // 如果传入了 editUrl 则内置请求

      if (editUrl) {
        setConfirmLoading(true);
        var params = formData;

        if (editFormatParams) {
          params = editFormatParams === null || editFormatParams === void 0 ? void 0 : editFormatParams(formData, record);
        }

        request(_defineProperty({
          url: editUrl,
          method: editMethod
        }, requestDataKey, params)).then(function (resp) {
          var _actionRef$current, _actionRef$current$re;

          Message.success(successMessage);
          actionRef === null || actionRef === void 0 ? void 0 : (_actionRef$current = actionRef.current) === null || _actionRef$current === void 0 ? void 0 : (_actionRef$current$re = _actionRef$current.refresh) === null || _actionRef$current$re === void 0 ? void 0 : _actionRef$current$re.call(_actionRef$current); // setEditVisible(!editVisible);
        }).catch(function (error) {// TODO 暂时不处理。是否需要开放函数？
        }).finally(function () {// setConfirmLoading(false);
        });
      }

      var okResult = editOnOk === null || editOnOk === void 0 ? void 0 : editOnOk(formData, e); // 重写了 editOnOk

      if (okResult instanceof Promise) {
        setConfirmLoading(true);
        okResult.then(function () {
          setPopConfirmVisible(!popConfirmVisible);
          setEditVisible(!editVisible);
          setConfirmLoading(false);
        });
      } else {
        setPopConfirmVisible(!popConfirmVisible);
        setEditVisible(!editVisible);
      }
    }; // 取消


    var onCancel = function onCancel(e) {
      var formData = toJS(dataFilterForm.values);

      if (editOnCancel) {
        editOnCancel === null || editOnCancel === void 0 ? void 0 : editOnCancel(formData, e);
        setPopConfirmVisible(!popConfirmVisible);
        setEditVisible(!editVisible);
      } else {
        setPopConfirmVisible(!popConfirmVisible);
        setEditVisible(!editVisible);
      }
    };

    return /*#__PURE__*/React.createElement("div", {
      className: cls('edit'),
      onMouseEnter: function onMouseEnter() {
        setEditVisible(true);
      },
      onMouseLeave: function onMouseLeave() {
        setEditVisible(false);
      }
    }, /*#__PURE__*/React.createElement(ProField, _objectSpread(_objectSpread({
      type: type,
      value: value,
      render: getRender(),
      dataSource: getDataSource()
    }, others), getFieldProps())), /*#__PURE__*/React.createElement(PopConfirm, {
      visible: popConfirmVisible,
      content: renderContent(),
      triggerType: "click",
      popupClassName: cls('edit-pop-confirm'),
      onConfirm: onConfirm,
      onCancel: onCancel,
      confirmProps: {
        loading: confirmLoading
      },
      trigger: /*#__PURE__*/React.createElement(TeamixIcon, {
        type: "edit-line",
        size: "small",
        className: cls('edit-icon'),
        // 这里使用 opacity 是为了占位
        style: {
          opacity: editVisible || popConfirmVisible ? 1 : 0
        },
        onClick: function onClick() {
          setPopConfirmVisible(!popConfirmVisible);
        }
      })
    }), renderAction(), extra && extra);
  }

  return /*#__PURE__*/React.createElement("div", {
    className: cls('item-value')
  }, /*#__PURE__*/React.createElement(ProField, _objectSpread(_objectSpread({
    type: type,
    value: value,
    render: getRender(),
    dataSource: getDataSource()
  }, others), getFieldProps())), renderAction(), extra && extra);
};

export default InfoValueItem;