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 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 _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; }
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); }
import { useMemoizedFn } from 'ahooks';
import { formFieldFilterFuncMap } from "../../fields/utils";
import { isArr, isJson, isString } from '@pisell/utils';
import dayjs from 'dayjs';
// 过滤条件操作符 https://docs-cn.nocobase.com/api/database/operators
var filterOperatorArr = ['$eq', '$ne', '$is', '$not', '$col', '$in', '$notIn', '$empty', '$notEmpty', '$and', '$or', '$isFalsy', '$isTruly', '$gt', '$gte', '$lt', '$lte', '$between', '$notBetween', '$includes', '$notIncludes', '$startsWith', '$notStatsWith', '$endsWith', '$notEndsWith', '$like', '$notLike', '$iLike', '$notILike', '$regexp', '$notRegexp', '$iRegexp', '$notIRegexp', '$dateOn', '$dateNotOn', '$dateBefore', '$dateNotBefore', '$dateAfter', '$dateNotAfter', '$match', '$notMatch', '$anyOf', '$noneOf', '$arrayEmpty', '$arrayNotEmpty', '$exists', '$notExists'];

// 转换过滤条件
var formatFilter = function formatFilter(filterValue, fields) {
  var conditions = [];
  if (!filterValue || !(fields !== null && fields !== void 0 && fields.length)) {
    return JSON.stringify({});
  }
  if (isString(filterValue)) {
    return filterValue;
  }

  // 处理关键字搜索
  if (filterValue._keywords) {
    var keywordFields = fields.filter(function (item) {
      return ['string', 'number', 'text'].includes(item.type);
    }).map(function (item) {
      return _defineProperty({}, item.name, {
        $includes: filterValue._keywords
      });
    });
    if (keywordFields.length > 0) {
      conditions.push({
        $or: keywordFields
      });
    }
  }
  var fieldsMap = fields.reduce(function (acc, field) {
    if (field.name) {
      acc[field.name] = field;
    }
    return acc;
  }, {});

  // 处理其他过滤条件
  var normalConditions = [];
  Object.entries(filterValue).forEach(function (_ref2) {
    var _field$uiSchema;
    var _ref3 = _slicedToArray(_ref2, 2),
      key = _ref3[0],
      value = _ref3[1];
    if (key === '_keywords' || value === undefined || value === null || value === '' || isArr(value) && value.length === 0) {
      return;
    }

    // 判断value是否包含filterOperatorArr中的元素
    if (isString(value) && filterOperatorArr.some(function (item) {
      return value.includes(item);
    })) {
      if (isJson(value)) {
        conditions.push(_defineProperty({}, key, JSON.parse(value)));
      }
      return;
    }
    var field = fieldsMap[key];
    if (!(field !== null && field !== void 0 && (_field$uiSchema = field.uiSchema) !== null && _field$uiSchema !== void 0 && _field$uiSchema['x-component'])) {
      return;
    }
    var filterFunc = formFieldFilterFuncMap[field.uiSchema['x-component']];
    if (!filterFunc) {
      return;
    }
    var condition = filterFunc(value, field);
    if (condition) {
      normalConditions.push(_defineProperty({}, key, condition));
    }
  });
  if (normalConditions.length > 0) {
    conditions.push({
      $and: normalConditions
    });
  }
  var filterCondition = conditions.length ? {
    $and: conditions
  } : {};
  return JSON.stringify(filterCondition);
};

