<template>
  <div
    class="xb-progress"
    :class="[
      'xb-progress--' + type,
      status ? 'is-' + status : '',
      showLoading ? 'is-show-loading' : '',
      {
        'xb-progress--without-text': !showText,
        'xb-progress--text-inside': textInside,
        'xb-progress--icon-inside': iconInside,
      }
    ]"
    role="progressbar"
    :aria-valuenow="percentage"
    aria-valuemin="0"
    aria-valuemax="100"
  >
    <div class="xb-progress-bar" v-if="type === 'line'">
      <div class="xb-progress-bar__outer" :style="{height: (textInside || iconInside) && !strokeWidth ? 18 : strokeWidth + 'px'}">
        <div class="xb-progress-bar__inner-loading" v-if="showLoading" :style="barStyle"></div>
        <div class="xb-progress-bar__inner" :style="barStyle">
          <div class="xb-progress-bar__innerText" v-if="showText && (textInside || iconInside)">
            <i v-if="iconInside" :class="iconInside"></i>
            <span v-else>{{showLoading && percentage!==100 ? '加载中' : content}}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="xb-progress-circle" :style="{height: width + 'px', width: width + 'px'}" v-else>
      <svg viewBox="0 0 100 100">
        <path
          class="xb-progress-circle__track"
          :d="trackPath"
          stroke="rgba(0,0,0,0.04)"
          :stroke-width="relativeStrokeWidth"
          fill="none"
          :style="trailPathStyle"></path>
        <path
          class="xb-progress-circle__path"
          :d="trackPath"
          :stroke="stroke"
          fill="none"
          :stroke-linecap="strokeLinecap"
          :stroke-width="percentage ? relativeStrokeWidth : 0"
          :style="circlePathStyle"></path>
      </svg>
    </div>
    <div
      class="xb-progress__text"
      v-if="showText && (!textInside && !iconInside)"
    >
      <template v-if="!status">{{showLoading && percentage!==100 ? '加载中' : content}}</template>
      <i v-else :class="iconClass"></i>
    </div>
  </div>
</template>
<script>
  export default {
    name: 'XbProgress',
    props: {
      type: {
        type: String,
        default: 'line',
        validator: val => ['line', 'circle', 'dashboard'].indexOf(val) > -1
      },
      percentage: {
        type: Number,
        default: 0,
        required: true,
        validator: val => val >= 0 && val <= 100
      },
      status: {
        type: String,
        validator: val => ['success', 'exception', 'warning'].indexOf(val) > -1
      },
      strokeWidth: Number,
      strokeLinecap: {
        type: String,
        default: 'round'
      },
      textInside: {
        type: Boolean,
        default: false
      },
      iconInside: {
        type: String,
        default: ''
      },
      width: {
        type: Number,
        default: 80
      },
      showText: {
        type: Boolean,
        default: true
      },
      showLoading: {
        type: Boolean,
        default: false
      },
      color: {
        type: [String, Array, Function],
        default: ''
      },
      format: Function
    },
    data() {
      return {
        widthStroke: 4
      };
    },
    computed: {
      barStyle() {
        const style = {};
        style.width = this.percentage + '%';
        style.backgroundColor = this.getCurrentColor(this.percentage);
        return style;
      },
      relativeStrokeWidth() {
        this.widthStroke = this.strokeWidth ? this.strokeWidth : this.widthStroke;
        return (this.widthStroke / this.width * 100).toFixed(1);
      },
      radius() {
        if (this.type === 'circle' || this.type === 'dashboard') {
          return parseInt(50 - parseFloat(this.relativeStrokeWidth) / 2, 10);
        } else {
          return 0;
        }
      },
      trackPath() {
        const radius = this.radius;
        const isDashboard = this.type === 'dashboard';
        return `
          M 50 50
          m 0 ${isDashboard ? '' : '-'}${radius}
          a ${radius} ${radius} 0 1 1 0 ${isDashboard ? '-' : ''}${radius * 2}
          a ${radius} ${radius} 0 1 1 0 ${isDashboard ? '' : '-'}${radius * 2}
          `;
      },
      perimeter() {
        return 2 * Math.PI * this.radius;
      },
      rate() {
        return this.type === 'dashboard' ? 0.75 : 1;
      },
      strokeDashoffset() {
        const offset = -1 * this.perimeter * (1 - this.rate) / 2;
        return `${offset}px`;
      },
      trailPathStyle() {
        return {
          strokeDasharray: `${(this.perimeter * this.rate)}px, ${this.perimeter}px`,
          strokeDashoffset: this.strokeDashoffset
        };
      },
      circlePathStyle() {
        return {
          strokeDasharray: `${this.perimeter * this.rate * (this.percentage / 100) }px, ${this.perimeter}px`,
          strokeDashoffset: this.strokeDashoffset,
          transition: 'stroke-dasharray 0.6s ease 0s, stroke 0.6s ease'
        };
      },
      stroke() {
        let ret;
        if (this.color) {
          ret = this.getCurrentColor(this.percentage);
        } else {
          switch (this.status) {
            case 'success':
              ret = '#67C23A';
              break;
            case 'exception':
              ret = '#EE2932';
              break;
            case 'warning':
              ret = '#ED9E4A';
              break;
            default:
              ret = '#FF3B12';
          }
        }
        return ret;
      },
      iconClass() {
        if (this.status === 'warning') {
          return this.type === 'line' ? 'xb_icon_remind_caution' : 'xb_icon_warn';
        }
        if (this.status === 'success') {
          return this.type === 'line' ? 'xb_icon_correct_facet' : 'xb_icon_correct_linear';
        }
        if (this.status === 'exception') {
          return this.type === 'line' ? 'xb_icon_close_facet' : 'xb_icon_exclamation';
        }
      },
      content() {
        if (typeof this.format === 'function') {
          return this.format(this.percentage) || '';
        } else {
          let textInner = `${this.percentage}%`;
          if (this.status === 'success') {
            textInner = '成功了';
          } else if (this.status === 'warning') {
            textInner = '出现异常，请刷新';
          } else if (this.status === 'exception') {
            textInner = '加载失败，请重试';
          }
          return textInner;
        }
      }
    },
    methods: {
      getCurrentColor(percentage) {
        if (typeof this.color === 'function') {
          return this.color(percentage);
        } else if (typeof this.color === 'string') {
          return this.color;
        } else {
          return this.getLevelColor(percentage);
        }
      },
      getLevelColor(percentage) {
        const colorArray = this.getColorArray().sort((a, b) => a.percentage - b.percentage);

        for (let i = 0; i < colorArray.length; i++) {
          if (colorArray[i].percentage > percentage) {
            return colorArray[i].color;
          }
        }
        return colorArray[colorArray.length - 1].color;
      },
      getColorArray() {
        const color = this.color;
        const span = 100 / color.length;
        return color.map((seriesColor, index) => {
          if (typeof seriesColor === 'string') {
            return {
              color: seriesColor,
              progress: (index + 1) * span
            };
          }
          return seriesColor;
        });
      }
    }
  };
</script>
