import _typeof from "@babel/runtime/helpers/esm/typeof";

var __assign = this && this.__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 __spreadArray = this && this.__spreadArray || function (to, from) {
  for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) {
    to[j] = from[i];
  }

  return to;
};

import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import * as React from 'react';
import { flatten, map, filter, every, get, isEmpty, isString, isEqual, isArray, size, pick, isUndefined } from 'lodash';
import Icon from "../../../icon";
import DatePicker from "../../../date-picker";
import { InputNumber } from "../../../input";
import { useMeasure, useToggle } from 'react-use';
import Checkbox from "../../../checkbox";
import Radio from "../../../radio";
import Spin from "../../../spin";
import dayjs from 'dayjs';
import isNull from 'lodash/isNull';
import { FieldType } from "../../enum";
import { DATE_NUM_KEYS } from "../../constants";
import { prefixCls } from "./Tiled";
export var FIELD_ROW_HEIGHT = 28;
var DEAFAULT_DISPLAY_NUM = 25; //如果是字符串，那就格式化{label: string, value: string}
//如果是null， 就按空值处理
//如果是object， 就直接返回

export var formatLabelValue = function formatLabelValue(arr, emptyVal) {
  return map(arr, function (it) {
    return _typeof(it) === 'object' ? isNull(it) ? {
      label: emptyVal,
      value: it
    } : it : {
      label: it,
      value: it
    };
  });
};
var TiledFieldItem = /*#__PURE__*/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 === FieldType.number;
  var isDatetime = type === FieldType.datetime;
  var isText = type === FieldType.text;

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

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

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

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

    if (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 = 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([], formatLabelValue(top25Opts, textLabels === null || textLabels === void 0 ? void 0 : textLabels.emptyValText)), [{
      label: renderRestLabel && renderRestLabel(len - DEAFAULT_DISPLAY_NUM),
      value: 'rest'
    }]) : 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 = map(mixedOptions, function (it) {
        return typeof it === 'string' || it === null ? it : it.value;
      });
      isText && (obj.list = 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), isArray(v_1) ? v_1 : [v_1]) : filter(filterItemList, function (it) {
        return isArray(v_1) ? !v_1.includes(it) : it !== v_1;
      });
      valObj = {
        list: list
      };
    } else {
      valObj = isText ? {
        list: isArray(value) ? value : value ? [value] : []
      } : isEmpty(value) ? filterItemTemplate : (_a = {}, _a[fk] = get(value, '[0]'), _a[sk] = 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' : FIELD_ROW_HEIGHT,
      overflow: isExpand ? 'auto' : 'hidden'
    };
  }, [isExpand]); // eslint-disable-next-line @typescript-eslint/no-explicit-any

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

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

      var originPv = get(mixedOptions, "" + index);
      var pv = ['string', 'number'].includes(_typeof(originPv)) ? originPv : get(originPv, "" + k);
      isDatetime ? arr.push(__assign(__assign({}, obj), {
        onChange: function onChange(_val, dateString) {
          return changeDateAndNum(k, dateString);
        },
        value: value ? dayjs(value) : null
      })) : arr.push(__assign(__assign({}, obj), {
        visibilityHandler: true,
        placeholder: "" + (isNull(pv) || 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 = every(formatOptions, function (it) {
      return isArray(it.value) ? every(it.value, function (i) {
        return list.includes(i);
      }) : list.includes(it.value);
    });
    return multi && !!size(mixedOptions) && _jsx("div", __assign({
      className: prefixCls + "-row-vals-it"
    }, {
      children: _jsx(Checkbox, {
        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("div", __assign({
      className: prefixCls + "-row-vals-it"
    }, {
      children: map(dateNumRangeProp, function (it, index) {
        return _jsxs(React.Fragment, {
          children: [_jsx(DateNumRangeComp, __assign({}, it), void 0), !index && _jsx("span", __assign({
            className: prefixCls + "-row-vals-it-separate"
          }, {
            children: "-"
          }), void 0)]
        }, "customInputs" + index);
      })
    }), void 0);
  }, [DateNumRangeComp, dateNumRangeProp, hiddenCustom, isDatetime, isNum]);
  var fieldMoreNode = React.useMemo(function () {
    return filterHeight > FIELD_ROW_HEIGHT && _jsx("div", __assign({
      className: prefixCls + "-row-vals-it " + prefixCls + "-row-vals-it-expand-no",
      onClick: setIsExpand
    }, {
      children: _jsxs("div", __assign({
        style: moreBtnStyle
      }, {
        children: [_jsx(Icon, {
          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 _jsxs("div", __assign({
    className: prefixCls + "-row"
  }, {
    children: [_jsx("div", __assign({
      className: prefixCls + "-row-label"
    }, {
      children: field.name
    }), void 0), _jsx("div", __assign({
      className: prefixCls + "-row-vals " + prefixCls + "-row-vals-loading",
      style: style
    }, {
      children: valLoading ? _jsx(Spin, {
        size: "small"
      }, void 0) : _jsxs(React.Fragment, {
        children: [_jsxs("div", __assign({
          className: prefixCls + "-row-vals-wrapper",
          ref: filterWrapperRef
        }, {
          children: [formatOptions.length === 0 && isText ? '-' : checkboxOrRadio && _jsxs(_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 = isArray(it.value) || isRest ? 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 = isString(it.value) ? list.includes(it.value) : isEqual(isText ? list : [get(fieldFilter, "" + fk), 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: get([radioChecked, multiChecked], "" + multiIndex)
              };
              var View = get([Radio, Checkbox], "" + multiIndex);
              return _jsx("div", __assign({
                className: prefixCls + "-row-vals-it"
              }, {
                children: _jsx(View, __assign({}, props, {
                  children: !multi && it.label
                }), void 0)
              }), index);
            })]
          }, void 0), customInputs]
        }), void 0), fieldMoreNode]
      }, void 0)
    }), void 0)]
  }), field.name);
});
export default TiledFieldItem;

