<template lang="pug">
  button.button(@click.stop="$emit('click')")
    slot(name="left")
    span(:style="{color: textColor}")
      slot
    canvas.loading(v-show="hasLoading && loadingShow" ref='loading' width="14" height="14")
    slot(name="right")
</template>

<script>
export default {
  props: {
    textColor: {
      type: String
    },
    hasLoading: {
      type: Boolean,
      default: false
    },
    loadingShow: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {};
  },
  mounted() {
    if (this.hasLoading) this.buildLoading();
  },
  methods: {
    buildLoading() {
      if(!this.$refs.loading) return

      let ctx = this.$refs.loading.getContext("2d");
      let circle = {
        x: 7, //圆心的x轴坐标值
        y: 7, //圆心的y轴坐标值
        r: 6 //圆的半径
      }
      let times = 0
      this.animation(ctx, circle, times)
    },
    animation(ctx, circle, times) {
      window.requestAnimationFrame(() => {
        if(this.loadingShow) {
          ctx.clearRect(0, 0, 32, 32)
          times += 6.28 / 60
          ctx.beginPath(0, 0);
          ctx.arc(circle.x, circle.y, circle.r, times, Math.PI * 1.5 + times, false);
          ctx.stroke();
        }

        this.animation(ctx, circle, times)
      })
    }
  }
};
</script>

<style scoped lang="less">
.button {
  position: relative;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  border: 0;
  outline: none;
  border-radius: 4px;
  cursor: pointer;

  .text {
  }

  .loading {
    // position: absolute;
    // right: 0;
    // top: 0;
  }
}
</style>
