import { mergeProps as _mergeProps, createVNode as _createVNode } from "vue";
import { defineComponent, reactive, watch, getCurrentInstance } from "vue";
import { getComponent } from '../_util/props-util';
import Star from './Star';
import Icon from '../icon';
const Rate = defineComponent({
  name: 'x-rate',
  props: {
    prefixCls: {
      default: 'x-rate'
    },
    value: Number,
    character: String,
    count: {
      default: 5
    },
    color: String,
    allowHalf: Boolean,
    disabled: Boolean
  },
  emits: ['update:value', 'change', 'hoverChange'],

  setup(props, {
    emit
  }) {
    const {
      proxy: self
    } = getCurrentInstance();
    const state = reactive({
      value: props.value,
      hoverValue: null
    });
    watch(() => props.value, val => {
      state.value = val;
    });

    function getStarValue(e, i) {
      if (props.allowHalf) {
        return e.offsetX > e.target.offsetWidth / 2 ? i + 1 : i + .5;
      } else {
        return i + 1;
      }
    }

    function onClick(e, i) {
      state.value = getStarValue(e, i);
    }

    function onHover(e, i) {
      state.hoverValue = getStarValue(e, i);
      emit('hoverChange', state.hoverValue);
    }

    function onMouseleave() {
      state.hoverValue = null;
    }

    return () => {
      const {
        prefixCls,
        disabled
      } = props;
      const ratePorps = {
        class: prefixCls,
        role: 'radiogroup',
        tabindex: 0,
        onMouseleave: disabled ? null : onMouseleave
      };
      const itemProps = {
        prefixCls: `${prefixCls}_star`,
        value: state.hoverValue || state.value,
        character: getComponent(self, 'character') || _createVNode(Icon, {
          "type": "ziyuan"
        }, null),
        allowHalf: props.allowHalf,
        disabled: props.disabled,
        count: props.count,
        color: props.color,
        onClick,
        onHover
      };
      const children = Array.from(Array(props.count), (_, i) => {
        return _createVNode(Star, _mergeProps(itemProps, {
          "index": i
        }), null);
      });
      return _createVNode("div", ratePorps, [children]);
    };
  }

});

Rate.install = app => {
  app.component(Rate.name, Rate);
};

export default Rate;