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); }
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 _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 = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
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(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
import { useMemoizedFn } from 'ahooks';
import { formFieldFilterFuncMap } from "../../fields/utils";
import { isArr, isString } from '@pisell/utils';
import dayjs from 'dayjs';
// 转换过滤条件
var formatFilter = function formatFilter(filterValue, fields) {
  var conditions = [];
  if (!filterValue || !(fields !== null && fields !== void 0 && fields.length)) {
    return JSON.stringify({});
  }

  // 处理关键字搜索
  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;
    }
    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) {
      return {
        data: res.list,
        count: res.count,
        page: res.page,
        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为空 则为标准数据源
    if (!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 || {}));
    }
    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;