import { defineComponent, inject, ref, computed, openBlock, createElementBlock, normalizeClass, unref, normalizeStyle, Fragment, renderList, createVNode, withCtx, createBlock, resolveDynamicComponent, createCommentVNode, toDisplayString } from 'vue';
import '../../../utils/index.mjs';
import '../../../tokens/index.mjs';
import { PsIcon } from '../../icon/index.mjs';
import '../../../hooks/index.mjs';
import { rateProps } from './rate2.mjs';
import _export_sfc from '../../../_virtual/plugin-vue_export-helper.mjs';
import { isObject, isArray } from '@vue/shared';
import { formContextKey } from '../../../tokens/form.mjs';
import { useSize } from '../../../hooks/use-common-props/index.mjs';
import { useNamespace } from '../../../hooks/use-namespace/index.mjs';
import { hasClass } from '../../../utils/dom/style.mjs';

const _hoisted_1 = ["aria-valuenow", "aria-valuetext", "aria-valuemax"];
const __default__ = {
  name: "PsRate"
};
const _sfc_main = /* @__PURE__ */ defineComponent({
  ...__default__,
  props: rateProps,
  setup(__props, { expose }) {
    const props = __props;
    function getValueFromMap(value, map) {
      const isExcludedObject = (val) => isObject(val);
      const matchedKeys = Object.keys(map).map((key) => +key).filter((key) => {
        const val = map[key];
        const excluded = isExcludedObject(val) ? val.excluded : false;
        return excluded ? value < key : value <= key;
      }).sort((a, b) => a - b);
      const matchedValue = map[matchedKeys[0]];
      return isExcludedObject(matchedValue) && matchedValue.value || matchedValue;
    }
    const formContext = inject(formContextKey, void 0);
    const rateSize = useSize();
    const ns = useNamespace("rate");
    const currentValue = ref(props.modelValue);
    const hoverIndex = ref(-1);
    const pointerAtLeftHalf = ref(true);
    const rateClasses = computed(() => [ns.b(), ns.m(rateSize.value)]);
    const rateDisabled = computed(() => props.disabled || (formContext == null ? void 0 : formContext.disabled));
    const rateStyles = computed(() => {
      return {
        "--el-rate-void-color": props.voidColor,
        "--el-rate-disabled-void-color": props.disabledVoidColor,
        "--el-rate-fill-color": activeColor.value
      };
    });
    const text = computed(() => {
      let result = "";
      if (props.showScore) {
        result = props.scoreTemplate.replace(/\{\s*value\s*\}/, rateDisabled.value ? `${props.modelValue}` : `${currentValue.value}`);
      } else if (props.showText) {
        result = props.texts[Math.ceil(currentValue.value) - 1];
      }
      return result;
    });
    const valueDecimal = computed(() => props.modelValue * 100 - Math.floor(props.modelValue) * 100);
    const colorMap = computed(() => isArray(props.colors) ? {
      [props.lowThreshold]: props.colors[0],
      [props.highThreshold]: { value: props.colors[1], excluded: true },
      [props.max]: props.colors[2]
    } : props.colors);
    const activeColor = computed(() => {
      const color = getValueFromMap(currentValue.value, colorMap.value);
      return isObject(color) ? "" : color;
    });
    const decimalStyle = computed(() => {
      let width = "";
      if (rateDisabled.value) {
        width = `${valueDecimal.value}%`;
      } else if (props.allowHalf) {
        width = "50%";
      }
      return {
        color: activeColor.value,
        width
      };
    });
    const componentMap = computed(() => isArray(props.icons) ? {
      [props.lowThreshold]: props.icons[0],
      [props.highThreshold]: {
        value: props.icons[1],
        excluded: true
      },
      [props.max]: props.icons[2]
    } : props.icons);
    const decimalIconComponent = computed(() => getValueFromMap(props.modelValue, componentMap.value));
    const voidComponent = computed(() => rateDisabled.value ? props.disabledVoidIcon : props.voidIcon);
    const activeComponent = computed(() => getValueFromMap(currentValue.value, componentMap.value));
    const iconComponents = computed(() => {
      const result = Array.from({ length: props.max });
      const threshold = currentValue.value;
      result.fill(activeComponent.value, 0, threshold);
      result.fill(voidComponent.value, threshold, props.max);
      return result;
    });
    function showDecimalIcon(item) {
      const showWhenDisabled = rateDisabled.value && valueDecimal.value > 0 && item - 1 < props.modelValue && item > props.modelValue;
      const showWhenAllowHalf = props.allowHalf && pointerAtLeftHalf.value && item - 0.5 <= currentValue.value && item > currentValue.value;
      return showWhenDisabled || showWhenAllowHalf;
    }
    function setCurrentValue(value, event) {
      if (rateDisabled.value) {
        return;
      }
      if (props.allowHalf) {
        let target = event.target;
        if (hasClass(target, ns.e("item"))) {
          target = target.querySelector(`.${ns.e("icon")}`);
        }
        if (target.clientWidth === 0 || hasClass(target, ns.e("decimal"))) {
          target = target.parentNode;
        }
        pointerAtLeftHalf.value = event.offsetX * 2 <= target.clientWidth;
        currentValue.value = pointerAtLeftHalf.value ? value - 0.5 : value;
      } else {
        currentValue.value = value;
      }
      hoverIndex.value = value;
    }
    expose({
      setCurrentValue
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        class: normalizeClass([unref(rateClasses), unref(ns).is("disabled", unref(rateDisabled))]),
        role: "slider",
        "aria-valuenow": currentValue.value,
        "aria-valuetext": unref(text),
        "aria-valuemin": "0",
        "aria-valuemax": _ctx.max,
        tabindex: "0",
        style: normalizeStyle(unref(rateStyles))
      }, [
        (openBlock(true), createElementBlock(Fragment, null, renderList(_ctx.max, (item, key) => {
          return openBlock(), createElementBlock("span", {
            key,
            class: normalizeClass(unref(ns).e("item"))
          }, [
            createVNode(unref(PsIcon), {
              class: normalizeClass([
                unref(ns).e("icon"),
                { hover: hoverIndex.value === item },
                unref(ns).is("active", item <= currentValue.value)
              ])
            }, {
              default: withCtx(() => [
                !showDecimalIcon(item) ? (openBlock(), createBlock(resolveDynamicComponent(unref(iconComponents)[item - 1]), { key: 0 })) : createCommentVNode("v-if", true),
                showDecimalIcon(item) ? (openBlock(), createBlock(unref(PsIcon), {
                  key: 1,
                  style: normalizeStyle(unref(decimalStyle)),
                  class: normalizeClass([unref(ns).e("icon"), unref(ns).e("decimal")])
                }, {
                  default: withCtx(() => [
                    (openBlock(), createBlock(resolveDynamicComponent(unref(decimalIconComponent))))
                  ]),
                  _: 1
                }, 8, ["style", "class"])) : createCommentVNode("v-if", true)
              ]),
              _: 2
            }, 1032, ["class"])
          ], 2);
        }), 128)),
        _ctx.showText || _ctx.showScore ? (openBlock(), createElementBlock("span", {
          key: 0,
          class: normalizeClass(unref(ns).e("text"))
        }, toDisplayString(unref(text)), 3)) : createCommentVNode("v-if", true)
      ], 14, _hoisted_1);
    };
  }
});
var Rate = /* @__PURE__ */ _export_sfc(_sfc_main, [["__file", "/Users/meng/workspace/element-ps/packages/components/rate/src/rate.vue"]]);

export { Rate as default };
//# sourceMappingURL=rate.mjs.map