// 转换排序条件
var formatSort = function formatSort(sortValue) {
  if (!sortValue) return undefined;
  var _sortValue$split = sortValue.split(':'),
    _sortValue$split2 = _slicedToArray(_sortValue$split, 2),
    field = _sortValue$split2[0],
    order = _sortValue$split2[1];
  var prefix = order === 'desc' ? '-' : '';
  return ["".concat(prefix).concat(field)];
};
var formatCreateUpdateParamsUtils = function formatCreateUpdateParamsUtils(params, fields) {
  if (!params || !(fields !== null && fields !== void 0 && fields.length)) {
    return params;
  }
  var formattedParams = _objectSpread({}, params);
  fields.forEach(function (field) {
    var _field$uiSchema2;
    var fieldName = field.name;
    var value = params[fieldName];
    if (((_field$uiSchema2 = field.uiSchema) === null || _field$uiSchema2 === void 0 ? void 0 : _field$uiSchema2['x-component']) === 'TimePicker' && value) {
      // 处理dayjs对象
      if (dayjs.isDayjs(value)) {
        formattedParams[fieldName] = value.format('HH:mm:ss');
      } else if (isString(value)) {
        var _timeArr$, _timeArr$2, _timeArr$3;
        var timeArr = value.split(':');
        var hours = ((_timeArr$ = timeArr[0]) === null || _timeArr$ === void 0 ? void 0 : _timeArr$.padStart(2, '0')) || '00';
        var minutes = ((_timeArr$2 = timeArr[1]) === null || _timeArr$2 === void 0 ? void 0 : _timeArr$2.padStart(2, '0')) || '00';
        var seconds = ((_timeArr$3 = timeArr[2]) === null || _timeArr$3 === void 0 ? void 0 : _timeArr$3.padStart(2, '0')) || '00';
        formattedParams[fieldName] = "".concat(hours, ":").concat(minutes, ":").concat(seconds);
      }
    }
  });
  return formattedParams;
};
var customApiFormatFilter = function customApiFormatFilter(filter) {
  return _objectSpread({}, filter);
};

// 数据格式化
var useFormat = function useFormat(_ref4) {
  var dataSourceKey = _ref4.dataSourceKey,
    fields = _ref4.fields;
  // list接口请求 结果格式化
  var formatListResult = useMemoizedFn(function (res) {
    if (dataSourceKey === 'pisell2-api' && 'list' in res && 'page' in res) {
      return {
        data: res.list,
        count: res.count,
        page: res.page,
        pageSize: res.size
      };
    }
    if (dataSourceKey === 'mypisell-api' && 'list' in res && 'skip' in res) {
      var skip = typeof res.skip === 'number' ? res.skip : 1;
      return {
        data: res.list,
        count: res.count,
        page: skip - 1 || 1,
        pageSize: res.size
      };
    }
    if ('meta' in res) {
      return {
        data: res.data,
        count: res.meta.count,
        page: res.meta.page,
        pageSize: res.meta.pageSize
      };
    }
    return res;
  });

  // list接口请求 参数格式化
  var formatListParams = useMemoizedFn(function (params) {
    // 如果dataSourceKey为空 pisell2 main  则为标准数据源
    if (!dataSourceKey || ['pisell2', 'main'].includes(dataSourceKey)) {
      return _objectSpread(_objectSpread({}, params), {}, {
        filter: formatFilter(params.filter, fields),
        sort: formatSort(params.sort)
      });
    }
    if (dataSourceKey === 'pisell2-api') {
      return _objectSpread({
        page: (params === null || params === void 0 ? void 0 : params.page) || 1,
        size: (params === null || params === void 0 ? void 0 : params.pageSize) || 10
      }, customApiFormatFilter(params.filter || {}));
    }
    if (dataSourceKey === 'mypisell-api') {
      return _objectSpread({
        skip: (params === null || params === void 0 ? void 0 : params.page) || 1,
        num: (params === null || params === void 0 ? void 0 : params.pageSize) || 10
      }, customApiFormatFilter(params.filter || {}));
    }
    return params;
  });
  var formatCreateUpdateParams = useMemoizedFn(function (params) {
    if (!dataSourceKey) {
      return formatCreateUpdateParamsUtils(params, fields);
    }
    return params;
  });
  return {
    formatListResult: formatListResult,
    formatListParams: formatListParams,
    formatCreateUpdateParams: formatCreateUpdateParams
  };
};
export default useFormat;