<template>
  <div v-show="show" class="progressShade" :style="{background: background}">
    <el-progress
      class="progressBar"
      :type="type"
      :show-text="showText"
      :text-inside="textInside"
      :stroke-width="strokeWidth"
      :percentage="percentage"
      :color="color"
      :status="status"
    />
  </div>
</template>

<script>
import { requestAnimationFrame, cancelRequestAnimFrame } from '@/utils/animation';

export default {
	name: 'ProgressBar',
	props: {
		type: {
			type: String,
			default() {
				return 'line';
			}
		},
		showText: {
			type: Boolean,
			default() {
				return true;
			}
		},
		textInside: {
			type: Boolean,
			default() {
				return false;
			}
		},
		strokeWidth: {
			type: Number,
			default() {
				return 5;
			}
		},
		background: {
			type: String,
			default() {
				return 'rgba(0, 0, 0, 0.8)';
			}
		}
	},
	data() {
		return {
			color: '#8e71c7',
			status: null,
			show: true,
			percentage: 0,
			fps: 30,
			then: null
		};
	},
	mounted() {
		this.percentage = this.randomNum();
	},
	methods: {
		randomNum() {
			return Math.ceil(Math.random() * 5) + 50;
		},
		run() {
			const now = +Date.now();
			const delta = now - this.then || +Date.now();
			const interval = 1000 / this.fps;

			if (delta > interval) {
				this.then = now - (delta % interval);
				if (this.percentage < 90) {
					this.percentage = this.percentage + 5;
				} else {
					cancelRequestAnimFrame(this.run);
				}
			}

			requestAnimationFrame(this.run);
		},
		start() {
			if (!this.show) {
				this.status = null;
				this.percentage = this.randomNum();
				this.show = true;
				this.run();
			}
		},
		end(isSuccess) {
			cancelRequestAnimFrame(this.run);
			if (this.show) {
				if (isSuccess) {
					this.success();
				} else {
					this.failed();
				}
			}
		},
		progressAt(num) {
			if (num > 0 && num < 100 && num > this.percentage) {
				this.percentage = num;
			}
		},
		success() {
			this.status = 'success';
			this.percentage = 100;
			setTimeout(() => {
				this.show = false;
			}, 1000 / this.fps);
		},
		failed() {
			this.status = 'exception';
			setTimeout(() => {
				this.show = false;
			}, 1000 / this.fps);
		}
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    @import "src/styles/mixin.scss";

    .progressShade {
        display: inline;
        z-index: 9998;
        position: absolute;
        top: 0px;
        left: 0px;
        width: 100%;
        height: 100%;
    }

    .progressBar {
        z-index: 9999;
        display: inline;
        position: absolute;
        top: 40%;
        width: 50%;
        left: 25%;
    }
</style>
