<!--
/*
* @Author: lb
* @Date: 2022-07-24 13:30:00
* @LastEditTime: 2022-07-28 09:30:00
* @LastEditors: lb
* @Description: 设备效率分析-echarts图
*/
-->
<template>
	<div class="graph-area">
		<span class="close-btn" @click="close">
			<svg xmlns="http://www.w3.org/2000/svg" style="height: 100%; width: 100%;" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
				<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
			</svg>
		</span>

		<div class="close-row">
			<el-radio-group v-model="dataType" class="head-radio-group" size="small" @change="setLegend">
				<el-radio-button :label="$t('eq.ratio')" />
				<el-radio-button :label="$t('eq.time')" />
			</el-radio-group>

			<el-radio-group v-if="1" v-model="searchType" class="head-radio-group" style="margin-left: 8px;" size="small" @change="handleRadioGroupChanged">
				<el-radio-button v-for="(opt, index) in searchRadioOptions" :key="index" :label="opt" />
			</el-radio-group>
		</div>

		<div id="trend-graph" class="real-graph" style="width: 100%; height: 500px;" />
	</div>
</template>

<script>
import * as echarts from 'echarts'
import moment from 'moment'
import { pick } from 'lodash/object'
import i18n from '../../../i18n'

class EchartConfigs {
	constructor() {
		this.color = ['#e91e63', '#4caf50', '#3f51b5', '#ffc107', '#607d8b']
		this.title = {
			text: i18n.t('eq.timetrend'),
			top: 0,
			left: 'center',
			textStyle: {
				fontWeight: 'bold',
				fontSize: 18,
				lineHeight: 18
			}
		}
		this.tooltip = {
			trigger: 'axis',
			// 将axisPointer设置得更显眼一点
			axisPointer: {
				type: 'shadow'
			}
		}
		// legend
		this.legend = {
			icon: 'circle',
			top: 24,
			left: 'center',
			padding: 8,
			itemGap: 8,
			data: [] // 动态设置
		}
		this.xAxis = {
			type: 'category',
			data: [] // 动态设置
			// https://tushuo.baidu.com/wave/index#/manufacture/dta9pydmexfdhc0sg/999
		}
		this.yAxis = {
			type: 'value'
		}
		this.series = [] // 动态设置
	}

	setTitle(val) {
		this.title.text = val
	}

	setLegend(val) {
		this.legend.data.splice(0)
		if (Array.isArray(val)) {
			this.legend.data = val
		} else {
			console.error('setLegend() 只接受数组参数')
		}
	}

	setXAxis(val) {
		// console.log('in setXAxis(): ', val)
		this.xAxis.data.splice(0)
		if (Array.isArray(val)) {
			this.xAxis.data = val
		} else {
			console.error('setXAxis() 只接受数组参数')
		}
	}

	setSeries(val) {
		this.series.splice(0)
		if (Array.isArray(val) && this.series.length === 0) {
			this.series = val
		} else {
			console.error('setSeries() 只接受数组参数')
		}
	}
}

