"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

var __assign = void 0 && (void 0).__assign || function () {
  __assign = Object.assign || function (t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];

      for (var p in s) {
        if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
      }
    }

    return t;
  };

  return __assign.apply(this, arguments);
};

var __createBinding = void 0 && (void 0).__createBinding || (Object.create ? function (o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  Object.defineProperty(o, k2, {
    enumerable: true,
    get: function get() {
      return m[k];
    }
  });
} : function (o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  o[k2] = m[k];
});

var __setModuleDefault = void 0 && (void 0).__setModuleDefault || (Object.create ? function (o, v) {
  Object.defineProperty(o, "default", {
    enumerable: true,
    value: v
  });
} : function (o, v) {
  o["default"] = v;
});

var __importStar = void 0 && (void 0).__importStar || function (mod) {
  if (mod && mod.__esModule) return mod;
  var result = {};
  if (mod != null) for (var k in mod) {
    if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  }

  __setModuleDefault(result, mod);

  return result;
};

var __spreadArray = void 0 && (void 0).__spreadArray || function (to, from) {
  for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) {
    to[j] = from[i];
  }

  return to;
};

var __importDefault = void 0 && (void 0).__importDefault || function (mod) {
  return mod && mod.__esModule ? mod : {
    "default": mod
  };
};

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

var jsx_runtime_1 = require("react/jsx-runtime");

var React = __importStar(require("react"));

var lodash_1 = require("lodash");

var icon_1 = __importDefault(require("../../../icon"));

var date_picker_1 = __importDefault(require("../../../date-picker"));

var input_1 = require("../../../input");

var react_use_1 = require("react-use");

var checkbox_1 = __importDefault(require("../../../checkbox"));

var radio_1 = __importDefault(require("../../../radio"));

var spin_1 = __importDefault(require("../../../spin"));

var dayjs_1 = __importDefault(require("dayjs"));

var isNull_1 = __importDefault(require("lodash/isNull"));

var enum_1 = require("../../enum");

var constants_1 = require("../../constants");

var Tiled_1 = require("./Tiled");

exports.FIELD_ROW_HEIGHT = 28;
var DEAFAULT_DISPLAY_NUM = 25; //如果是字符串，那就格式化{label: string, value: string}
//如果是null， 就按空值处理
//如果是object， 就直接返回

var formatLabelValue = function formatLabelValue(arr, emptyVal) {
  return lodash_1.map(arr, function (it) {
    return (0, _typeof2["default"])(it) === 'object' ? isNull_1["default"](it) ? {
      label: emptyVal,
      value: it
    } : it : {
      label: it,
      value: it
    };
  });
};

