import { createElementVNode, defineComponent, ref, reactive, computed, watch, onMounted, onUpdated, openBlock, createElementBlock, normalizeClass, unref, withModifiers, withDirectives, withKeys, createBlock, withCtx, createCommentVNode, createVNode } from 'vue';
import { isNil } from 'lodash-unified';
import { ElInput } from '../../input/index.mjs';
import { ElIcon } from '../../icon/index.mjs';
import '../../../directives/index.mjs';
import '../../../hooks/index.mjs';
import '../../../utils/index.mjs';
import { ArrowDown, Minus, ArrowUp, Plus } from '@element-plus/icons-vue';
import '../../../constants/index.mjs';
import { inputNumberProps, inputNumberEmits } from './input-number2.mjs';
import _export_sfc from '../../../_virtual/plugin-vue_export-helper.mjs';
import { useLocale } from '../../../hooks/use-locale/index.mjs';
import { useNamespace } from '../../../hooks/use-namespace/index.mjs';
import { useFormItem } from '../../../hooks/use-form-item/index.mjs';
import { isNumber } from '@vueuse/core';
import { isUndefined } from '../../../utils/types.mjs';
import { debugWarn } from '../../../utils/error.mjs';
import { useSize, useDisabled } from '../../../hooks/use-common-props/index.mjs';
import { INPUT_EVENT, UPDATE_MODEL_EVENT, CHANGE_EVENT } from '../../../constants/event.mjs';
import { isString } from '@vue/shared';
import { vRepeatClick } from '../../../directives/repeat-click/index.mjs';

