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

import { h as helper } from '../_chunks/dep-37d5b9c4.js';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import dayjs from 'dayjs';
import { i as isBetween } from '../_chunks/dep-8140ca7e.js';
import { CalendarIcon, TimeIcon } from 'tdesign-icons-vue';
import { prefix } from '../config.js';
import props from './props.js';
import ClASSNAMES from '../utils/classnames.js';
import { Button } from '../button/index.js';
import { Input } from '../input/index.js';
import { Popup } from '../popup/index.js';
import mixins from '../utils/mixins.js';
import getConfigReceiverMixins from '../config-provider/config-receiver.js';
import CalendarPresets from './calendar-presets.js';
import TDate from './panel/date.js';
import TDateRange from './panel/date-range.js';
import PickerPanel from '../time-picker/panel/index.js';
import { EPickerCols } from '../time-picker/interface.js';
import { firstUpperCase, extractTimeFormat } from '../_common/js/date-picker/utils.js';
import { renderTNodeJSX } from '../utils/render-tnode.js';
import '../_chunks/dep-8600dc2e.js';
import '../button/button.js';
import '../loading/index.js';
import '../loading/loading.js';
import 'vue';
import '../loading/icon/gradient.js';
import '../_common/js/loading/circle-adapter.js';
import '../_common/js/utils/set-style.js';
import '../_common/js/utils/helper.js';
import '@babel/runtime/helpers/objectWithoutProperties';
import '../utils/dom.js';
import 'raf';
import 'lodash/isString';
import '../utils/easing.js';
import '../utils/transfer-dom.js';
import '../loading/props.js';
import '../utils/withInstall.js';
import 'lodash/capitalize';
import './style/css.js';
import '../loading/type.js';
import '../loading/plugin.js';
import '@babel/runtime/helpers/typeof';
import '../button/props.js';
import '../utils/ripple.js';
import 'lodash/mergeWith';
import '../config-provider/context.js';
import 'lodash/merge';
import '../_common/js/global-config/default-config.js';
import '../_common/js/global-config/locale/zh_CN.js';
import '../config-provider/type.js';
import '../button/type.js';
import '../input/addon.js';
import '../input/input.js';
import '@babel/runtime/helpers/toConsumableArray';
import 'lodash/camelCase';
import 'lodash/kebabCase';
import '../utils/helper.js';
import '../utils/event.js';
import '../input/props.js';
import '../input/input-group.js';
import '../utils/map-props.js';
import '../input/type.js';
import '../popup/popup.js';
import '@popperjs/core';
import '../popup/props.js';
import '../popup/container.js';
import '../popup/type.js';
import './basic/header.js';
import './basic/table.js';
import './basic/cell.js';
import '../_chunks/dep-f43c4264.js';
import 'lodash/debounce';
import '../time-picker/panel/props.js';
import '../time-picker/props.js';
import '../time-picker/constant.js';
import '../time-picker/type.js';
import '@babel/runtime/helpers/extends';
import 'lodash/chunk';

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; }
dayjs.extend(isBetween);
var name = "".concat(prefix, "-date-picker");
var _DatePicker = mixins(getConfigReceiverMixins("datePicker")).extend({
  name: "TDatePicker",
  components: {
    CalendarIcon: CalendarIcon,
    TimeIcon: TimeIcon,
    TPopup: Popup,
    TButton: Button,
    TInput: Input,
    CalendarPresets: CalendarPresets,
    TDate: TDate,
    TDateRange: TDateRange,
    TTimePickerPanel: PickerPanel
  },
  props: _objectSpread({}, props),
  data: function data() {
    return {
      tempValue: "",
      monthDate: new Date(),
      start: new Date(),
      end: new Date(),
      selectedDates: [],
      inSelection: false,
      inline: false,
      dateFormat: "",
      multiSeparator: ",",
      inlineView: false,
      showTime: false,
      isOpen: false,
      formDisabled: void 0,
      startTimeValue: dayjs(),
      endTimeValue: dayjs()
    };
  },
  computed: {
    inputListeners: function inputListeners() {
      return _objectSpread(_objectSpread({}, this.$listeners), {}, {
        focus: this.onNativeFocus,
        input: this.onNativeInput,
        click: this.onClick
      });
    },
    startText: function startText() {
      return this.formatDate(this.start);
    },
    endText: function endText() {
      return this.formatDate(this.end);
    },
    formattedValue: {
      get: function get() {
        var vm = this;
        var tempValue = vm.tempValue,
            range = vm.range,
            mode = vm.mode,
            isOpen = vm.isOpen,
            startText = vm.startText,
            endText = vm.endText,
            global = vm.global,
            outValue = vm.value;
        var selectedDates = vm.getDates(outValue);
        var selectedFmtDates = selectedDates.map(function (d) {
          return vm.formatDate(d);
        });

        if (tempValue) {
          return tempValue;
        }

        var strMode = range ? "range" : mode;
        var value = "";

        switch (strMode) {
          case "time":
          case "date":
          case "month":
          case "year":
            value = selectedFmtDates.join("");
            break;

          case "range":
            if (isOpen) {
              value = [startText, endText].join(global.rangeSeparator);
            } else if (selectedFmtDates.length > 1) {
              value = [selectedFmtDates[0], selectedFmtDates[1]].join(global.rangeSeparator);
            }

            break;
        }

        return value;
      },
      set: function set(value) {
        var vm = this;
        var min = vm.min,
            dateFormat = vm.dateFormat;

        if (value) {
          if (String(value).length >= String(vm.formatDate(min || new Date())).length && dayjs(value, dateFormat)) {
            vm.tempValue = "";
            vm.setDate(value, true);
          } else {
            vm.tempValue = value;
          }
        }
      }
    },
    rangeText: {
      get: function get() {
        var vm = this;
        var range = vm.startText;

        if (vm.range) {
          range += " ".concat(vm.global.rangeSeparator, " ").concat(vm.endText);
        }

        return range;
      },
      set: function set(value) {
        var vm = this;

        if (vm.value) {
          vm.setDate(value, false);
        }
      }
    },
    min: function min() {
      var disableDate = this.disableDate || {};
      var before = disableDate.before;
      return before ? new Date(before) : null;
    },
    max: function max() {
      var disableDate = this.disableDate || {};
      var after = disableDate.after;
      return after ? new Date(after) : null;
    },
    classes: function classes() {
      var _ref;

      return [name, ClASSNAMES.SIZE[this.size] || "", (_ref = {}, _defineProperty(_ref, "".concat(name, "--month-picker"), this.mode === "year" || this.mode === "month"), _defineProperty(_ref, "".concat(prefix, "-inline"), this.inline || this.inlineView), _ref)];
    },
    pickerStyles: function pickerStyles() {
      var _ref2;

      return _ref2 = {}, _defineProperty(_ref2, "".concat(name, "__container"), true), _defineProperty(_ref2, "".concat(name, "-picker--open"), this.isOpen || this.inlineView), _defineProperty(_ref2, "".concat(name, "--calendar-inline-view"), this.inlineView), _defineProperty(_ref2, "".concat(name, "--range"), this.range), _ref2;
    },
    tDisabled: function tDisabled() {
      return this.formDisabled || this.disabled;
    }
  },
  mounted: function mounted() {
    this.attachDatePicker();
  },
  methods: {
    handleTInputFocus: function handleTInputFocus() {
      var _this = this;

      this.$nextTick(function () {
        _this.$refs["native"].blur();
      });
    },
    handleTimePick: function handleTimePick(col, time, index) {
      if (!this.range || index === 0) {
        var start = new Date(this.start);
        start["set".concat(firstUpperCase(col), "s")](time);
        this.start = start;
        this.startTimeValue = dayjs(start);
        this.dateClick(new Date(start));
      } else {
        var end = new Date(this.end);
        end["set".concat(firstUpperCase(col), "s")](time);
        this.end = end;
        this.endTimeValue = dayjs(end);
        this.dateClick(new Date(end));
      }
    },
    attachDatePicker: function attachDatePicker() {
      var startDate = new Date();
      var endDate = new Date();
      this.dateFormat = this.format || this.global.format;
      var start = new Date(startDate);
      var end = new Date(endDate);

      if (!this.range) {
        end = new Date(startDate);
      }

      this.start = start;
      this.end = end;
      var val = this.value || this.defaultValue || "";
      this.setDate(val, false);

      if (this.inlineView) {
        this.open();
      }
    },
    onNativeInput: function onNativeInput(event) {
      var val = event.target.value;
      this.formattedValue = val;
      var d1 = this.parseDate(val);

      if (d1 instanceof Date) {
        var d2 = this.formatDate(d1);
        this.$emit("input", d2);
      }
    },
    onNativeFocus: function onNativeFocus(event) {
      if (!this.isOpen) {
        this.open();
      }

      this.$emit("focus", event);
    },
    onClick: function onClick(event) {
      if (!this.isOpen) {
        this.open();
      }

      this.$emit("click", event);
    },
    normalizeDateTime: function normalizeDateTime(value, oldValue) {
      var newDate = dayjs(value);
      var oldDate = dayjs(oldValue);

      if (this.enableTimePicker) {
        newDate.hour(oldDate.hour());
        newDate.minute(oldDate.minute());
        newDate.second(oldDate.second());
        newDate.millisecond(oldDate.millisecond());
      }

      return newDate.toDate();
    },
    dateClick: function dateClick(value) {
      var mode = this.range ? "range" : this.mode;

      if (this.showTime) {
        mode = "time";
      }

      switch (mode) {
        case "time":
          this.selectedDates = this.range ? [this.start, this.end] : [value];
          this.clickedApply(false);
          break;

        case "year":
        case "month":
        case "date":
          this.start = this.normalizeDateTime(value, this.start);
          this.selectedDates = [this.start];
          this.clickedApply(!this.enableTimePicker);
          break;

        case "range":
          if (this.inSelection) {
            this.inSelection = false;
            this.start = this.normalizeDateTime(value[0], this.end);
            this.end = this.normalizeDateTime(value[1], this.end);

            if (this.end < this.start) {
              this.inSelection = true;
              this.start = this.normalizeDateTime(value[0], this.start);
            }
          } else {
            this.start = this.normalizeDateTime(value[0], this.start);
            this.end = this.normalizeDateTime(value[1], this.end);
            this.inSelection = true;
          }

          this.clickedApply(!this.enableTimePicker);
          break;
      }
    },
    toggle: function toggle() {
      if (!this.tDisabled) {
        if (this.isOpen) {
          this.close();
        } else {
          this.open();
        }
      }
    },
    open: function open() {
      var _this2 = this;

      if (!this.tDisabled) {
        var formattedValue = this.formattedValue;

        if (formattedValue) {
          this.setDate(formattedValue);
        }

        this.tempValue = "";
        this.isOpen = true;
        this.$nextTick(function () {
          _this2.$emit("open", _this2.selectedDates);
        });
      }
    },
    close: function close() {
      if (!this.tDisabled) {
        this.tempValue = "";
        this.isOpen = false;
        this.showTime = false;
        this.$emit("close", this.selectedDates);
      }
    },
    clickedApply: function clickedApply() {
      var _this3 = this;

      var closePicker = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;

      if (this.range) {
        this.selectedDates = [this.start, this.end];
      }

      var selectedDates = this.selectedDates.map(function (d) {
        var fd = _this3.formatDate(d);

        return fd;
      });
      this.submitInput(selectedDates, true);
      this.$emit("onChange", selectedDates);

      if (closePicker) {
        this.close();
      }
    },
    toggleTime: function toggleTime() {
      var _this4 = this;

      this.startTimeValue = dayjs(this.start);
      this.endTimeValue = dayjs(this.end);
      this.showTime = !this.showTime;
      this.$nextTick(function () {
        var timePickerPanel = _this4.$refs.timePickerPanel;
        timePickerPanel && timePickerPanel.panelColUpdate();
      });
    },
    clickAway: function clickAway() {
      if (this.isOpen) {
        var selectedDates = this.selectedDates;

        if (selectedDates.length > 1) {
          this.start = new Date(selectedDates[0]);
          this.end = new Date(selectedDates[1]);
        }

        this.close();
      }
    },
    clickRange: function clickRange(value) {
      if (Array.isArray(value)) {
        var _value = _slicedToArray(value, 2),
            start = _value[0],
            end = _value[1];

        this.start = dayjs(start).toDate();
        this.end = dayjs(end || start).toDate();
        this.monthDate = dayjs(start).toDate();
      } else {
        this.start = dayjs(value).toDate();
        this.end = dayjs(value).toDate();
        this.monthDate = dayjs(value).toDate();
      }

      this.clickedApply();
    },
    clear: function clear() {
      var triggerChange = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
      this.close();

      if (!this.tDisabled) {
        var selectedDates = [];
        this.selectedDates = selectedDates;
        this.formattedValue = "";
        this.start = new Date();
        this.end = new Date();
        this.submitInput(selectedDates, triggerChange);
      }
    },
    submitInput: function submitInput(selectedDates) {
      var triggerChange = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
      var multiSeparator = this.multiSeparator;
      var mode = this.range ? "range" : this.mode;

      switch (mode) {
        case "date":
        case "month":
        case "year":
          if (triggerChange) {
            this.$emit("input", selectedDates.join(multiSeparator));
            this.$emit("change", selectedDates.join(multiSeparator));
          }

          break;

        case "range":
          if (triggerChange) {
            this.$emit("input", selectedDates);
            this.$emit("change", selectedDates);
          }

          break;
      }
    },
    parseDate: function parseDate() {
      var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
      var format = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";

      if (value instanceof Date) {
        return new Date(value);
      }

      if (format) {
        var oDate = dayjs(value, format);

        if (oDate.isValid()) {
          return new Date(oDate.toDate());
        }

        return false;
      }

      var d2 = dayjs(value);

      if (d2.isValid()) {
        return new Date(d2.toDate());
      }

      return false;
    },
    isEnabled: function isEnabled(value) {
      var min = this.min,
          max = this.max,
          disableDate = this.disableDate,
          dateFormat = this.dateFormat;

      if (!disableDate) {
        return true;
      }

      var isEnabled = true;

      if (typeof disableDate === "function") {
        return !disableDate(value);
      }

      if (Array.isArray(disableDate)) {
        var isIncludes = false;
        var formattedDisabledDate = disableDate.map(function (item) {
          return dayjs(item, dateFormat);
        });
        formattedDisabledDate.forEach(function (item) {
          if (item.isSame(dayjs(value))) {
            isIncludes = true;
          }
        });
        return !isIncludes;
      }

      var from = disableDate.from,
          to = disableDate.to;

      if (from && to) {
        var compareMin = dayjs(new Date(from));
        var compareMax = dayjs(new Date(to));
        return !dayjs(value).isBetween(compareMin, compareMax, this.mode, "[]");
      }

      if (max && min) {
        var _compareMin = dayjs(new Date(min));

        var _compareMax = dayjs(new Date(max));

        isEnabled = dayjs(value).isBetween(_compareMin, _compareMax, this.mode, "[]");
      } else if (min) {
        var _compareMin2 = dayjs(new Date(min));

        isEnabled = !dayjs(value).isBefore(_compareMin2, this.mode);
      } else if (max) {
        var _compareMax2 = dayjs(new Date(max));

        isEnabled = !dayjs(value).isAfter(_compareMax2, this.mode);
      }

      return isEnabled;
    },
    setDate: function setDate() {
      var inputDate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
      var triggerChange = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

      if (inputDate !== 0 && !inputDate || inputDate instanceof Array && inputDate.length === 0) {
        return this.clear(triggerChange);
      }

      var selectedDates = this.getDates(inputDate);
      this.selectedDates = selectedDates;

      if (selectedDates.length > 0) {
        var _selectedDates = _slicedToArray(selectedDates, 2),
            start = _selectedDates[0],
            end = _selectedDates[1];

        this.start = start;
        this.end = end || start;
      }
    },
    getDates: function getDates() {
      var _this5 = this;

      var inputDate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";

      if (inputDate !== 0 && !inputDate || inputDate instanceof Array && inputDate.length === 0) {
        return [];
      }

      var format = this.dateFormat || "";
      var dates = [];

      if (inputDate instanceof Array) {
        dates = inputDate.map(function (d) {
          var d1 = _this5.parseDate(d, format);

          return d1;
        });
      } else if (inputDate instanceof Date || typeof inputDate === "number") {
        dates = [this.parseDate(inputDate, format)];
      } else if (typeof inputDate === "string") {
        var mode = this.range ? "range" : this.mode;

        switch (mode) {
          case "date":
          case "month":
          case "year":
            dates = [this.parseDate(inputDate, format)];
            break;

          case "range":
            dates = inputDate.split(this.global.rangeSeparator || "-").map(function (d) {
              var d1 = _this5.parseDate(d, format);

              return d1;
            });
            break;

          default:
            break;
        }
      }

      var selectedDates = dates.filter(function (d) {
        var isEnable = d instanceof Date && _this5.isEnabled(d);

        return isEnable;
      });
      selectedDates.sort(function (a, b) {
        return a.getTime() - b.getTime();
      });
      return selectedDates;
    },
    formatDate: function formatDate(date) {
      var format = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
      var dateFormat = format || this.dateFormat || this.global.format;
      var arrTime = ["H", "h", "m", "s"];
      var hasTime = arrTime.some(function (f) {
        return String(dateFormat).includes(f);
      });

      if (this.enableTimePicker && !hasTime) {
        dateFormat = [dateFormat, "HH:mm:ss"].join(" ");
      }

      var d1 = new Date(date);
      return dayjs(d1).format(dateFormat);
    },
    getPlaceholderText: function getPlaceholderText() {
      var _this$global, _this$global$placehol;

      var placeholder = this.placeholder,
          mode = this.mode;
      var placeholderStr = placeholder || ((_this$global = this.global) === null || _this$global === void 0 ? void 0 : (_this$global$placehol = _this$global.placeholder) === null || _this$global$placehol === void 0 ? void 0 : _this$global$placehol[mode]);

      if (placeholder && Array.isArray(placeholder)) {
        placeholderStr = placeholder.join(this.global.rangeSeparator);
      }

      return placeholderStr;
    },
    onPopupVisibleChange: function onPopupVisibleChange(visible, context) {
      if (context.trigger === "document") {
        this.toggle();
      }
    }
  },
  render: function render() {
    var _this6 = this;

    var h = arguments[0];
    var popupProps = this.popupProps,
        tDisabled = this.tDisabled,
        clearable = this.clearable,
        allowInput = this.allowInput,
        size = this.size,
        inputProps = this.inputProps,
        enableTimePicker = this.enableTimePicker,
        mode = this.mode,
        range = this.range,
        presets = this.presets,
        firstDayOfWeek = this.firstDayOfWeek;
    var start = this.start,
        end = this.end,
        showTime = this.showTime,
        startTimeValue = this.startTimeValue,
        global = this.global,
        isOpen = this.isOpen,
        endTimeValue = this.endTimeValue;
    var panelProps = {
      value: range ? [start, end] : start,
      mode: mode,
      firstDayOfWeek: firstDayOfWeek === void 0 ? 1 : firstDayOfWeek,
      disableDate: function disableDate(d) {
        return !_this6.isEnabled(d);
      },
      onChange: this.dateClick,
      global: this.global
    };

    var onPick = function onPick(date, context) {
      _this6.$emit("pick", date, context);
    };

    var panelComponent = range ? h(TDateRange, {
      "props": _objectSpread({}, _objectSpread(_objectSpread({}, panelProps), {}, {
        onPick: onPick
      }))
    }) : h(TDate, {
      "props": _objectSpread({}, _objectSpread({}, panelProps))
    });

    var popupContent = function popupContent() {
      return h("div", {
        "ref": "dropdownPopup",
        "class": _this6.pickerStyles
      }, [enableTimePicker && showTime && h("div", [h("t-time-picker-panel", {
        "ref": "timePickerPanel",
        "attrs": {
          "format": extractTimeFormat(_this6.dateFormat) || "HH:mm:ss",
          "cols": [EPickerCols.hour, EPickerCols.minute, EPickerCols.second],
          "steps": [1, 1, 1],
          "value": !range ? [startTimeValue] : [startTimeValue, endTimeValue],
          "range": true,
          "isFooterDisplay": false
        },
        "on": {
          "time-pick": _this6.handleTimePick
        }
      })]), !showTime && panelComponent, (!!presets || enableTimePicker) && h("div", {
        "class": "".concat(prefix, "-date-picker__footer")
      }, [h("calendar-presets", {
        "attrs": {
          "presets": presets,
          "global": global
        },
        "props": _objectSpread({}, {
          onClick: range ? _this6.clickRange : _this6.dateClick
        })
      }), enableTimePicker && h("div", {
        "class": "".concat(name, "--apply")
      }, [enableTimePicker && h("t-button", {
        "attrs": {
          "theme": "primary",
          "variant": "text"
        },
        "on": {
          "click": _this6.toggleTime
        }
      }, [showTime ? global.selectDate : global.selectTime]), h("t-button", {
        "attrs": {
          "theme": "primary"
        },
        "on": {
          "click": _this6.clickedApply
        }
      }, [global.confirm])])])]);
    };

    var inputClassNames = ["".concat(prefix, "-form-controls"), _defineProperty({}, ClASSNAMES.STATUS.active, this.isOpen)];
    var prefixIcon = renderTNodeJSX(this, "prefixIcon");
    var suffixIconSlot = renderTNodeJSX(this, "suffixIcon");

    var suffixIcon = function suffixIcon() {
      if (suffixIconSlot) {
        return suffixIconSlot;
      }

      if (enableTimePicker) {
        return h("time-icon");
      }

      return h("calendar-icon");
    };

    return h("div", {
      "class": this.classes
    }, [h("t-popup", helper([{
      "ref": "popup",
      "class": "".concat(name, "__popup-reference"),
      "attrs": {
        "trigger": "click",
        "placement": "bottom-left",
        "disabled": tDisabled,
        "showArrow": false,
        "visible": isOpen,
        "popupProps": popupProps,
        "overlayClassName": name,
        "content": popupContent,
        "expandAnimation": true
      }
    }, {
      "on": {
        "visible-change": this.onPopupVisibleChange
      }
    }]), [h("div", {
      "class": inputClassNames,
      "on": {
        "click": this.toggle
      }
    }, [h("t-input", {
      "ref": "native",
      "attrs": {
        "disabled": tDisabled,
        "clearable": clearable,
        "placeholder": this.getPlaceholderText(),
        "allowInput": allowInput ? 1 : 0,
        "size": size,
        "inputProps": inputProps,
        "prefixIcon": prefixIcon,
        "suffixIcon": suffixIcon
      },
      "on": {
        "clear": function clear(context) {
          context.e.stopPropagation();

          _this6.clear(true);
        },
        "focus": this.handleTInputFocus
      },
      "props": _objectSpread({}, _objectSpread({}, this.inputListeners)),
      "model": {
        value: _this6.formattedValue,
        callback: function callback($$v) {
          _this6.formattedValue = $$v;
        }
      }
    })])])]);
  }
});

export { _DatePicker as default };
//# sourceMappingURL=date-picker.js.map
