"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.renderColumnsTitle = exports.renderCell = void 0;

var _react = _interopRequireDefault(require("react"));

var _utils = require("@teamix/utils");

var _actions = require("../../actions");

var _field = _interopRequireWildcard(require("../../field"));

var _Filter = _interopRequireDefault(require("../components/Filter"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(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; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

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; }

/**
 * 增加了 icon 的功能 render title
 */
var renderColumnsTitle = function renderColumnsTitle(item, actionRef) {
  var filterMode = item.filterMode,
      filters = item.filters,
      dataSource = item.dataSource,
      dataIndex = item.dataIndex,
      valueType = item.valueType; // 为列过滤添加状态标题

  var getItemLabel = function getItemLabel() {
    if (filters && filterMode !== 'multiple') {
      var _actionRef$current$ge, _actionRef$current, _actionRef$current$ge2;

      var selectedItem = (_actionRef$current$ge = (_actionRef$current = actionRef.current) === null || _actionRef$current === void 0 ? void 0 : (_actionRef$current$ge2 = _actionRef$current.getState) === null || _actionRef$current$ge2 === void 0 ? void 0 : _actionRef$current$ge2.call(_actionRef$current).filterRules) !== null && _actionRef$current$ge !== void 0 ? _actionRef$current$ge : {};

      if (Object.keys(selectedItem).length > 0) {
        var _selectedItem$dataInd;

        if ((_selectedItem$dataInd = selectedItem[dataIndex]) === null || _selectedItem$dataInd === void 0 ? void 0 : _selectedItem$dataInd.params) {
          var _targetFilters$find;

          // 找到对应的 label
          var targetFilters = filters !== null && filters !== void 0 ? filters : [];

          if (filters === true) {
            targetFilters = dataSource !== null && dataSource !== void 0 ? dataSource : [];
          }

          var label = (_targetFilters$find = targetFilters.find(function (item) {
            var _selectedItem$dataInd2;

            return item.value === ((_selectedItem$dataInd2 = selectedItem[dataIndex]) === null || _selectedItem$dataInd2 === void 0 ? void 0 : _selectedItem$dataInd2.params);
          })) === null || _targetFilters$find === void 0 ? void 0 : _targetFilters$find.label;
          var value = "".concat(item.title, " (").concat(label, ")");
          return /*#__PURE__*/_react.default.createElement(_field.default, {
            style: {
              display: 'inline-flex'
            },
            value: value,
            type: "text",
            render: {
              ellipsis: true,
              color: 'var(--table-th-color,#848484)'
            }
          });
        }
      }
    }

    return /*#__PURE__*/_react.default.createElement(_field.default, {
      style: {
        display: 'inline-flex'
      },
      value: item.title,
      type: "text",
      render: {
        ellipsis: true,
        color: 'var(--table-th-color,#848484)'
      }
    });
  };

  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_field.LabelIconTip, {
    label: item.title,
    tooltip: item.tooltip,
    icon: item.tooltipIcon
  }), item.filters && /*#__PURE__*/_react.default.createElement(_Filter.default, {
    column: item,
    actionRef: actionRef
  }));
};
/**
 * 负责单元格的具体渲染
 */


exports.renderColumnsTitle = renderColumnsTitle;

