type CircleProgressType = {
  x?: number,
  y?: number,
  radius?: number,
  circleColor?: number,
  backColor?: number,
  lineWidth?: number,
  value?:number
}

export default class CircleProgressBar extends FYGE.Container {
  opt: CircleProgressType
  _value: number
  private circlePointer

  constructor(opt?: CircleProgressType) {
    super()
    this.opt = Object.assign({}, {
      x: 0,
      y: 0,
      radius: 10,
      lineWidth: 10,
      circleColor: 0xfe5000,
      backColor: 0xf0e4ce,
      value: 0
    }, opt)

    this._value = this.opt.value > 1 ? 1 : (this.opt.value < 0 ? 0 : this.opt.value)
    this.circlePointer = {
      x: this.opt.radius + this.opt.lineWidth,
      y: this.opt.radius + this.opt.lineWidth,
    }

    this.initUi()
  }

  backCircle: FYGE.Shape
  progressCircle: FYGE.Shape
  initUi() {
    var radius = this.opt.radius
    var lw = this.opt.lineWidth

    this.x = this.opt.x - radius - lw
    this.y = this.opt.y - radius - lw
    
    this.strokeBackCircle()

    this.strokeProgress(this.opt.value)
  }

  strokeBackCircle() {
    var radius = this.opt.radius
    var lw = this.opt.lineWidth

    if (!this.backCircle) {
      this.backCircle = this.addChild(new FYGE.Shape)
      this.backCircle.anchorX = radius + lw
      this.backCircle.anchorY = radius + lw
    } else {
      this.backCircle.clear()
    }
    this.backCircle.beginStroke(this.opt.backColor, this.opt.lineWidth)
    this.backCircle.arc(this.circlePointer.x, this.circlePointer.y, radius, 0, 2*Math.PI)
    this.backCircle.endStroke()
    this.backCircle.alpha = 0.5
  }

  strokeProgress(v) {
    if (!v) {
      this.progressCircle && this.progressCircle.clear()
      return
    }
    var radius = this.opt.radius
    var lw = this.opt.lineWidth
    // FYGE.LINE_CAP.ROUND
    if (!this.progressCircle) {
      this.progressCircle = this.addChild(new FYGE.Shape)
      this.progressCircle.anchorX = radius + lw
      this.progressCircle.anchorY = radius + lw
      this.progressCircle.rotation = -90 // 好看点
      this.progressCircle.beginStroke(this.opt.circleColor, this.opt.lineWidth)
      this.progressCircle.arc(radius + lw, radius + lw, radius, 0, 2*Math.PI * v, true)
      this.progressCircle.endStroke()
    } else {
      this.progressCircle.clear()
      this.progressCircle.beginStroke(this.opt.circleColor, this.opt.lineWidth)
        .arc(this.circlePointer.x, this.circlePointer.y, radius, 0, 2*Math.PI * v, true)
        .endStroke()
    }
  }

  get value() {
    return this._value;
  }

  set value(v) {
    if (v < 0) v = 0;
    if (v >= 1) v = 1;
    this._value = v;
    // this.progressTxt && (this.progressTxt.text = this.progressCfg.valueDesc + ((v * 100) >> 0) + "%");
    this.strokeProgress(v)
  }

  get radius() {
    return this.opt.radius
  }

  set radius(r: number) {
    this.opt.radius = r
    this.strokeBackCircle()
  }
}