/**
 * tdesign v0.46.4
 * (c) 2022 tdesign
 * @license MIT
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var VueCompositionAPI = require('@vue/composition-api');
var debounce = require('lodash/debounce');
var range = require('lodash/range');
var padStart = require('lodash/padStart');
var dayjs = require('dayjs');
var customParseFormat = require('../../_chunks/dep-200196ec.js');
var timePicker_panel_props = require('./props.js');
var _common_js_timePicker_const = require('../../_common/js/time-picker/const.js');
var _common_js_timePicker_utils = require('../../_common/js/time-picker/utils.js');
var configProvider_useConfig = require('../../config-provider/useConfig.js');
require('../../_chunks/dep-f8992a6f.js');
require('../props.js');
require('../../config-provider/context.js');
require('lodash/merge');
require('lodash/mergeWith');
require('../../_common/js/global-config/default-config.js');
require('../../_common/js/global-config/locale/zh_CN.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy(_slicedToArray);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var debounce__default = /*#__PURE__*/_interopDefaultLegacy(debounce);
var range__default = /*#__PURE__*/_interopDefaultLegacy(range);
var padStart__default = /*#__PURE__*/_interopDefaultLegacy(padStart);
var dayjs__default = /*#__PURE__*/_interopDefaultLegacy(dayjs);

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__default["default"](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; }
dayjs__default["default"].extend(customParseFormat.customParseFormat);
var timeArr = [_common_js_timePicker_const.EPickerCols.hour, _common_js_timePicker_const.EPickerCols.minute, _common_js_timePicker_const.EPickerCols.second, _common_js_timePicker_const.EPickerCols.milliSecond];
var panelOffset = {
  top: 15,
  bottom: 21
};
var SinglePanel = VueCompositionAPI.defineComponent({
  name: "TTimePickerPanelCol",
  props: _objectSpread(_objectSpread({}, timePicker_panel_props.panelColProps()), {}, {
    position: String,
    triggerScroll: Boolean,
    onChange: Function,
    resetTriggerScroll: Function,
    disableTime: Function
  }),
  setup: function setup(props, ctx) {
    var _toRefs = VueCompositionAPI.toRefs(props),
        steps = _toRefs.steps,
        value = _toRefs.value,
        format = _toRefs.format,
        position = _toRefs.position,
        triggerScroll = _toRefs.triggerScroll;

    var _useConfig = configProvider_useConfig.useConfig("timePicker"),
        global = _useConfig.global;

    var _useConfig2 = configProvider_useConfig.useConfig(),
        classPrefix = _useConfig2.classPrefix;

    var cols = VueCompositionAPI.ref([]);
    var bodyRef = VueCompositionAPI.ref();
    var maskRef = VueCompositionAPI.ref(null);
    var dayjsValue = VueCompositionAPI.computed(function () {
      var isStepsSet = !!steps.value.filter(function (v) {
        return v > 1;
      }).length;
      if (value.value) return dayjs__default["default"](value.value, format.value);
      if (isStepsSet) return dayjs__default["default"]().hour(0).minute(0).second(0);
      return dayjs__default["default"]();
    });
    var panelClassName = VueCompositionAPI.computed(function () {
      return "".concat(classPrefix.value, "-time-picker__panel");
    });
    VueCompositionAPI.watch(function () {
      return dayjsValue.value;
    }, function () {
      if (dayjsValue.value) updateTimeScrollPos(true);
    });
    VueCompositionAPI.watch(function () {
      return triggerScroll.value;
    }, function () {
      if (triggerScroll.value) {
        updateTimeScrollPos(true);
      }
    });
    VueCompositionAPI.onMounted(function () {
      var match = format.value.match(_common_js_timePicker_const.TIME_FORMAT);

      var _match = _slicedToArray__default["default"](match, 7),
          startCol = _match[1],
          hourCol = _match[2],
          minuteCol = _match[3],
          secondCol = _match[4],
          milliSecondCol = _match[5],
          endCol = _match[6];

      var meridiem = _common_js_timePicker_const.EPickerCols.meridiem,
          hour = _common_js_timePicker_const.EPickerCols.hour,
          minute = _common_js_timePicker_const.EPickerCols.minute,
          second = _common_js_timePicker_const.EPickerCols.second,
          milliSecond = _common_js_timePicker_const.EPickerCols.milliSecond;
      var renderCol = [startCol && meridiem, hourCol && hour, minuteCol && minute, secondCol && second, milliSecondCol && milliSecond, endCol && meridiem].filter(function (v) {
        return !!v;
      });
      cols.value = renderCol;
    });

    var getItemHeight = function getItemHeight() {
      var _maskRef$value;

      var maskDom = (_maskRef$value = maskRef.value) === null || _maskRef$value === void 0 ? void 0 : _maskRef$value.querySelector("div");

      if (!maskDom) {
        return {
          offsetHeight: 0,
          margin: 0
        };
      }

      return {
        offsetHeight: maskDom.offsetHeight,
        margin: parseInt(getComputedStyle(maskDom).marginTop, 10)
      };
    };

    var timeItemCanUsed = function timeItemCanUsed(col, el) {
      var colIdx = timeArr.indexOf(col);

      if (colIdx !== -1) {
        var _props$disableTime, _props$disableTime$ca, _props$disableTime$ca2;

        var params = [dayjsValue.value.hour(), dayjsValue.value.minute(), dayjsValue.value.second()];
        params[colIdx] = Number(el);
        return !((_props$disableTime = props.disableTime) !== null && _props$disableTime !== void 0 && (_props$disableTime$ca = _props$disableTime.call.apply(_props$disableTime, [props].concat(params, [{
          partial: position.value || "start"
        }]))) !== null && _props$disableTime$ca !== void 0 && (_props$disableTime$ca2 = _props$disableTime$ca[col]) !== null && _props$disableTime$ca2 !== void 0 && _props$disableTime$ca2.includes(Number(el)));
      }

      return true;
    };

    var getColList = function getColList(col) {
      var count = 0;

      if (timeArr.includes(col)) {
        var colIdx = timeArr.indexOf(col);
        var colStep = steps.value[colIdx] || 1;
        if (col === _common_js_timePicker_const.EPickerCols.hour) count = _common_js_timePicker_const.TWELVE_HOUR_FORMAT.test(format.value) ? 11 : 23;else if (col === _common_js_timePicker_const.EPickerCols.milliSecond) count = 999;else count = 59;
        var colList = range__default["default"](0, count + 1, Number(colStep)).map(function (v) {
          return padStart__default["default"](String(v), 2, "0");
        }) || [];
        return props.hideDisabledTime && !!props.disableTime ? colList.filter(function (t) {
          var _props$disableTime2, _props$disableTime2$c, _props$disableTime2$c2;

          var params = [dayjsValue.value.hour(), dayjsValue.value.minute(), dayjsValue.value.second()];
          params[colIdx] = Number(t);
          return !((_props$disableTime2 = props.disableTime) !== null && _props$disableTime2 !== void 0 && (_props$disableTime2$c = _props$disableTime2.call.apply(_props$disableTime2, [props].concat(params, [{
            partial: position.value || "start"
          }]))) !== null && _props$disableTime2$c !== void 0 && (_props$disableTime2$c2 = _props$disableTime2$c[col]) !== null && _props$disableTime2$c2 !== void 0 && _props$disableTime2$c2.includes(Number(t)));
        }) : colList;
      }

      return _common_js_timePicker_const.MERIDIEM_LIST;
    };

    var getScrollDistance = function getScrollDistance(col, time) {
      if (col === _common_js_timePicker_const.EPickerCols.hour && /[h]{1}/.test(format.value)) {
        time %= 12;
      }

      var itemIdx = getColList(col).indexOf(padStart__default["default"](String(time), 2, "0"));

      var _getItemHeight = getItemHeight(),
          offsetHeight = _getItemHeight.offsetHeight,
          margin = _getItemHeight.margin;

      var timeItemTotalHeight = offsetHeight + margin;
      var distance = Math.abs(Math.max(0, itemIdx) * timeItemTotalHeight);
      return distance;
    };

    var handleScroll = function handleScroll(col) {
      var _ctx$refs, _props$onChange;

      var val;
      var formattedVal;
      var scrollTop = (_ctx$refs = ctx.refs["".concat(col, "Col")]) === null || _ctx$refs === void 0 ? void 0 : _ctx$refs.scrollTop;

      var _getItemHeight2 = getItemHeight(),
          offsetHeight = _getItemHeight2.offsetHeight,
          margin = _getItemHeight2.margin;

      var timeItemTotalHeight = offsetHeight + margin;
      var colStep = Math.abs(Math.round(scrollTop / timeItemTotalHeight + 0.5));
      var meridiem = _common_js_timePicker_const.MERIDIEM_LIST[Math.min(colStep - 1, 1)].toLowerCase();
      if (Number.isNaN(colStep)) colStep = 1;

      if (timeArr.includes(col)) {
        var max = 59;
        if (col === _common_js_timePicker_const.EPickerCols.hour) max = /[h]{1}/.test(format.value) ? 11 : 23;else if (col === _common_js_timePicker_const.EPickerCols.milliSecond) max = 999;
        var colIdx = timeArr.indexOf(col);
        var availableArr = range__default["default"](0, max + 1, Number(steps.value[colIdx]) || 1);
        val = _common_js_timePicker_utils.closestLookup(availableArr, Number(getColList(col)[Math.min(colStep - 1, max + 1, availableArr.length - 1)]), Number(steps.value[colIdx]) || 1);
        if (Number.isNaN(val)) val = availableArr[availableArr.length - 1];

        if (col === _common_js_timePicker_const.EPickerCols.hour && cols.value.includes(_common_js_timePicker_const.EPickerCols.meridiem) && dayjsValue.value.hour() >= 12) {
          val = Number(val) + 12;
        }
      } else val = meridiem;

      var distance = getScrollDistance(col, val);
      if (!dayjs__default["default"](dayjsValue.value).isValid() || value.value && !dayjs__default["default"](value.value, format.value, true).isValid()) return;

      if (timeArr.includes(col)) {
        var _dayjsValue$value$col, _dayjsValue$value;

        if (timeItemCanUsed(col, val)) formattedVal = (_dayjsValue$value$col = (_dayjsValue$value = dayjsValue.value)[col]) === null || _dayjsValue$value$col === void 0 ? void 0 : _dayjsValue$value$col.call(_dayjsValue$value, val).format(format.value);
      } else {
        var currentHour = dayjsValue.value.hour();

        if (meridiem === _common_js_timePicker_const.AM && currentHour >= 12) {
          formattedVal = dayjsValue.value.hour(currentHour - 12).format(format.value);
        } else if (meridiem === _common_js_timePicker_const.PM && currentHour < 12) {
          formattedVal = dayjsValue.value.hour(currentHour + 12).format(format.value);
        } else {
          formattedVal = dayjsValue.value.format(format.value);
        }
      }

      if (formattedVal !== value.value) (_props$onChange = props.onChange) === null || _props$onChange === void 0 ? void 0 : _props$onChange.call(props, formattedVal);

      if (distance !== scrollTop) {
        var _scrollCtrl$scrollTo;

        var scrollCtrl = ctx.refs["".concat(col, "Col")];
        if (!scrollCtrl || scrollCtrl.scrollTop === distance) return;
        (_scrollCtrl$scrollTo = scrollCtrl.scrollTo) === null || _scrollCtrl$scrollTo === void 0 ? void 0 : _scrollCtrl$scrollTo.call(scrollCtrl, {
          top: distance,
          behavior: "smooth"
        });
      }
    };

    var scrollToTime = function scrollToTime(col, time, idx) {
      var _scrollCtrl$scrollTo2;

      var behavior = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "auto";
      var distance = getScrollDistance(col, time);
      var scrollCtrl = ctx.refs["".concat(col, "Col")];
      if (!scrollCtrl || scrollCtrl.scrollTop === distance || !timeItemCanUsed(col, time)) return;
      (_scrollCtrl$scrollTo2 = scrollCtrl.scrollTo) === null || _scrollCtrl$scrollTo2 === void 0 ? void 0 : _scrollCtrl$scrollTo2.call(scrollCtrl, {
        top: distance,
        behavior: behavior
      });
    };

    var handleTimeItemClick = function handleTimeItemClick(col, el, idx) {
      if (!timeItemCanUsed(col, el)) return;

      if (timeArr.includes(col)) {
        if (col === _common_js_timePicker_const.EPickerCols.hour && dayjsValue.value.format("a") === _common_js_timePicker_const.PM && cols.value.includes(_common_js_timePicker_const.EPickerCols.meridiem)) {
          el = Number(el) + 12;
        }

        scrollToTime(col, el, idx, "smooth");
        setTimeout(function () {
          var _dayjsValue$value$col2, _dayjsValue$value2;

          props.onChange((_dayjsValue$value$col2 = (_dayjsValue$value2 = dayjsValue.value)[col]) === null || _dayjsValue$value$col2 === void 0 ? void 0 : _dayjsValue$value$col2.call(_dayjsValue$value2, el).format(format.value));
        }, 100);
      } else {
        var currentHour = dayjsValue.value.hour();

        if (el === _common_js_timePicker_const.AM && currentHour >= 12) {
          var _props$onChange2;

          (_props$onChange2 = props.onChange) === null || _props$onChange2 === void 0 ? void 0 : _props$onChange2.call(props, dayjsValue.value.hour(currentHour - 12).format(format.value));
        } else if (el === _common_js_timePicker_const.PM && currentHour < 12) {
          var _props$onChange3;

          (_props$onChange3 = props.onChange) === null || _props$onChange3 === void 0 ? void 0 : _props$onChange3.call(props, dayjsValue.value.hour(currentHour + 12).format(format.value));
        }
      }
    };

    var updateTimeScrollPos = function updateTimeScrollPos() {
      var isAutoScroll = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
      var behavior = value.value && !isAutoScroll ? "smooth" : "auto";
      var isStepsSet = !!steps.value.filter(function (v) {
        return v > 1;
      }).length;
      VueCompositionAPI.nextTick(function () {
        cols.value.forEach(function (col, idx) {
          if (!isStepsSet || isStepsSet && value.value) {
            var _dayjsValue$value$col3, _dayjsValue$value3;

            scrollToTime(col, timeArr.includes(col) ? (_dayjsValue$value$col3 = (_dayjsValue$value3 = dayjsValue.value)[col]) === null || _dayjsValue$value$col3 === void 0 ? void 0 : _dayjsValue$value$col3.call(_dayjsValue$value3) : dayjsValue.value.format("a"), idx, behavior);
          } else {
            var _getColList;

            scrollToTime(col, (_getColList = getColList(col)) === null || _getColList === void 0 ? void 0 : _getColList[0], idx, behavior);
          }
        });
      });
      props.resetTriggerScroll();
    };

    var isCurrent = function isCurrent(col, colItem) {
      var _dayjsValue$value$col4, _dayjsValue$value4;

      var colVal;

      if (col === _common_js_timePicker_const.EPickerCols.meridiem) {
        var currentMeridiem = dayjsValue.value.format("a");
        return currentMeridiem === colItem;
      }

      colVal = (_dayjsValue$value$col4 = (_dayjsValue$value4 = dayjsValue.value)[col]) === null || _dayjsValue$value$col4 === void 0 ? void 0 : _dayjsValue$value$col4.call(_dayjsValue$value4);

      if (col === _common_js_timePicker_const.EPickerCols.hour && /[h]{1}/.test(format.value)) {
        colVal %= 12;
      }

      return colVal === Number(colItem);
    };

    return {
      getColList: getColList,
      isCurrent: isCurrent,
      bodyRef: bodyRef,
      maskRef: maskRef,
      global: global,
      classPrefix: classPrefix,
      panelClassName: panelClassName,
      cols: cols,
      timeItemCanUsed: timeItemCanUsed,
      handleScroll: handleScroll,
      handleTimeItemClick: handleTimeItemClick
    };
  },
  render: function render() {
    var _this$cols$map,
        _this$cols,
        _this$cols$map2,
        _this$cols2,
        _this = this;

    var h = arguments[0];
    return h("div", {
      "class": "".concat(this.panelClassName, "-body"),
      "ref": "bodyRef"
    }, [h("div", {
      "class": "".concat(this.panelClassName, "-body-active-mask"),
      "ref": "maskRef"
    }, [(_this$cols$map = (_this$cols = this.cols).map) === null || _this$cols$map === void 0 ? void 0 : _this$cols$map.call(_this$cols, function (col, idx) {
      return h("div", {
        "key": "".concat(col, "_").concat(idx)
      });
    })]), (_this$cols$map2 = (_this$cols2 = this.cols).map) === null || _this$cols$map2 === void 0 ? void 0 : _this$cols$map2.call(_this$cols2, function (col, idx) {
      return h("ul", {
        "key": "".concat(col, "_").concat(idx),
        "ref": "".concat(col, "Col"),
        "class": "".concat(_this.panelClassName, "-body-scroll"),
        "on": {
          "scroll": debounce__default["default"](function () {
            return _this.handleScroll(col);
          }, 50)
        },
        "style": {
          "--timePickerPanelOffsetTop": panelOffset.top,
          "--timePickerPanelOffsetBottom": panelOffset.bottom
        }
      }, [_this.getColList(col).map(function (el) {
        var _ref;

        return h("li", {
          "key": el,
          "class": ["".concat(_this.panelClassName, "-body-scroll-item"), (_ref = {}, _defineProperty__default["default"](_ref, "".concat(_this.classPrefix, "-is-disabled"), !_this.timeItemCanUsed(col, el)), _defineProperty__default["default"](_ref, "".concat(_this.classPrefix, "-is-current"), _this.isCurrent(col, el)), _ref)],
          "on": {
            "click": function click() {
              return _this.handleTimeItemClick(col, el, idx);
            }
          }
        }, [timeArr.includes(col) ? _common_js_timePicker_const.TWELVE_HOUR_FORMAT.test(_this.format) && el === "00" ? "12" : el : _this.global[el === _common_js_timePicker_const.AM ? "anteMeridiem" : "postMeridiem"]]);
      })]);
    })]);
  }
});

exports["default"] = SinglePanel;
//# sourceMappingURL=single-panel.js.map
