"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const aria = require("../../../../constants/aria.js");
const event = require("../../../../constants/event.js");
const event$1 = require("../../../../utils/dom/event.js");
const shared_esmBundler = require("../../../../../../@vue/shared/dist/shared.esm-bundler.js");
const error = require("../../../../utils/error.js");
const index = require("../../../../hooks/use-namespace/index.js");
const index$2 = require("../../../../hooks/use-focus-controller/index.js");
const index$1 = require("../../../../hooks/use-empty-values/index.js");
const index$7 = require("../../../icon/index.js");
const useFormCommonProps = require("../../../form/src/hooks/use-form-common-props.js");
const useFormItem = require("../../../form/src/hooks/use-form-item.js");
const index$5 = require("../../../tooltip/index.js");
const index$6 = require("../../../input/index.js");
const constants = require("../constants.js");
const utils = require("../utils.js");
const useCommonPicker = require("../composables/use-common-picker.js");
const props = require("./props.js");
const pickerRangeTrigger = require("./picker-range-trigger.js");
const index$4 = require("../../../../../node_modules/@vueuse/core/index.js");
const index$3 = require("../../../../../../@element-plus/icons-vue/dist/index.js");
const Vue = require("vue");
var picker_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ Vue.defineComponent({
  name: "Picker",
  __name: "picker",
  props: props.timePickerDefaultProps,
  emits: [
    event.UPDATE_MODEL_EVENT,
    event.CHANGE_EVENT,
    "focus",
    "blur",
    "clear",
    "calendar-change",
    "panel-change",
    "visible-change",
    "keydown"
  ],
  setup(__props, { expose: __expose, emit: __emit }) {
    const props2 = __props;
    const emit = __emit;
    const attrs = Vue.useAttrs();
    const nsDate = index.useNamespace("date");
    const nsInput = index.useNamespace("input");
    const nsRange = index.useNamespace("range");
    const { formItem } = useFormItem.useFormItem();
    const elPopperOptions = Vue.inject(constants.PICKER_POPPER_OPTIONS_INJECTION_KEY, {});
    const emptyValues = index$1.useEmptyValues(props2, null);
    const refPopper = Vue.ref();
    const inputRef = Vue.ref();
    const valueOnOpen = Vue.ref(null);
    let hasJustTabExitedInput = false;
    const pickerDisabled = useFormCommonProps.useFormDisabled();
    const commonPicker = useCommonPicker.useCommonPicker(props2, emit);
    const { parsedValue, pickerActualVisible, userInput, pickerVisible, pickerOptions, valueIsEmpty, emitInput, onPick, onSetPickerOption, onCalendarChange, onPanelChange } = commonPicker;
    const { isFocused, handleFocus, handleBlur } = index$2.useFocusController(inputRef, {
      disabled: pickerDisabled,
      beforeFocus() {
        return props2.readonly;
      },
      afterFocus() {
        if (!props2.automaticDropdown) return;
        pickerVisible.value = true;
      },
      beforeBlur(event2) {
        var _a;
        return !hasJustTabExitedInput && ((_a = refPopper.value) == null ? void 0 : _a.isFocusInsideContent(event2));
      },
      afterBlur() {
        var _a, _b;
        if (isTimePicker.value && !props2.saveOnBlur) {
          if (!valueIsEmpty.value) (_b = (_a = pickerOptions.value).handleCancel) == null ? void 0 : _b.call(_a);
        } else handleChange();
        pickerVisible.value = false;
        hasJustTabExitedInput = false;
        props2.validateEvent && (formItem == null ? void 0 : formItem.validate("blur").catch((err) => error.debugWarn(err)));
      }
    });
    const hovering = Vue.ref(false);
    const rangeInputKls = Vue.computed(() => [
      nsDate.b("editor"),
      nsDate.bm("editor", props2.type),
      nsInput.e("wrapper"),
      nsDate.is("disabled", pickerDisabled.value),
      nsDate.is("active", pickerVisible.value),
      nsRange.b("editor"),
      pickerSize ? nsRange.bm("editor", pickerSize.value) : "",
      attrs.class
    ]);
    const clearIconKls = Vue.computed(() => [
      nsInput.e("icon"),
      nsRange.e("close-icon"),
      !showClearBtn.value ? nsRange.em("close-icon", "hidden") : ""
    ]);
    Vue.watch(pickerVisible, (val) => {
      if (!val) {
        userInput.value = null;
        Vue.nextTick(() => {
          emitChange(props2.modelValue);
        });
      } else Vue.nextTick(() => {
        if (val) valueOnOpen.value = props2.modelValue;
      });
    });
    const emitChange = (val, isClear) => {
      if (isClear || !utils.valueEquals(val, valueOnOpen.value)) {
        emit(event.CHANGE_EVENT, val);
        isClear && (valueOnOpen.value = val);
        props2.validateEvent && (formItem == null ? void 0 : formItem.validate("change").catch((err) => error.debugWarn(err)));
      }
    };
    const emitKeydown = (e) => {
      emit("keydown", e);
    };
    const refInput = Vue.computed(() => {
      if (inputRef.value) return Array.from(inputRef.value.$el.querySelectorAll("input"));
      return [];
    });
    const setSelectionRange = (start, end, pos) => {
      const _inputs = refInput.value;
      if (!_inputs.length) return;
      if (!pos || pos === "min") {
        _inputs[0].setSelectionRange(start, end);
        _inputs[0].focus();
      } else if (pos === "max") {
        _inputs[1].setSelectionRange(start, end);
        _inputs[1].focus();
      }
    };
    const onBeforeShow = () => {
      pickerActualVisible.value = true;
    };
    const onShow = () => {
      emit("visible-change", true);
    };
    const onHide = () => {
      pickerActualVisible.value = false;
      pickerVisible.value = false;
      emit("visible-change", false);
    };
    const handleOpen = () => {
      pickerVisible.value = true;
    };
    const handleClose = () => {
      pickerVisible.value = false;
    };
    const displayValue = Vue.computed(() => {
      const formattedValue = formatToString(parsedValue.value);
      if (shared_esmBundler.isArray(userInput.value)) return [userInput.value[0] || formattedValue && formattedValue[0] || "", userInput.value[1] || formattedValue && formattedValue[1] || ""];
      else if (userInput.value !== null) return userInput.value;
      if (isTimePicker.value && valueIsEmpty.value && !props2.saveOnBlur) return "";
      if (!isTimePicker.value && valueIsEmpty.value) return "";
      if (!pickerVisible.value && valueIsEmpty.value) return "";
      if (formattedValue) return isDatesPicker.value || isMonthsPicker.value || isYearsPicker.value ? formattedValue.join(", ") : formattedValue;
      return "";
    });
    const isTimeLikePicker = Vue.computed(() => props2.type.includes("time"));
    const isTimePicker = Vue.computed(() => props2.type.startsWith("time"));
    const isDatesPicker = Vue.computed(() => props2.type === "dates");
    const isMonthsPicker = Vue.computed(() => props2.type === "months");
    const isYearsPicker = Vue.computed(() => props2.type === "years");
    const triggerIcon = Vue.computed(() => props2.prefixIcon || (isTimeLikePicker.value ? index$3.Clock : index$3.Calendar));
    const showClearBtn = Vue.computed(() => props2.clearable && !pickerDisabled.value && !props2.readonly && !valueIsEmpty.value && (hovering.value || isFocused.value));
    const onClear = (event2) => {
      if (props2.readonly || pickerDisabled.value) return;
      if (showClearBtn.value) {
        event2 == null ? void 0 : event2.stopPropagation();
        if (pickerOptions.value.handleClear) pickerOptions.value.handleClear();
        else emitInput(emptyValues.valueOnClear.value);
        emitChange(emptyValues.valueOnClear.value, true);
        onHide();
      }
      emit("clear");
    };
    const onMouseDownInput = async (event2) => {
      var _a;
      if (props2.readonly || pickerDisabled.value) return;
      if (((_a = event2.target) == null ? void 0 : _a.tagName) !== "INPUT" || isFocused.value || !props2.automaticDropdown) pickerVisible.value = true;
    };
    const onMouseEnter = () => {
      if (props2.readonly || pickerDisabled.value) return;
      if (!valueIsEmpty.value && props2.clearable) hovering.value = true;
    };
    const onMouseLeave = () => {
      hovering.value = false;
    };
    const onTouchStartInput = (event2) => {
      var _a;
      if (props2.readonly || pickerDisabled.value) return;
      if (((_a = event2.touches[0].target) == null ? void 0 : _a.tagName) !== "INPUT" || isFocused.value || !props2.automaticDropdown) pickerVisible.value = true;
    };
    const isRangeInput = Vue.computed(() => {
      return props2.type.includes("range");
    });
    const pickerSize = useFormCommonProps.useFormSize();
    const popperEl = Vue.computed(() => {
      var _a, _b;
      return (_b = (_a = Vue.unref(refPopper)) == null ? void 0 : _a.popperRef) == null ? void 0 : _b.contentRef;
    });
    const stophandle = index$4.onClickOutside(inputRef, (e) => {
      const unrefedPopperEl = Vue.unref(popperEl);
      const inputEl = index$4.unrefElement(inputRef);
      if (unrefedPopperEl && (e.target === unrefedPopperEl || e.composedPath().includes(unrefedPopperEl)) || e.target === inputEl || inputEl && e.composedPath().includes(inputEl)) return;
      pickerVisible.value = false;
    });
    Vue.onBeforeUnmount(() => {
      stophandle == null ? void 0 : stophandle();
    });
    const handleChange = () => {
      if (isTimePicker.value && !props2.saveOnBlur) return;
      if (userInput.value) {
        const value = parseUserInputToDayjs(displayValue.value);
        if (value) {
          if (isValidValue(value)) emitInput(utils.dayOrDaysToDate(value));
          userInput.value = null;
        }
      }
      if (userInput.value === "") {
        emitInput(emptyValues.valueOnClear.value);
        emitChange(emptyValues.valueOnClear.value, true);
        userInput.value = null;
      }
    };
    const parseUserInputToDayjs = (value) => {
      if (!value) return null;
      return pickerOptions.value.parseUserInput(value);
    };
    const formatToString = (value) => {
      if (!value) return null;
      return shared_esmBundler.isArray(value) ? value.map((_) => _.format(props2.format)) : value.format(props2.format);
    };
    const isValidValue = (value) => {
      return pickerOptions.value.isValidValue(value);
    };
    const handleKeydownInput = async (event2) => {
      if (props2.readonly || pickerDisabled.value) return;
      const code = event$1.getEventCode(event2);
      emitKeydown(event2);
      if (code === aria.EVENT_CODE.esc) {
        if (pickerVisible.value === true) {
          pickerVisible.value = false;
          event2.preventDefault();
          event2.stopPropagation();
        }
        return;
      }
      if (code === aria.EVENT_CODE.down) {
        if (pickerOptions.value.handleFocusPicker) {
          event2.preventDefault();
          event2.stopPropagation();
        }
        if (pickerVisible.value === false) {
          pickerVisible.value = true;
          await Vue.nextTick();
        }
        if (pickerOptions.value.handleFocusPicker) {
          pickerOptions.value.handleFocusPicker();
          return;
        }
      }
      if (code === aria.EVENT_CODE.tab) {
        hasJustTabExitedInput = true;
        return;
      }
      if (code === aria.EVENT_CODE.enter || code === aria.EVENT_CODE.numpadEnter) {
        if (!pickerVisible.value) pickerVisible.value = true;
        else if (userInput.value === null || userInput.value === "" || isValidValue(parseUserInputToDayjs(displayValue.value))) {
          handleChange();
          pickerVisible.value = false;
        }
        event2.preventDefault();
        event2.stopPropagation();
        return;
      }
      if (userInput.value) {
        event2.stopPropagation();
        return;
      }
      if (pickerOptions.value.handleKeydownInput) pickerOptions.value.handleKeydownInput(event2);
    };
    const onUserInput = (e) => {
      userInput.value = e;
      if (!pickerVisible.value) pickerVisible.value = true;
    };
    const handleStartInput = (event2) => {
      const target = event2.target;
      if (userInput.value) userInput.value = [target.value, userInput.value[1]];
      else userInput.value = [target.value, null];
    };
    const handleEndInput = (event2) => {
      const target = event2.target;
      if (userInput.value) userInput.value = [userInput.value[0], target.value];
      else userInput.value = [null, target.value];
    };
    const handleStartChange = () => {
      var _a;
      const values = userInput.value;
      const value = parseUserInputToDayjs(values && values[0]);
      const parsedVal = Vue.unref(parsedValue);
      if (value && value.isValid()) {
        userInput.value = [formatToString(value), ((_a = displayValue.value) == null ? void 0 : _a[1]) || null];
        const newValue = [value, parsedVal && (parsedVal[1] || null)];
        if (isValidValue(newValue)) {
          emitInput(utils.dayOrDaysToDate(newValue));
          userInput.value = null;
        }
      }
    };
    const handleEndChange = () => {
      var _a;
      const values = Vue.unref(userInput);
      const value = parseUserInputToDayjs(values && values[1]);
      const parsedVal = Vue.unref(parsedValue);
      if (value && value.isValid()) {
        userInput.value = [((_a = Vue.unref(displayValue)) == null ? void 0 : _a[0]) || null, formatToString(value)];
        const newValue = [parsedVal && parsedVal[0], value];
        if (isValidValue(newValue)) {
          emitInput(utils.dayOrDaysToDate(newValue));
          userInput.value = null;
        }
      }
    };
    const focus = () => {
      var _a;
      (_a = inputRef.value) == null ? void 0 : _a.focus();
    };
    const blur = () => {
      var _a;
      (_a = inputRef.value) == null ? void 0 : _a.blur();
    };
    Vue.provide(constants.PICKER_BASE_INJECTION_KEY, {
      props: props2,
      emptyValues
    });
    Vue.provide(constants.ROOT_COMMON_PICKER_INJECTION_KEY, commonPicker);
    __expose({
      focus,
      blur,
      handleOpen,
      handleClose,
      onPick
    });
    return (_ctx, _cache) => {
      return Vue.openBlock(), Vue.createBlock(Vue.unref(index$5.ElTooltip), Vue.mergeProps({
        ref_key: "refPopper",
        ref: refPopper,
        visible: Vue.unref(pickerVisible),
        effect: "light",
        pure: "",
        trigger: "click"
      }, _ctx.$attrs, {
        role: "dialog",
        teleported: "",
        transition: `${Vue.unref(nsDate).namespace.value}-zoom-in-top`,
        "popper-class": [`${Vue.unref(nsDate).namespace.value}-picker__popper`, _ctx.popperClass],
        "popper-style": _ctx.popperStyle,
        "popper-options": Vue.unref(elPopperOptions),
        "fallback-placements": _ctx.fallbackPlacements,
        "gpu-acceleration": false,
        placement: _ctx.placement,
        "stop-popper-mouse-event": false,
        "hide-after": 0,
        persistent: "",
        onBeforeShow,
        onShow,
        onHide
      }), {
        default: Vue.withCtx(() => [!isRangeInput.value ? (Vue.openBlock(), Vue.createBlock(Vue.unref(index$6.ElInput), {
          key: 0,
          id: _ctx.id,
          ref_key: "inputRef",
          ref: inputRef,
          "container-role": "combobox",
          "model-value": displayValue.value,
          name: _ctx.name,
          size: Vue.unref(pickerSize),
          disabled: Vue.unref(pickerDisabled),
          placeholder: _ctx.placeholder,
          class: Vue.normalizeClass([
            Vue.unref(nsDate).b("editor"),
            Vue.unref(nsDate).bm("editor", _ctx.type),
            Vue.unref(nsDate).is("focus", Vue.unref(pickerVisible)),
            _ctx.$attrs.class
          ]),
          style: Vue.normalizeStyle(_ctx.$attrs.style),
          readonly: !_ctx.editable || _ctx.readonly || isDatesPicker.value || isMonthsPicker.value || isYearsPicker.value || _ctx.type === "week",
          "aria-label": _ctx.ariaLabel,
          tabindex: _ctx.tabindex,
          "validate-event": false,
          onInput: onUserInput,
          onFocus: Vue.unref(handleFocus),
          onBlur: Vue.unref(handleBlur),
          onKeydown: handleKeydownInput,
          onChange: handleChange,
          onMousedown: onMouseDownInput,
          onMouseenter: onMouseEnter,
          onMouseleave: onMouseLeave,
          onTouchstartPassive: onTouchStartInput,
          onClick: _cache[0] || (_cache[0] = Vue.withModifiers(() => {
          }, ["stop"]))
        }, {
          prefix: Vue.withCtx(() => [triggerIcon.value ? (Vue.openBlock(), Vue.createBlock(Vue.unref(index$7.ElIcon), {
            key: 0,
            class: Vue.normalizeClass(Vue.unref(nsInput).e("icon")),
            onMousedown: Vue.withModifiers(onMouseDownInput, ["prevent"]),
            onTouchstartPassive: onTouchStartInput
          }, {
            default: Vue.withCtx(() => [(Vue.openBlock(), Vue.createBlock(Vue.resolveDynamicComponent(triggerIcon.value)))]),
            _: 1
          }, 8, ["class"])) : Vue.createCommentVNode("v-if", true)]),
          suffix: Vue.withCtx(() => [showClearBtn.value && _ctx.clearIcon ? (Vue.openBlock(), Vue.createBlock(Vue.unref(index$7.ElIcon), {
            key: 0,
            class: Vue.normalizeClass(`${Vue.unref(nsInput).e("icon")} clear-icon`),
            onMousedown: Vue.withModifiers(Vue.unref(shared_esmBundler.NOOP), ["prevent"]),
            onClick: onClear
          }, {
            default: Vue.withCtx(() => [(Vue.openBlock(), Vue.createBlock(Vue.resolveDynamicComponent(_ctx.clearIcon)))]),
            _: 1
          }, 8, ["class", "onMousedown"])) : Vue.createCommentVNode("v-if", true)]),
          _: 1
        }, 8, [
          "id",
          "model-value",
          "name",
          "size",
          "disabled",
          "placeholder",
          "class",
          "style",
          "readonly",
          "aria-label",
          "tabindex",
          "onFocus",
          "onBlur"
        ])) : (Vue.openBlock(), Vue.createBlock(pickerRangeTrigger.default, {
          key: 1,
          id: _ctx.id,
          ref_key: "inputRef",
          ref: inputRef,
          "model-value": displayValue.value,
          name: _ctx.name,
          disabled: Vue.unref(pickerDisabled),
          readonly: !_ctx.editable || _ctx.readonly,
          "start-placeholder": _ctx.startPlaceholder,
          "end-placeholder": _ctx.endPlaceholder,
          class: Vue.normalizeClass(rangeInputKls.value),
          style: Vue.normalizeStyle(_ctx.$attrs.style),
          "aria-label": _ctx.ariaLabel,
          tabindex: _ctx.tabindex,
          autocomplete: "off",
          role: "combobox",
          onClick: onMouseDownInput,
          onFocus: Vue.unref(handleFocus),
          onBlur: Vue.unref(handleBlur),
          onStartInput: handleStartInput,
          onStartChange: handleStartChange,
          onEndInput: handleEndInput,
          onEndChange: handleEndChange,
          onMousedown: onMouseDownInput,
          onMouseenter: onMouseEnter,
          onMouseleave: onMouseLeave,
          onTouchstartPassive: onTouchStartInput,
          onKeydown: handleKeydownInput
        }, {
          prefix: Vue.withCtx(() => [triggerIcon.value ? (Vue.openBlock(), Vue.createBlock(Vue.unref(index$7.ElIcon), {
            key: 0,
            class: Vue.normalizeClass([Vue.unref(nsInput).e("icon"), Vue.unref(nsRange).e("icon")])
          }, {
            default: Vue.withCtx(() => [(Vue.openBlock(), Vue.createBlock(Vue.resolveDynamicComponent(triggerIcon.value)))]),
            _: 1
          }, 8, ["class"])) : Vue.createCommentVNode("v-if", true)]),
          "range-separator": Vue.withCtx(() => [Vue.renderSlot(_ctx.$slots, "range-separator", {}, () => [Vue.createElementVNode("span", { class: Vue.normalizeClass(Vue.unref(nsRange).b("separator")) }, Vue.toDisplayString(_ctx.rangeSeparator), 3)])]),
          suffix: Vue.withCtx(() => [_ctx.clearIcon ? (Vue.openBlock(), Vue.createBlock(Vue.unref(index$7.ElIcon), {
            key: 0,
            class: Vue.normalizeClass(clearIconKls.value),
            onMousedown: Vue.withModifiers(Vue.unref(shared_esmBundler.NOOP), ["prevent"]),
            onClick: onClear
          }, {
            default: Vue.withCtx(() => [(Vue.openBlock(), Vue.createBlock(Vue.resolveDynamicComponent(_ctx.clearIcon)))]),
            _: 1
          }, 8, ["class", "onMousedown"])) : Vue.createCommentVNode("v-if", true)]),
          _: 3
        }, 8, [
          "id",
          "model-value",
          "name",
          "disabled",
          "readonly",
          "start-placeholder",
          "end-placeholder",
          "class",
          "style",
          "aria-label",
          "tabindex",
          "onFocus",
          "onBlur"
        ]))]),
        content: Vue.withCtx(() => [Vue.renderSlot(_ctx.$slots, "default", {
          visible: Vue.unref(pickerVisible),
          actualVisible: Vue.unref(pickerActualVisible),
          parsedValue: Vue.unref(parsedValue),
          format: _ctx.format,
          dateFormat: _ctx.dateFormat,
          timeFormat: _ctx.timeFormat,
          unlinkPanels: _ctx.unlinkPanels,
          type: _ctx.type,
          defaultValue: _ctx.defaultValue,
          showNow: _ctx.showNow,
          showConfirm: _ctx.showConfirm,
          showFooter: _ctx.showFooter,
          showWeekNumber: _ctx.showWeekNumber,
          onPick: _cache[1] || (_cache[1] = (...args) => Vue.unref(onPick) && Vue.unref(onPick)(...args)),
          onSelectRange: setSelectionRange,
          onSetPickerOption: _cache[2] || (_cache[2] = (...args) => Vue.unref(onSetPickerOption) && Vue.unref(onSetPickerOption)(...args)),
          onCalendarChange: _cache[3] || (_cache[3] = (...args) => Vue.unref(onCalendarChange) && Vue.unref(onCalendarChange)(...args)),
          onClear,
          onPanelChange: _cache[4] || (_cache[4] = (...args) => Vue.unref(onPanelChange) && Vue.unref(onPanelChange)(...args)),
          onMousedown: _cache[5] || (_cache[5] = Vue.withModifiers(() => {
          }, ["stop"]))
        })]),
        _: 3
      }, 16, [
        "visible",
        "transition",
        "popper-class",
        "popper-style",
        "popper-options",
        "fallback-placements",
        "placement"
      ]);
    };
  }
});
exports.default = picker_vue_vue_type_script_setup_true_lang_default;