exports.formatLabelValue = formatLabelValue;
var TiledFieldItem = React.memo(function (_a) {
  var field = _a.field,
      fieldFilter = _a.fieldFilter,
      changeItem = _a.changeItem,
      options = _a.options,
      textLabels = _a.textLabels,
      renderRestLabel = _a.renderRestLabel;
  var type = field.type,
      hiddenCustom = field.hiddenCustom,
      mode = field.mode,
      isCombined = field.isCombined;
  var isNum = type === enum_1.FieldType.number;
  var isDatetime = type === enum_1.FieldType.datetime;
  var isText = type === enum_1.FieldType.text;

  var _b = React.useState(false),
      valLoading = _b[0],
      setValLoading = _b[1];

  var _c = react_use_1.useToggle(false),
      isExpand = _c[0],
      setIsExpand = _c[1];

  var _d = react_use_1.useMeasure(),
      filterWrapperRef = _d[0],
      filterHeight = _d[1].height;

  var originOptionsRef = React.useRef();
  var filterItemTemplate = lodash_1.pick(field.detail, ['db', 'hType', 'hValue']);
  React.useEffect(function () {
    if (isDatetime) {
      setValLoading(false);
      return;
    }

    if (lodash_1.isEqual(options, originOptionsRef.current)) {
      setValLoading(!options);
    } else {
      originOptionsRef.current = options;
      setValLoading(false);
    }
  }, [isDatetime, options]); //被聚合

  var numIsCombine = isNum && isCombined;
  var dateIsCombine = isDatetime && isCombined; //暂定为数值，时间字段聚合后单选和选择模式为单选这两种情况

  var single = numIsCombine || dateIsCombine || mode === 'single';
  var checkboxOrRadio = single || isText;
  var multi = !single;
  var keys = constants_1.DATE_NUM_KEYS[type];

  var _e = keys || [],
      fk = _e[0],
      sk = _e[1]; // //处理交叉筛选导致options为空的问题
  // const mixedOptions =
  //   options.length > 0
  //     ? options
  //     : isText
  //     ? fieldFilter?.list ?? []
  //     : map(keys, (k) => get(fieldFilter, [k]));


  var mixedOptions = React.useMemo(function () {
    return options !== null && options !== void 0 ? options : [];
  }, [options]);

  var _f = React.useMemo(function () {
    // 暂时前25个显示，其他的不显示
    var top25Opts = mixedOptions.slice(0, DEAFAULT_DISPLAY_NUM);
    var restVals = mixedOptions.slice(DEAFAULT_DISPLAY_NUM);
    var len = mixedOptions.length;
    var formatOptions = len > DEAFAULT_DISPLAY_NUM ? __spreadArray(__spreadArray([], exports.formatLabelValue(top25Opts, textLabels === null || textLabels === void 0 ? void 0 : textLabels.emptyValText)), [{
      label: renderRestLabel && renderRestLabel(len - DEAFAULT_DISPLAY_NUM),
      value: 'rest'
    }]) : exports.formatLabelValue(mixedOptions, textLabels === null || textLabels === void 0 ? void 0 : textLabels.emptyValText);
    return [formatOptions, restVals];
  }, [mixedOptions, renderRestLabel, textLabels === null || textLabels === void 0 ? void 0 : textLabels.emptyValText]),
      formatOptions = _f[0],
      restVals = _f[1]; //todo 暂时num和datetime分成单选，因为合并之后的选项可能交叉


  var allCheck = React.useCallback(function (checked) {
    var obj = __assign({}, filterItemTemplate);

    if (checked) {
      var vals = lodash_1.map(mixedOptions, function (it) {
        return typeof it === 'string' || it === null ? it : it.value;
      });
      isText && (obj.list = lodash_1.flatten(vals));
    } // changeItem(obj, field);


    changeItem(obj, field);
  }, [changeItem, filterItemTemplate, field, mixedOptions, isText]); //value string: 选择普通选项， string[]选择聚合选项，ObjectInterface：输入数字或者日期

  var change = React.useCallback(function (value, checked) {
    var _a;

    var _b; // let vals: unknown;
    // const item = filterItemRef.current;


    var valObj = {};

    if (multi) {
      var isRest = value === 'rest';
      var filterItemList = (_b = fieldFilter === null || fieldFilter === void 0 ? void 0 : fieldFilter.list) !== null && _b !== void 0 ? _b : [];
      var v_1 = isRest ? restVals : value; //判断是否数组，是因为聚合，value就可能是一个string[]

      var list = checked ? __spreadArray(__spreadArray([], filterItemList), lodash_1.isArray(v_1) ? v_1 : [v_1]) : lodash_1.filter(filterItemList, function (it) {
        return lodash_1.isArray(v_1) ? !v_1.includes(it) : it !== v_1;
      });
      valObj = {
        list: list
      };
    } else {
      valObj = isText ? {
        list: lodash_1.isArray(value) ? value : value ? [value] : []
      } : lodash_1.isEmpty(value) ? filterItemTemplate : (_a = {}, _a[fk] = lodash_1.get(value, '[0]'), _a[sk] = lodash_1.get(value, '[1]'), _a);
    }

    changeItem(__assign(__assign({}, filterItemTemplate), valObj), field);
  }, [multi, changeItem, filterItemTemplate, field, fieldFilter, restVals, isText, fk, sk]);
  var changeDateAndNum = React.useCallback(function (key, value) {
    var _a;

    var obj = __assign(__assign({}, fieldFilter !== null && fieldFilter !== void 0 ? fieldFilter : filterItemTemplate), (_a = {}, _a[key] = value !== null && value !== void 0 ? value : undefined, _a));

    changeItem(obj, field);
  }, [changeItem, field, filterItemTemplate, fieldFilter]);
  var style = React.useMemo(function () {
    return {
      flexWrap: 'wrap',
      height: isExpand ? 'auto' : exports.FIELD_ROW_HEIGHT,
      overflow: isExpand ? 'auto' : 'hidden'
    };
  }, [isExpand]); // eslint-disable-next-line @typescript-eslint/no-explicit-any

  var dateNumRange = {
    datetime: date_picker_1["default"],
    number: input_1.InputNumber
  };
  var DateNumRangeComp = dateNumRange[type];
  var dateNumRangeProp = React.useMemo(function () {
    var arr = [];
    if (type === enum_1.FieldType.text) return arr;
    var keys = constants_1.DATE_NUM_KEYS[type];
    var obj = {
      size: 'compact'
    };

    var _loop_1 = function _loop_1(index) {
      var k = keys[index];
      var value = lodash_1.get(fieldFilter, "" + k); //未聚合的number格式， [1, 14]
      //聚合果的number格式[{"label": "0-0.4","value": [0,0.4],"max": 0.8,"min": 0}]，所以再获取一次

      var originPv = lodash_1.get(mixedOptions, "" + index);
      var pv = ['string', 'number'].includes((0, _typeof2["default"])(originPv)) ? originPv : lodash_1.get(originPv, "" + k);
      isDatetime ? arr.push(__assign(__assign({}, obj), {
        onChange: function onChange(_val, dateString) {
          return changeDateAndNum(k, dateString);
        },
        value: value ? dayjs_1["default"](value) : null
      })) : arr.push(__assign(__assign({}, obj), {
        visibilityHandler: true,
        placeholder: "" + (isNull_1["default"](pv) || lodash_1.isUndefined(pv) ? '-' : pv),
        onBlur: function onBlur(e) {
          var fv = parseFloat(e.target.value);
          var v = Number.isNaN(fv) ? undefined : fv;
          changeDateAndNum(k, v);
        },
        value: value
      }));
    };

    for (var index = 0; index < 2; index++) {
      _loop_1(index);
    }

    return arr;
  }, [changeDateAndNum, fieldFilter, isDatetime, mixedOptions, type]);
  var moreBtnStyle = React.useMemo(function () {
    var _a;

    return _a = {}, _a["" + (isExpand ? 'top' : 'bottom')] = 4, _a;
  }, [isExpand]);
  var AllCheck = React.useMemo(function () {
    var _a;

    var list = (_a = fieldFilter === null || fieldFilter === void 0 ? void 0 : fieldFilter.list) !== null && _a !== void 0 ? _a : [];
    var checked = lodash_1.every(formatOptions, function (it) {
      return lodash_1.isArray(it.value) ? lodash_1.every(it.value, function (i) {
        return list.includes(i);
      }) : list.includes(it.value);
    });
    return multi && !!lodash_1.size(mixedOptions) && jsx_runtime_1.jsx("div", __assign({
      className: Tiled_1.prefixCls + "-row-vals-it"
    }, {
      children: jsx_runtime_1.jsx(checkbox_1["default"], {
        checked: checked,
        onChange: allCheck,
        title: textLabels === null || textLabels === void 0 ? void 0 : textLabels.allSelectLabel
      }, void 0)
    }), void 0);
  }, [allCheck, fieldFilter === null || fieldFilter === void 0 ? void 0 : fieldFilter.list, formatOptions, mixedOptions, multi, textLabels === null || textLabels === void 0 ? void 0 : textLabels.allSelectLabel]);
  var customInputs = React.useMemo(function () {
    return (isDatetime || isNum) && !hiddenCustom && jsx_runtime_1.jsx("div", __assign({
      className: Tiled_1.prefixCls + "-row-vals-it"
    }, {
      children: lodash_1.map(dateNumRangeProp, function (it, index) {
        return jsx_runtime_1.jsxs(React.Fragment, {
          children: [jsx_runtime_1.jsx(DateNumRangeComp, __assign({}, it), void 0), !index && jsx_runtime_1.jsx("span", __assign({
            className: Tiled_1.prefixCls + "-row-vals-it-separate"
          }, {
            children: "-"
          }), void 0)]
        }, "customInputs" + index);
      })
    }), void 0);
  }, [DateNumRangeComp, dateNumRangeProp, hiddenCustom, isDatetime, isNum]);
  var fieldMoreNode = React.useMemo(function () {
    return filterHeight > exports.FIELD_ROW_HEIGHT && jsx_runtime_1.jsx("div", __assign({
      className: Tiled_1.prefixCls + "-row-vals-it " + Tiled_1.prefixCls + "-row-vals-it-expand-no",
      onClick: setIsExpand
    }, {
      children: jsx_runtime_1.jsxs("div", __assign({
        style: moreBtnStyle
      }, {
        children: [jsx_runtime_1.jsx(icon_1["default"], {
          icon: isExpand ? 'remove' : 'add'
        }, void 0), isExpand ? textLabels === null || textLabels === void 0 ? void 0 : textLabels.more : textLabels === null || textLabels === void 0 ? void 0 : textLabels.expand]
      }), void 0)
    }), void 0);
  }, [filterHeight, isExpand, moreBtnStyle, setIsExpand, textLabels === null || textLabels === void 0 ? void 0 : textLabels.expand, textLabels === null || textLabels === void 0 ? void 0 : textLabels.more]);
  return jsx_runtime_1.jsxs("div", __assign({
    className: Tiled_1.prefixCls + "-row"
  }, {
    children: [jsx_runtime_1.jsx("div", __assign({
      className: Tiled_1.prefixCls + "-row-label"
    }, {
      children: field.name
    }), void 0), jsx_runtime_1.jsx("div", __assign({
      className: Tiled_1.prefixCls + "-row-vals " + Tiled_1.prefixCls + "-row-vals-loading",
      style: style
    }, {
      children: valLoading ? jsx_runtime_1.jsx(spin_1["default"], {
        size: "small"
      }, void 0) : jsx_runtime_1.jsxs(React.Fragment, {
        children: [jsx_runtime_1.jsxs("div", __assign({
          className: Tiled_1.prefixCls + "-row-vals-wrapper",
          ref: filterWrapperRef
        }, {
          children: [formatOptions.length === 0 && isText ? '-' : checkboxOrRadio && jsx_runtime_1.jsxs(jsx_runtime_1.Fragment, {
            children: [AllCheck, formatOptions.map(function (it, index) {
              var _a;

              var isRest = it.value === 'rest';
              var list = (_a = fieldFilter === null || fieldFilter === void 0 ? void 0 : fieldFilter.list) !== null && _a !== void 0 ? _a : []; //聚合过的就用every,没有聚合过的就用includes

              var multiChecked = lodash_1.isArray(it.value) || isRest ? lodash_1.every(isRest ? restVals : it.value, function (i) {
                return list.includes(i);
              }) : list.includes(it.value); //字符串 单选
              //   list ["中海金沙湾A区"]
              //  it{label: "万科四季花城伴山美筑", value: "万科四季花城伴山美筑"}
              // it.value万科四季花城伴山美筑
              //字符串 聚合 单选
              //   list (2) ["碧绿名苑", "顺德碧桂园蓝天花语五街"]
              //  it {label: "1111", value: ["碧绿名苑", "顺德碧桂园蓝天花语五街"]} it.value ["四季康城", "五峰路"]
              // datetime number 类型聚合
              //  dateOrNumVals： {min: 0, max: 2000}
              // it {label: "0-2000", value: {min: 0, max: 2000}} it.value{max: 2000, min: 0}

              var radioChecked = lodash_1.isString(it.value) ? list.includes(it.value) : lodash_1.isEqual(isText ? list : [lodash_1.get(fieldFilter, "" + fk), lodash_1.get(fieldFilter, "" + sk)], it.value);
              var multiIndex = Number(multi);
              var props = {
                value: it.label,
                onChange: multi ? function (checked) {
                  return change(it.value, checked);
                } : function () {
                  return change(radioChecked ? isText ? '' : {} : it.value);
                },
                title: it.label,
                checked: lodash_1.get([radioChecked, multiChecked], "" + multiIndex)
              };
              var View = lodash_1.get([radio_1["default"], checkbox_1["default"]], "" + multiIndex);
              return jsx_runtime_1.jsx("div", __assign({
                className: Tiled_1.prefixCls + "-row-vals-it"
              }, {
                children: jsx_runtime_1.jsx(View, __assign({}, props, {
                  children: !multi && it.label
                }), void 0)
              }), index);
            })]
          }, void 0), customInputs]
        }), void 0), fieldMoreNode]
      }, void 0)
    }), void 0)]
  }), field.name);
});
exports["default"] = TiledFieldItem;