var renderCell = function renderCell(value, item, index, record, actionRef,
/** 接收外部比如 dialog-table 传过来的 context，用于弹窗关闭等 */
context, // 用于埋点
dataTeamixSpm) {
  var _actionSchema$actions;

  var _item$valueType = item.valueType,
      valueType = _item$valueType === void 0 ? 'text' : _item$valueType,
      render = item.render,
      actionSchema = item.actionSchema,
      dataIndex = item.dataIndex,
      format = item.format; // 如果没传 dataIndex，返回 null

  if (!dataIndex) {
    value = null;
  } // 处理 dataIndex 为数组的情况


  if (Array.isArray(dataIndex)) {
    value = dataIndex.map(function (item) {
      return (0, _utils.getTargetValue)("{{".concat(item, "}}"), _objectSpread(_objectSpread({}, record), {}, {
        record: record
      }));
    });
  }

  var newRender = null;
  var newDataSource = null;
  var props = item.props; // 如果 render 直接传函数

  if (typeof render === 'function') {
    newRender = function newRender() {
      return render === null || render === void 0 ? void 0 : render(value, index, record);
    };
  } else {
    newRender = processBuriedPoint(processRenderFunction(render, value, index, record), record, value, index);

    if (valueType === 'selectGroup') {
      newRender = _objectSpread(_objectSpread({
        maxShowNumber: 'auto',
        foldText: 'more',
        editOnClick: function editOnClick() {},
        edit: true
      }, newRender), {}, {
        ellipsis: false
      });
      props = _objectSpread({
        valueAlias: {
          value: 'TagValue',
          key: 'TagKey'
        }
      }, props);
    }

    if ((render === null || render === void 0 ? void 0 : render.type) === 'step') {
      newRender = _objectSpread(_objectSpread({}, newRender), {}, {
        ellipsis: false
      });
    }
  } // 渲染操作组


  if (actionSchema && ((_actionSchema$actions = actionSchema.actions) === null || _actionSchema$actions === void 0 ? void 0 : _actionSchema$actions.length)) {
    // 默认 context
    var defaultContext = _objectSpread({
      value: value,
      index: index,
      record: record,
      action: actionRef.current
    }, context);

    return /*#__PURE__*/_react.default.createElement(_actions.ProActionGroup, _objectSpread(_objectSpread({
      type: "text"
    }, actionSchema), {}, {
      context: _objectSpread(_objectSpread({}, defaultContext), actionSchema.context),
      "data-teamix-spm": dataTeamixSpm ? "".concat(dataTeamixSpm, "-columnAction") : undefined
    }));
  } // dataSource可传函数


  if (typeof item.dataSource === 'function') {
    var _item$dataSource;

    newDataSource = (_item$dataSource = item.dataSource) === null || _item$dataSource === void 0 ? void 0 : _item$dataSource.call(item, value, index, record);
  } else {
    var _item$dataSource2;

    newDataSource = ((_item$dataSource2 = item.dataSource) !== null && _item$dataSource2 !== void 0 ? _item$dataSource2 : []).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, (0, _utils.getTargetValue)(v, _objectSpread(_objectSpread({}, record), {}, {
          record: record,
          value: value,
          index: index
        }))];
      }));
    });
  } // 渲染 ProField


  return /*#__PURE__*/_react.default.createElement(_field.default, _objectSpread({
    type: valueType || 'text',
    value: value,
    render: newRender,
    dataSource: newDataSource,
    format: format
  }, props));
};
/**
 * 处理 render 配置项是函数的情况
 * @param render ProFieldRender
 * @param value table cell value
 * @param index table cell index
 * @param record table cell record
 * @returns
 */


exports.renderCell = renderCell;

var processRenderFunction = function processRenderFunction() {
  var render = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var value = arguments.length > 1 ? arguments[1] : undefined;
  var index = arguments.length > 2 ? arguments[2] : undefined;
  var record = arguments.length > 3 ? arguments[3] : undefined;
  // 当 ProField render 类型为 function 时。需要表格预先处理以塞入 record
  var external = ['linkOnClick', 'link', 'value', 'renderEdit', 'descriptionRenderEdit', 'editPopConfirmProps', 'descriptionEditPopConfirmProps', 'editOnClick', 'descriptionEditOnClick', 'extra', 'prefixExtra'];
  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, index, record].concat(others));
        }];
      }

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

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


var processBuriedPoint = function processBuriedPoint() {
  var render = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var record = arguments.length > 1 ? arguments[1] : undefined;
  var value = arguments.length > 2 ? arguments[2] : undefined;
  var index = arguments.length > 3 ? arguments[3] : undefined;
  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, (0, _utils.getTargetValue)(v, _objectSpread(_objectSpread({}, record), {}, {
      record: record,
      value: value,
      index: index
    }))];
  }))));
};