const _hoisted_1 = ["aria-label", "onKeydown"];
const _hoisted_2 = {
  key: 1,
  viewBox: "0 0 7 1",
  xmlns: "http://www.w3.org/2000/svg"
};
const _hoisted_3 = /* @__PURE__ */ createElementVNode("path", {
  height: "1",
  fill: "currentColor",
  d: "M0.172 1.016C0.0573333 0.901333 0 0.760667 0 0.594C0 0.427333 0.0573333 0.286667 0.172 0.172C0.286667 0.0573333 0.427333 0 0.594 0H6.4065C6.57317 0 6.71383 0.0573333 6.8285 0.172C6.94317 0.286667 7.0005 0.427333 7.0005 0.594C7.0005 0.760667 6.94317 0.901333 6.8285 1.016C6.71383 1.13067 6.57317 1.188 6.4065 1.188H0.594C0.427333 1.188 0.286667 1.13067 0.172 1.016Z"
}, null, -1);
const _hoisted_4 = [
  _hoisted_3
];
const _hoisted_5 = ["aria-label", "onKeydown"];
const _hoisted_6 = {
  key: 1,
  xmlns: "http://www.w3.org/2000/svg",
  viewBox: "0 0 8 8"
};
const _hoisted_7 = /* @__PURE__ */ createElementVNode("path", {
  d: "M1.094 3.406h2.313V1.095c0-.167.057-.307.171-.422A.574.574 0 014 .5c.167 0 .308.057.423.172a.574.574 0 01.171.422v2.313h2.313c.167 0 .307.057.422.171A.574.574 0 017.501 4a.574.574 0 01-.172.423.574.574 0 01-.422.171H4.594v2.313a.574.574 0 01-.171.422.574.574 0 01-.423.172.574.574 0 01-.421-.172.574.574 0 01-.173-.422V4.594H1.095a.574.574 0 01-.422-.171A.574.574 0 01.5 4a.57.57 0 01.172-.421.574.574 0 01.422-.173z",
  fill: "#currentColor"
}, null, -1);
const _hoisted_8 = [
  _hoisted_7
];
const __default__ = defineComponent({
  name: "ElInputNumber"
});
const _sfc_main = /* @__PURE__ */ defineComponent({
  ...__default__,
  props: inputNumberProps,
  emits: inputNumberEmits,
  setup(__props, { expose, emit }) {
    const props = __props;
    const { t } = useLocale();
    const ns = useNamespace("input-number");
    const input = ref();
    const data = reactive({
      currentValue: props.modelValue,
      userInput: null
    });
    const { formItem } = useFormItem();
    const minDisabled = computed(() => isNumber(props.modelValue) && ensurePrecision(props.modelValue, -1) < props.min);
    const maxDisabled = computed(() => isNumber(props.modelValue) && ensurePrecision(props.modelValue) > props.max);
    const numPrecision = computed(() => {
      const stepPrecision = getPrecision(props.step);
      if (!isUndefined(props.precision)) {
        if (stepPrecision > props.precision) {
          debugWarn("InputNumber", "precision should not be less than the decimal places of step");
        }
        return props.precision;
      } else {
        return Math.max(getPrecision(props.modelValue), stepPrecision);
      }
    });
    const controlsAtRight = computed(() => {
      return props.controls && props.controlsPosition === "right";
    });
    const isBorder = computed(() => {
      return props.border;
    });
    const inputNumberSize = useSize();
    const inputNumberDisabled = useDisabled();
    const displayValue = computed(() => {
      if (data.userInput !== null) {
        return data.userInput;
      }
      let currentValue = data.currentValue;
      if (isNil(currentValue))
        return "";
      if (isNumber(currentValue)) {
        if (Number.isNaN(currentValue))
          return "";
        if (!isUndefined(props.precision)) {
          currentValue = currentValue.toFixed(props.precision);
        }
      }
      return currentValue;
    });
    const toPrecision = (num, pre) => {
      if (isUndefined(pre))
        pre = numPrecision.value;
      if (pre === 0)
        return Math.round(num);
      let snum = String(num);
      const pointPos = snum.indexOf(".");
      if (pointPos === -1)
        return num;
      const nums = snum.replace(".", "").split("");
      const datum = nums[pointPos + pre];
      if (!datum)
        return num;
      const length = snum.length;
      if (snum.charAt(length - 1) === "5") {
        snum = `${snum.slice(0, Math.max(0, length - 1))}6`;
      }
      return Number.parseFloat(Number(snum).toFixed(pre));
    };
    const getPrecision = (value) => {
      if (isNil(value))
        return 0;
      const valueString = value.toString();
      const dotPosition = valueString.indexOf(".");
      let precision = 0;
      if (dotPosition !== -1) {
        precision = valueString.length - dotPosition - 1;
      }
      return precision;
    };
    const ensurePrecision = (val, coefficient = 1) => {
      if (!isNumber(val))
        return data.currentValue;
      return toPrecision(val + props.step * coefficient);
    };
    const increase = () => {
      if (props.readonly || inputNumberDisabled.value || maxDisabled.value)
        return;
      const value = Number(displayValue.value) || 0;
      const newVal = ensurePrecision(value);
      setCurrentValue(newVal);
      emit(INPUT_EVENT, data.currentValue);
    };
    const decrease = () => {
      if (props.readonly || inputNumberDisabled.value || minDisabled.value)
        return;
      const value = Number(displayValue.value) || 0;
      const newVal = ensurePrecision(value, -1);
      setCurrentValue(newVal);
      emit(INPUT_EVENT, data.currentValue);
    };
    const verifyValue = (value, update) => {
      const { max, min, step, precision, stepStrictly, valueOnClear } = props;
      let newVal = Number(value);
      if (isNil(value) || Number.isNaN(newVal)) {
        return null;
      }
      if (value === "") {
        if (valueOnClear === null) {
          return null;
        }
        newVal = isString(valueOnClear) ? { min, max }[valueOnClear] : valueOnClear;
      }
      if (stepStrictly) {
        newVal = toPrecision(Math.round(newVal / step) * step, precision);
      }
      if (!isUndefined(precision)) {
        newVal = toPrecision(newVal, precision);
      }
      if (newVal > max || newVal < min) {
        newVal = newVal > max ? max : min;
        update && emit(UPDATE_MODEL_EVENT, newVal);
      }
      return newVal;
    };
    const setCurrentValue = (value) => {
      var _a;
      const oldVal = data.currentValue;
      const newVal = verifyValue(value);
      if (oldVal === newVal)
        return;
      data.userInput = null;
      emit(UPDATE_MODEL_EVENT, newVal);
      emit(CHANGE_EVENT, newVal, oldVal);
      if (props.validateEvent) {
        (_a = formItem == null ? void 0 : formItem.validate) == null ? void 0 : _a.call(formItem, "change").catch((err) => debugWarn(err));
      }
      data.currentValue = newVal;
    };
    const handleInput = (value) => {
      data.userInput = value;
      emit(INPUT_EVENT, value === "" ? null : Number(value));
    };
    const handleInputChange = (value) => {
      const newVal = value !== "" ? Number(value) : "";
      if (isNumber(newVal) && !Number.isNaN(newVal) || value === "") {
        setCurrentValue(newVal);
      }
      data.userInput = null;
    };
    const focus = () => {
      var _a, _b;
      (_b = (_a = input.value) == null ? void 0 : _a.focus) == null ? void 0 : _b.call(_a);
    };
    const blur = () => {
      var _a, _b;
      (_b = (_a = input.value) == null ? void 0 : _a.blur) == null ? void 0 : _b.call(_a);
    };
    const handleFocus = (event) => {
      emit("focus", event);
    };
    const handleBlur = (event) => {
      var _a;
      emit("blur", event);
      if (props.validateEvent) {
        (_a = formItem == null ? void 0 : formItem.validate) == null ? void 0 : _a.call(formItem, "blur").catch((err) => debugWarn(err));
      }
    };
    watch(() => props.modelValue, (value) => {
      data.currentValue = verifyValue(value, true);
      data.userInput = null;
    }, { immediate: true });
    onMounted(() => {
      var _a;
      const { min, max, modelValue } = props;
      const innerInput = (_a = input.value) == null ? void 0 : _a.input;
      innerInput.setAttribute("role", "spinbutton");
      if (Number.isFinite(max)) {
        innerInput.setAttribute("aria-valuemax", String(max));
      } else {
        innerInput.removeAttribute("aria-valuemax");
      }
      if (Number.isFinite(min)) {
        innerInput.setAttribute("aria-valuemin", String(min));
      } else {
        innerInput.removeAttribute("aria-valuemin");
      }
      innerInput.setAttribute("aria-valuenow", String(data.currentValue));
      innerInput.setAttribute("aria-disabled", String(inputNumberDisabled.value));
      if (!isNumber(modelValue) && modelValue != null) {
        let val = Number(modelValue);
        if (Number.isNaN(val)) {
          val = null;
        }
        emit(UPDATE_MODEL_EVENT, val);
      }
    });
    onUpdated(() => {
      var _a;
      const innerInput = (_a = input.value) == null ? void 0 : _a.input;
      innerInput == null ? void 0 : innerInput.setAttribute("aria-valuenow", `${data.currentValue}`);
    });
    expose({
      focus,
      blur
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        class: normalizeClass([
          unref(ns).b(),
          unref(ns).m(unref(inputNumberSize)),
          unref(ns).is("disabled", unref(inputNumberDisabled)),
          unref(ns).is("without-controls", !_ctx.controls),
          unref(ns).is("controls-right", unref(controlsAtRight)),
          unref(ns).is("without-border", !unref(isBorder))
        ]),
        onDragstart: _cache[0] || (_cache[0] = withModifiers(() => {
        }, ["prevent"]))
      }, [
        _ctx.controls ? withDirectives((openBlock(), createElementBlock("span", {
          key: 0,
          role: "button",
          "aria-label": unref(t)("el.inputNumber.decrease"),
          class: normalizeClass([unref(ns).e("decrease"), unref(ns).is("disabled", unref(minDisabled))]),
          onKeydown: withKeys(decrease, ["enter"])
        }, [
          unref(isBorder) ? (openBlock(), createBlock(unref(ElIcon), { key: 0 }, {
            default: withCtx(() => [
              unref(controlsAtRight) ? (openBlock(), createBlock(unref(ArrowDown), { key: 0 })) : (openBlock(), createBlock(unref(Minus), { key: 1 }))
            ]),
            _: 1
          })) : (openBlock(), createBlock(unref(ElIcon), {
            key: 1,
            size: 7
          }, {
            default: withCtx(() => [
              unref(controlsAtRight) ? (openBlock(), createBlock(unref(ArrowDown), { key: 0 })) : (openBlock(), createElementBlock("svg", _hoisted_2, _hoisted_4))
            ]),
            _: 1
          }))
        ], 42, _hoisted_1)), [
          [unref(vRepeatClick), decrease]
        ]) : createCommentVNode("v-if", true),
        _ctx.controls ? withDirectives((openBlock(), createElementBlock("span", {
          key: 1,
          role: "button",
          "aria-label": unref(t)("el.inputNumber.increase"),
          class: normalizeClass([unref(ns).e("increase"), unref(ns).is("disabled", unref(maxDisabled))]),
          onKeydown: withKeys(increase, ["enter"])
        }, [
          unref(isBorder) ? (openBlock(), createBlock(unref(ElIcon), { key: 0 }, {
            default: withCtx(() => [
              unref(controlsAtRight) ? (openBlock(), createBlock(unref(ArrowUp), { key: 0 })) : (openBlock(), createBlock(unref(Plus), { key: 1 }))
            ]),
            _: 1
          })) : (openBlock(), createBlock(unref(ElIcon), {
            key: 1,
            size: 7
          }, {
            default: withCtx(() => [
              unref(controlsAtRight) ? (openBlock(), createBlock(unref(ArrowUp), { key: 0 })) : (openBlock(), createElementBlock("svg", _hoisted_6, _hoisted_8))
            ]),
            _: 1
          }))
        ], 42, _hoisted_5)), [
          [unref(vRepeatClick), increase]
        ]) : createCommentVNode("v-if", true),
        createVNode(unref(ElInput), {
          id: _ctx.id,
          ref_key: "input",
          ref: input,
          type: "number",
          step: _ctx.step,
          "model-value": unref(displayValue),
          placeholder: _ctx.placeholder,
          readonly: _ctx.readonly,
          disabled: unref(inputNumberDisabled),
          size: unref(inputNumberSize),
          max: _ctx.max,
          min: _ctx.min,
          name: _ctx.name,
          label: _ctx.label,
          "number-valid": true,
          precision: _ctx.precision,
          "validate-event": false,
          onKeydown: [
            withKeys(withModifiers(increase, ["prevent"]), ["up"]),
            withKeys(withModifiers(decrease, ["prevent"]), ["down"])
          ],
          onBlur: handleBlur,
          onFocus: handleFocus,
          onInput: handleInput,
          onChange: handleInputChange
        }, null, 8, ["id", "step", "model-value", "placeholder", "readonly", "disabled", "size", "max", "min", "name", "label", "precision", "onKeydown"])
      ], 34);
    };
  }
});
var InputNumber = /* @__PURE__ */ _export_sfc(_sfc_main, [["__file", "/Users/judai/code/d-element-plus/packages/components/input-number/src/input-number.vue"]]);

export { InputNumber as default };
//# sourceMappingURL=input-number.mjs.map
