import { defineComponent } from 'vue'
import styles from './CircleProgress.module.less'

export default defineComponent({
  name: 'CircleProgress',
  data() {
    return {
      now: 0,
      timer: null as any
    }
  },
  props: {
    // 进度值
    value: {
      type: Number,
      default: 0
    },
    // 尺寸
    size: {
      type: Number,
      default: 120
    },
    // 边框粗细
    strokeWidth: {
      type: Number,
      default: 10
    },
    // 进度条颜色
    color: {
      type: String,
      default: 'rgba(153,202,251,1)'
    },
    // 动画执行时间
    duration: {
      type: Number,
      default: 1000
    },
    des:{
        type: String,
        default: '总达标率'
    }
  },
  watch:{
    value(value) {
      this.now = 0
      this.$nextTick(() => {
        this.run()
      })
    }
  },
  computed: {
    percentage() {
      return this.value
    },
    countDown() {
      return this.now
    },
    // 圆心x轴坐标
    cx() {
      return this.size / 2
    },
    // 圆心y轴坐标
    cy() {
      return this.size / 2
    },
    // 半径
    radius() {
      return (this.size - this.strokeWidth) / 2
    },
    // 圆周长
    circumference() {
      return 2 * Math.PI * this.radius
    },
    // 进度长度
    progress() {
      return (1 - this.now / 100) * this.circumference
    }
  },
  mounted() {
    this.run()
  },
  methods: {
    run() {
      if (this.value == 0) return
      let t = this.duration / this.value
      this.timer = setInterval(() => {
        if (this.now >= this.value) {
          this.now = this.value
          return clearInterval(this.timer)
        }
        this.now++
      }, t)
    }
  },
  render() {
    return (
      <div class={styles['circle-main']}>
        <div
          class={styles['circle-main-box']}
          style={[{ width: this.size + 'px', height: this.size + 'px' }]}
        >
          <svg width={this.size} height={this.size} class={styles['circle']}>
            <circle
              r={this.radius}
              cx={this.cx}
              cy={this.cy}
              fill="transparent"
              stroke="#FFE7DF"
              stroke-width={this.strokeWidth}
            />
            <circle
              r={this.radius}
              cx={this.cx}
              cy={this.cy}
              fill="transparent"
              stroke={this.color}
              stroke-width={this.strokeWidth}
              stroke-linecap="round"
              stroke-dasharray={this.circumference}
              stroke-dashoffset={this.progress}
            />
          </svg>
          <span class={styles['count-num']}>
            {this.countDown}<span class={styles.countType}>%</span>
          </span>
          <span class={styles.des}>{this.des}</span>
        </div>
      </div>
    )
  }
})