export default {
	name: 'EquipmentEfficiencyGraph',
	props: {},
	data() {
		return {
			searchType: i18n.t('eq.nogap'),
			searchRadioOptions: [i18n.t('eq.nogap'), i18n.t('eq.monthgap'), i18n.t('eq.weekgap'), i18n.t('eq.daygap')],
			dataType: i18n.t('eq.time'),
			dataRadioOptions: [i18n.t('eq.time'), i18n.t('eq.ratio')],
			config: new EchartConfigs(),
			chart: null,
			rateList: [], // 对请求来的数据分流
			timeList: [],
			xAxis: [], // 动态设置
			injectData: null
		}
	},
	methods: {
		async initChart() {
			this.config.setTitle(this.injectData.equipmentName + i18n.t('eq.timetrend'))
			await this.getList()
			this.setLegend()
		},

		init(data) {
			this.injectData = data
			if (!this.chart) {
				this.chart = echarts.init(document.getElementById('trend-graph'))
				// this.chart.setOption(this.config)
				this.initChart()
			}
		},
		close() {
			this.$emit('close-graph')
		},

		makeQuerys() {
			const searchTypeMap = {
				[i18n.t('eq.nogap')]: 1,
				[i18n.t('eq.monthgap')]: 2,
				[i18n.t('eq.weekgap')]: 3,
				[i18n.t('eq.daygap')]: 4,
				[i18n.t('eq.hourgap')]: 5
			}

			return {
				type: searchTypeMap[this.searchType],
				eqId: this.injectData.equipmentId,
				startTime: this.injectData.startTime, // '2022-06-14T00:00:00'
				endTime: this.injectData.endTime
			}
		},

		// getOEE
		getOEE(params) {
			return this.$http({
				url: this.$http.adornUrl('/monitoring/eqAnalysis/oee'),
				method: 'post',
				data: params
			}).then(({ data: res }) => {
				if (!res.data || res.code === 500) {
					this.dataList.splice(0)
					this.$message.error(res.msg)
					return { data: null }
				}
				return res.data
			})
		},

		getList() {
			const params = this.makeQuerys()
			// 发起请求
			return this.getOEE(params).then(datalist => {
				console.log('getOEE res:', datalist)
				this.timeList.splice(0)
				this.rateList.splice(0)
				this.xAxis.splice(0)
				if (datalist.length) {
					// 分流
					datalist.map(item => {
						const time = moment(item.time)
						if (this.searchType === i18n.t('eq.monthgap')) {
							this.xAxis.push(`${time.year()}${i18n.t('eq.year')}${time.month() + 1}${i18n.t('eq.month')}`)
						} else if (this.searchType === i18n.t('eq.weekgap')) {
							this.xAxis.push(`${time.format('YYYY-MM-DD')}`)
						} else if (this.searchType === i18n.t('eq.daygap')) {
							this.xAxis.push(`${time.format('YY-M-D')}`)
						} else {
							this.xAxis.push(`${time.format('YYYY-MM-DD')}`)
						}
						this.timeList.push(pick(item, ['workTime', 'stopTime', 'downTime']))
						this.rateList.push(pick(item, ['workRate', 'stopRate', 'downRate', 'peEfficiency', 'timeEfficiency', 'oee', 'teep']))
					})

					// 设置横轴
					this.config.setXAxis(JSON.parse(JSON.stringify(this.xAxis)))
				}
			})
		},

		async handleRadioGroupChanged() {
			// 获取数据且设置横轴
			await this.getList()
			// 设置legend和数据
			this.setLegend()
		},

		setLegend() {
			// 设置legend
			const legendMap = {
				[i18n.t('eq.ratio')]: [
					i18n.t('eq.workdurationratio'),
					i18n.t('eq.stopdurationratio'),
					i18n.t('eq.downdurationratio'),
					i18n.t('eq.speedefficiency'),
					i18n.t('eq.timeefficiency'),
					'OEE',
					'TEEP'
				],
				[i18n.t('eq.time')]: [i18n.t('eq.worktime'), i18n.t('eq.stoptime'), i18n.t('eq.downtime')]
			}
			this.config.setLegend(legendMap[this.dataType])
			this.setData()
			// 重新绘制
			this.renderGraph()
		},

		setData() {
			if (this.dataType === i18n.t('eq.time')) {
				const workTimeList = []
				const stopTimeList = []
				const downTimeList = []
				this.timeList.map(item => {
					workTimeList.push(item.workTime)
					stopTimeList.push(item.stopTime)
					downTimeList.push(item.downTime)
				})
				this.config.setSeries([
					{ name: i18n.t('eq.worktime'), type: 'bar', data: workTimeList },
					{ name: i18n.t('eq.stoptime'), type: 'bar', data: stopTimeList },
					{ name: i18n.t('eq.downtime'), type: 'bar', data: downTimeList }
				])
			} else {
				// 百分比
				const workRateList = []
				const stopRateList = []
				const downRateList = []
				const peEfficiencyList = []
				const timeEfficiencyList = []
				const oeeList = []
				const teepList = []
				this.rateList.map(item => {
					workRateList.push(item.workRate)
					stopRateList.push(item.stopRate)
					downRateList.push(item.downRate)
					peEfficiencyList.push(item.peEfficiency)
					timeEfficiencyList.push(item.timeEfficiency)
					oeeList.push(item.oee)
					teepList.push(item.teep)
				})
				this.config.setSeries([
					{ name: i18n.t('eq.workdurationratio'), type: 'bar', data: workRateList },
					{ name: i18n.t('eq.stopdurationratio'), type: 'bar', data: stopRateList },
					{ name: i18n.t('eq.downdurationratio'), type: 'bar', data: downRateList },
					{ name: i18n.t('eq.speedefficiency'), type: 'bar', data: peEfficiencyList },
					{ name: i18n.t('eq.timeefficiency'), type: 'bar', data: timeEfficiencyList },
					{ name: 'OEE', type: 'bar', data: oeeList },
					{ name: 'TEEP', type: 'bar', data: teepList }
				])
			}
		},

		// 重新绘制图形
		renderGraph() {
			console.log('latest config: ', JSON.stringify(this.config))
			this.$nextTick(() => {
				// this.chart.setOption(this.config)
				this.chart.setOption(this.config, {
					notMerge: true
				})
			})
		}
	}
}
</script>

<style scoped>
.graph-area {
	width: 100%;
	min-height: 200px;
	position: relative;
}

.close-row {
	position: relative;
	padding: 8px 0;
}

.close-btn {
	position: absolute;
	z-index: 1;
	top: 10px;
	right: 10px;
	display: inline-block;
	width: 20px;
	height: 20px;
	cursor: pointer;
	transition: color 0.3s linear;
}

.close-btn:hover {
	color: #409eff;
}

.head-radio-group >>> .el-radio-button__orig-radio:checked + .el-radio-button__inner {
	background-color: #409eff;
	border-color: #409eff;
}
</style>
