<template>
  <span
    class="ui-star"
    :class="{'is-checked': checked, 'is-viewable': !editable, 'is-loading': loading}"
    @click.stop.prevent="handleClick"
  >
    <span v-if="!loading" class="ui-start__control"></span>
    <ui-loading class="ui-star__loading" size="mini" :visible="loading"></ui-loading>
  </span>
</template>
<script>
import UiLoading from '@huntianning/components/packages/loading'

export default {
  name: 'UiStar',
  components: {
    UiLoading
  },
  model: {
    prop: 'checked'
  },
  props: {
    checked: {
      type: Boolean
    },
    editable: {
      type: Boolean,
      default: true
    },
    click: {
      type: Function
    }
  },
  data() {
    return {
      loading: false
    }
  },
  methods: {
    handleClick() {
      if (this.loading) {
        return
      }
      if (this.click) {
        const rs = this.click()
        if (rs && rs.then) {
          this.loading = true
          rs.then(() => {
            this.$emit('input', !this.checked)
          }).finally(() => {
            this.loading = false
          })
        } else {
          this.$emit('input', !this.checked)
        }
      } else {
        this.$emit('input', !this.checked)
      }
    }
  }
}
</script>
<style lang="less">
.ui-star {
  display: inline-block;
  width: 18px;
  height: 18px;
  position: relative;
  vertical-align: top;
  &:not(.is-checked) {
    .ui-start__control{
      background-image: url('./icons/star-fill.svg');
      opacity: .2;
    }
  }
  &.is-checked {
    .ui-start__control{
      background-image: url('./icons/star-fill-active.svg');
    }
  }
  &:not(.is-viewable) {
    cursor: pointer;
  }
}
.ui-start__control{
  display: inline-block;
  width: 18px;
  height: 18px;
  background-repeat: no-repeat;
  background-position: 50% 50%;
  background-size: 18px;
  transition: all .25s;
  vertical-align: top;
}
.ui-star__loading{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
