<template>
	<div class="mod-config">
		<el-form :inline="true" @keyup.enter.native="getDataList()" class="blueTip" size="small">
			<el-form-item>
				{{ $t('pl.name') }}
			</el-form-item>
			<el-form-item>
				<el-select v-model="lineIds" :placeholder="$t('pl.name')" clearable filterable multiple>
					<el-option v-for="line in lineList" :key="line.code" :value="line.id" :label="line.name" />
				</el-select>
			</el-form-item>
			<el-form-item>
				{{ $t('time') }}
			</el-form-item>
			<el-form-item>
				<!-- type="datetimerange" -->
				<!-- <el-date-picker
					type="daterange"
					v-model="datetime"
					value-format="yyyy-MM-ddTHH:mm:ss"
					:start-placeholder="$t('startTime')"
					:end-placeholder="$t('endTime')"
					:range-separator="$t('to')"
					:default-time="['00:00:00', '23:59:59']"
					:picker-options="quickOptions"
					clearable /> -->
				<el-date-picker v-model="datetime" type="date" :placeholder="$t('hints.date')" format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
			</el-form-item>
			<el-form-item>
				<el-button class="buttonColor" @click="getDataList()">{{ $t('query') }}</el-button>
				<!-- <el-button v-if="$hasPermission('monitoring:qualityinspectionrecord:save')" type="primary" @click="addOrUpdateHandle()">{{ $t('add') }}</el-button> -->
			</el-form-item>
		</el-form>

		<div class="quality-inspection-current base-container">
			<!-- <el-row>
				<el-col>
					<small-title :size="'md'">{{ $t('inspect.ioTotal') }}</small-title>
					<el-row style="margin-top: 12px;">
						<base-table :data="dataListStatic" :table-head-configs="tableConfigStatic" :max-height="500" @operate-event="handleOperations" @refreshDataList="getDataList" />
					</el-row>
				</el-col>
			</el-row> -->

			<!-- style="margin-top: 28px;" -->
			<el-row>
				<el-col>
					<el-row>
						<small-title :size="'md'">{{ $t('eq.productQuality') }}</small-title>
					</el-row>
					<el-row style="margin-top: 8px">
						<el-radio-group v-model="dataType" size="medium" @change="handleDataTypeChange">
							<el-radio-button :label="$t('table2')"></el-radio-button>
							<el-radio-button :label="$t('graph')"></el-radio-button>
						</el-radio-group>
					</el-row>
					<el-row style="margin-top: 12px">
						<div style="text-align: right">
							<!-- 设置设备名称小齿轮table列的图标 -->
							<el-popover width="200" trigger="click" v-if="showGraph">
								<div class="box">
									<!-- :label="item.name ? item.name : item.label" 三元判别就可以让厂务的实时数据可以显示 -->
									<el-checkbox
										v-for="(item, index) in echartCategories"
										:key="'cb' + index"
										v-model="selectedBox[index]"
										:label="item"
										@change="checkboxChange(echartCategories)" />
								</div>
								<i slot="reference" class="el-icon-s-tools" style="color: #0b58ff">{{ $t('pl.choose') }}</i>
							</el-popover>
						</div>
						<base-table
							v-if="!showGraph"
							:data="dataListDynamic"
							:table-head-configs="tableConfigDynamic"
							:max-height="500"
							@operate-event="handleOperations"
							@refreshDataList="getDataList" />
						<!-- :series-data="echartsData"  -->
						<fake-chart v-else :categories="echartRealtime" :type-list="echartCheckTypes" :series-data1="echartsData1" :series-data2="echartsData2" :pass-rate="pass" />
					</el-row>
				</el-col>
			</el-row>
		</div>
	</div>
</template>

<script>
import { calcMaxHeight } from '@/utils'
import { timeFilter } from '@/utils/filters'
import moment from 'moment'
import i18n from '@/i18n'
import BaseTable from '@/components/base-table'
import SmallTitle from '@/components/small-title'
import * as echarts from 'echarts'

// const tableConfigStatic = [
// 	{ type: 'index', width: 100, name: i18n.t('index') },
// 	{ name: i18n.t('pl.title'), prop: 'lineName' },
// 	{ name: i18n.t('inspect.inTotal'), prop: 'sumUp' },
// 	{ name: i18n.t('inspect.outTotal'), prop: 'sumDown' },
// 	{ name: i18n.t('inspect.checkTotal'), prop: 'sumCheck' },
// 	{ name: i18n.t('inspect.rate'), prop: 'scrapRatio', filter: (val) => (val || val === 0 ? `${val}%` : '-') }
// ]
const tableConfigDynamic = [
	{ type: 'index', width: 100, name: i18n.t('index') },
	{ name: i18n.t('eq.sectionName'), prop: 'sectionName' },
	// ...subProps,
	{ name: i18n.t('eq.equipmentName'), prop: 'equipmentName' },
	{ name: i18n.t('eq.okNum'), prop: 'okNum' },
	{ name: i18n.t('eq.nokNum'), prop: 'nokNum' },
	{ name: i18n.t('eq.passRate'), prop: 'passRate', filter: (val) => (val || val === 0 ? `${val}%` : '-') }
]

const FakeChart = {
	name: 'FakeChart',
	props: {
		categories: {
			type: Array,
			default: () => []
		},
		typeList: {
			type: Array,
			default: () => []
		},
		seriesData1: {
			type: Array,
			default: () => []
		},
		seriesData2: {
			type: Array,
			default: () => []
		},
		passRate: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			// selectedBox: new Array(100).fill(true),
			calcMaxHeight,
			chart: null,
			// 新加
			echartsData1: [],
			echartsData2: [],
			pass: [],
			defaultOpts: {
				grid: {
					left: '5%',
					right: '12%',
					top: '20%',
					bottom: '10%'
				},
				title: {
					text: i18n.t('eq.productQuality')
				},
				tooltip: {
					trigger: 'axis', //坐标轴触发，主要在柱状图，折线图等会使用类目轴的图表中使用
					axisPointer: {
						// 坐标轴指示器，坐标轴触发有效
						type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
					}
				},
				toolbox: {
					feature: {
						dataView: {
							show: true,
							readOnly: true,
							optionToContent: function (opt) {
								var axisData = opt.xAxis[0].data
								var series = opt.series
								//验证是否是中文
								var pattern = new RegExp('[\u4E00-\u9FA5]+')
								if (pattern.test(series[0].name)) {
									var table =
										'<table class="layui-table" style="width:100%;text-align:center"><tbody><tr>' +
										'<td>设备名称</td>' +
										'<td>' +
										series[0].name +
										'</td>' +
										'<td>' +
										series[1].name +
										'</td>' +
										'<td>' +
										series[2].name +
										'</td>' +
										'</tr>'
								} else {
									var table =
										'<table class="layui-table" style="width:100%;text-align:center"><tbody><tr>' +
										'<td>Equipment Name</td>' +
										'<td>' +
										series[0].name +
										'</td>' +
										'<td>' +
										series[1].name +
										'</td>' +
										'<td>' +
										series[2].name +
										'</td>' +
										'</tr>'
								}
								for (var i = 0, l = axisData.length; i < l; i++) {
									table +=
										'<tr>' +
										'<td>' +
										axisData[i] +
										'</td>' +
										'<td>' +
										series[0].data[i] +
										'</td>' +
										'<td>' +
										series[1].data[i] +
										'</td>' +
										'<td>' +
										series[2].data[i] +
										'</td>' +
										'</tr>'
								}
								table += '</tbody></table>'
								return table
							}
						},
						restore: { show: true },
						saveAsImage: { show: true }
					}
				},
				legend: {
					// orient: 'vertical',
					// type: 'scroll',
					// top: 10,
					// right: 0,
					// width: '12%',
					/** 修复文本太长时显示问题 */
					// formatter: function (name) {
					// 	return echarts.format.truncateText(name, 120, '14px Microsoft Yahei', '...')
					// },
					tooltip: {
						show: true
					},
					/** end */
					data: [i18n.t('eq.okNum'), i18n.t('eq.nokNum'), i18n.t('eq.passRatePercent')]
				},
				xAxis: {
					type: 'category',
					axisTick: {
						alignWithLabel: true
					},
					data: [],
					// axisLine: {
					// 	show: true,
					// 	lineStyle: {
					// 		color: 'rgba(219,225,255,1)',
					// 		width: 1,
					// 		type: 'solid'
					// 	}
					// },
					axisLabel: {
						//设置x轴的字
						show: true,
						interval: 0 //使x轴横坐标全部显示
						// textStyle: {
						// 	//x轴字体样式
						// 	color: 'rgba(219,225,255,1)',
						// 	margin: 15
						// }
					}

					// data: ['下片1', '上片1', '磨边机1', '设备13', '钢化炉2', '磨边机2', '设备15', '清洗机1', '钢化炉3']
				},
				yAxis: [
					{
						type: 'value',
						name: i18n.t('eq.okNum'),
						position: 'left',
						alignTicks: true,
						axisLine: {
							show: true,
							lineStyle: {
								color: '#5470C6'
							}
						},
						axisLabel: {
							// formatter: '{value} pcs'
						}
					},
					{
						type: 'value',
						name: i18n.t('eq.nokNum'),
						position: 'right',
						alignTicks: true,
						axisLine: {
							show: true,
							lineStyle: {
								color: '#91CC75'
							}
						},
						axisLabel: {
							// formatter: '{value} pcs'
						}
					},
					{
						type: 'value',
						name: i18n.t('eq.passRatePercent'),
						position: 'right',
						offset: 80,
						alignTicks: true,
						axisLine: {
							show: true,
							lineStyle: {
								color: '#FAC857'
							}
						},
						axisLabel: {
							formatter: '{value} %'
						}
					}
				],
				series: [
					// dynamic
					{
						name: i18n.t('eq.okNum'),
						type: 'bar',
						data: [],
						label: {
							normal: {
								show: true,
								position: 'top'
							},
							formatter: '{@value}'
						}
						// data: ['314', '1813', '136', '2202', '9895', '0', '411', '0', '2050']
					},
					{
						name: i18n.t('eq.nokNum'),
						type: 'bar',
						yAxisIndex: 1,
						data: [],
						label: {
							normal: {
								show: true,
								position: 'top'
							},
							formatter: '{@value}'
						}
						// data: ['62', '39', '21', '23', '40', '0', '3', '0', '4']
					},
					{
						name: i18n.t('eq.passRatePercent'),
						type: 'line',
						yAxisIndex: 2,
						data: [],
						label: {
							normal: {
								show: true,
								position: 'top'
							},
							formatter: '{@value}'
						}
						// data: ['62', '39', '21', '23', '40', '0', '3', '0', '4']
					}
					// {
					// 	data: [120, 200, 150, 80, 70, 110, 130],
					// 	type: 'bar'
					// }
				]
			}
		}
	},
	watch: {
		categories: {
			handler: function (val, oldVal) {
				if (val && val !== oldVal) {
					// this.defaultOpts.xAxis.data.push(...val)
					this.defaultOpts.xAxis.data = val
				}
			},
			immediate: true
		},
		typeList: {
			handler: function (val, oldVal) {
				if (val && val !== oldVal) {
					this.defaultOpts.legend.data.push(...val)
				}
			},
			immediate: true
		},
		seriesData1: {
			// this.defaultOpts.series[0].data.push 注意
			handler: function (val, oldVal) {
				if (val && val !== oldVal) {
					// this.defaultOpts.series[0].data.push(...val)
					this.defaultOpts.series[0].data = val
				}
			},
			immediate: true
		},
		seriesData2: {
			handler: function (val, oldVal) {
				if (val && val !== oldVal) {
					this.defaultOpts.series[1].data = val
				}
			},
			immediate: true
		},
		passRate: {
			handler: function (val, oldVal) {
				if (val && val !== oldVal) {
					this.defaultOpts.series[2].data = val
				}
			},
			immediate: true
		},
		defaultOpts: {
			handler: function (val) {
				// console.log('defaullt opts change: ', val)
				this.setOptions()
			},
			immediate: true,
			deep: true
		}
	},
	mounted() {
		this.$nextTick(() => {
			// console.log('echarts data1: ', this.echartsData1)
			// console.log('echarts data2: ', this.echartsData2)
			// console.log('passRate', this.pass)
			this.initChart()
			// console.log('this.defaultOpts.xAxis.data', this.defaultOpts.xAxis.data)
			this.setOptions()
			window.addEventListener('resize', () => {
				//监听浏览器窗口大小
				this.chart.resize()
			})
		})
	},
	methods: {
		initChart() {
			if (!this.chart) {
				this.chart = echarts.init(document.getElementById('bar-chart'))
			}
		},
		setOptions(opts) {
			/** prop options */
			if (opts) {
			}

			if (this.chart) this.chart.setOption(this.defaultOpts)
		}
	},
	render: function (h) {
		return h('div', { attrs: { id: 'bar-chart' }, style: { background: '#eee', width: '100%', height: '300px', padding: '8px' } }, '')
	}
}

const dict = [i18n.t('table2'), i18n.t('graph')]
export default {
	name: 'QualityInspectionCurrent',
	components: { BaseTable, SmallTitle, FakeChart },
	data() {
		return {
			selectedBox: new Array(100).fill(true),
			lineIds: [],
			lineList: [],
			// tableConfigStatic,
			tableConfigDynamic,
			dataListStatic: [],
			dataListDynamic: [],
			dict,
			dataType: dict[0], // 表格 | 图形
			showGraph: false,
			// datetime: [],
			datetime: new Date(),
			// quickOptions: {
			// 	shortcuts: [
			// 		{
			// 			text: i18n.t('today'),
			// 			onClick(picker) {
			// 				const baseTime = moment().set({ hour: 0, minute: 0, second: 0, millisecond: 0 })
			// 				const startTime = baseTime.format('yyyy-MM-DDTHH:mm:ss')
			// 				const endTime = baseTime.set({ hour: 23, minute: 59, second: 59, millisecond: 999 }).format('yyyy-MM-DDTHH:mm:ss')
			// 				picker.$emit('pick', [startTime, endTime])
			// 			}
			// 		}
			// 	]
			// },
			echartCategories: null,
			echartRealtime: [],
			echartCheckTypes: [],
			interval: null
		}
	},
	created() {
		this.getLineList()
		this.getDataList()

		this.interval = setInterval(() => {
			this.$message.info(i18n.t('refresh'))
			// this.dataListStatic.splice(0)
			this.dataListDynamic.splice(0)
			this.getDataList()
		}, 1000 * 5 * 60)
	},
	beforeMount() {
		this.selectedBox = new Array(100).fill(true)
	},
	deactivated() {
		if (this.interval) {
			clearInterval(this.interval)
			this.interval = null
		}
	},
	methods: {
		// 产线
		getLineList() {
			this.$http({
				url: this.$http.adornUrl('/monitoring/productionLine/list'),
				method: 'get'
			}).then(({ data }) => {
				if (data && data.code === 0) {
					this.lineList = data.data
					// console.log('产线数组',this.lineList);
				} else {
					this.lineList = []
				}
			})
		},
		handleOperations() {},
		handleDataTypeChange(value) {
			this.showGraph = value === dict[0] ? false : true
		},
		getDataList() {
			// this.echartsData1 = []
			// this.echartsData2 = []
			// this.pass = []
			this.showGraph = false
			this.dataType = i18n.t('table2')
			this.echartCategories = null
			this.echartCheckTypes.splice(0)
			this.echartRealtime = []
			// 更新下checkbox全选
			this.selectedBox = new Array(100).fill(true)
			/** 设置默认日期 */
			// const startTime = this.datetime[0] || moment().set({ hour: 0, minute: 0, second: 0 }).format('yyyy-MM-DDTHH:mm:ss')
			// const endTime = this.datetime[1] || moment().set({ hour: 23, minute: 59, second: 59 }).format('yyyy-MM-DDTHH:mm:ss')
			// console.log('this.datatime',this.datatime)
			// const startTime = this.datetime ? this.datetime + 'T00:00:00' : null
			const startTime = this.datetime ? moment(this.datetime).format('YYYY-MM-DD') + 'T00:00:00' : null
			// const endTime = this.datetime ? this.datetime + 'T23:59:59' : null
			const endTime = this.datetime ? moment(this.datetime).format('YYYY-MM-DD') + 'T23:59:59' : null
			const lineIds = this.lineIds

			/** 获取产品质量分析数据 */
			// this.fetchList(startTime, endTime, lineIds).then(({ data: res }) => {
			this.$http({
				url: this.$http.adornUrl('/monitoring/eqAnalysis/productQualityAnalysis'),
				method: 'POST',
				data: {
					startTime,
					endTime,
					lineIds: this.lineIds.length == 0 ? null : this.lineIds
				}
			})
				.then((res) => {
					// console.log('res: ', res)
					/** TODO: 解析 nameData */
					// 新加
					this.tableConfigDynamic = [
						{ type: 'index', width: 100, name: i18n.t('index') },
						{ name: i18n.t('eq.sectionName'), prop: 'sectionName' },
						// ...subProps,
						{ name: i18n.t('eq.equipmentName'), prop: 'equipmentName' },
						{ name: i18n.t('eq.okNum'), prop: 'okNum' },
						{ name: i18n.t('eq.nokNum'), prop: 'nokNum' },
						{ name: i18n.t('eq.passRate'), prop: 'passRate', filter: (val) => (val || val === 0 ? `${val}%` : '-') }
					]

					// this.dataListDynamic = this.parseDynamicData(res.data.data) || []
					this.dataListDynamic = res.data.data || []

					/** echarts related */
					// this.echartCategories = subProps.map((item) => item.name)
					this.echartCategories = this.dataListDynamic.map((item) => {
						return item.equipmentName
					})
					this.echartRealtime = this.echartCategories
					// this.parseTableProps(res.data.nameData)

					console.log('this.dataListDynamic', this.dataListDynamic)

					this.buildGraphData()
				})
				.catch((err) => {
					console.error(err)
				})
		},

		// parseTableProps(nameData) {
		// 	const subProps = []
		// 	const labelNameMap = new Map()

		// 	// if (nameData.length) {
		// 	// 	/** 处理 nameData */
		// 	// 	nameData.forEach((item) => {
		// 	// 		if (!labelNameMap.get(item.name)) {
		// 	// 			labelNameMap.set(item.name, 1)
		// 	// 			subProps.push({ name: item.name, prop: item.name })
		// 	// 		}
		// 	// 	})
		// 	// }

		// 	this.tableConfigDynamic = [
		// 		{ type: 'index', width: 100, name: i18n.t('index') },
		// 		{ name: i18n.t('eq.sectionName'), prop: 'sectionName' },
		// 		// ...subProps,
		// 		{ name: i18n.t('eq.equipmentName'), prop: 'equipmentName' },
		// 		{ name: i18n.t('eq.okNum'), prop: 'okNum' },
		// 		{ name: i18n.t('eq.nokNum'), prop: 'nokNum' },
		// 		{ name: i18n.t('eq.passRate'), prop: 'passRate', filter: (val) => (val || val === 0 ? `${val}%` : '-') }
		// 	]

		// 	/** echarts related */
		// 	// this.echartCategories = subProps.map((item) => item.name)
		// 	this.echartCategories = this.dataListDynamic.map((item) => item.name)
		// },

		// parseDynamicData(data) {
		// 	this.echartCheckTypes.splice(0)
		// 	return data.map((item) => {
		// 		/** echarts related */
		// 		this.echartCheckTypes.push(item.inspectionContent)
		// 		if (item.data.length) {
		// 			/** 解析子数组 */
		// 			item.data.forEach((subitem) => {
		// 				item[subitem.dynamicName] = subitem.dynamicValue
		// 			})
		// 		}
		// 		return item
		// 	})
		// },

		buildGraphData() {
			/** 构造 echart 需要的数据 */
			const result = []

			// this.echartCheckTypes.forEach((ect) => {
			// 	result.push({ name: ect, type: 'bar', data: [] })
			// })
			// console.log('echartCheckTypes', this.echartCheckTypes)
			// console.log('this.echartCategories', this.echartCategories)
			// this.dataListDynamic.forEach((inspection, index) => {
			// 	// console.log('inspection: ', inspection)
			// 	this.echartCategories.forEach((cate) => {
			// 		if (cate in inspection) {
			// 			result[index].data.push(inspection[cate])
			// 		} else {
			// 			result[index].data.push('0')
			// 		}
			// 	})
			// })

			// 新建一个echartRealtime来保存修改checkbox后实时的横坐标数据
			// this.echartRealtime = this.echartCategories
			this.echartsData1 = []
			this.echartsData2 = []
			this.pass = []
			// 尝试写个改变checkbox时触发改变this.echartCategories
			// console.log('this.echartRealtime1', this.echartRealtime)
			// 初始化
			this.echartRealtime = []
			// 根据selectedBox的真假，动态生成横坐标和数值，运用了数组与元素合并
			for (let i = 0; i < this.echartCategories.length; i++) {
				if (this.selectedBox[i] == true) {
					// console.log('this.echartCategories.slice(i)',this.echartCategories.slice(i))
					// console.log(
					// 	'this.dataListDynamic.map((item) => item.okNum)',
					// 	this.dataListDynamic.map((item) => item.okNum)
					// )
					this.echartRealtime = [...this.echartRealtime, ...this.echartCategories.slice(i, i + 1)]
					this.echartsData1 = [...this.echartsData1, this.dataListDynamic.map((item) => item.okNum)[i]]
					this.echartsData2 = [...this.echartsData2, this.dataListDynamic.map((item) => item.nokNum)[i]]
					this.pass = [...this.pass, this.dataListDynamic.map((item) => item.passRate)[i]]
				}
			}
			// console.log('this.echartRealtime2', this.echartRealtime)
			// console.log('this.echartsData1', this.echartsData1)
			// this.echartsData = result
			// console.log('result', result)
			// [
			// 	{ name: '11', type: 'bar', data: [/**产线1*/ 2, /**产线2*/ 3] },
			// 	{ name: '222', type: 'bar', data: [1, 2, 3] }
			// ]
		},

		fetchList(startTime, endTime, lineIds) {
			this.$http({
				url: this.$http.adornUrl('/monitoring/eqAnalysis/productQualityAnalysis'),
				method: 'POST',
				data: {
					startTime,
					endTime,
					lineIds: this.lineIds
				}
			}).catch((err) => {
				console.error(err)
			})
		},
		checkboxChange(val) {
			// console.log('val', val)
			// console.log('this.selectedBox', this.selectedBox)
			this.buildGraphData()
			// console.log('this.echartCategories', this.echartCategories)
			// console.log('val',val)
		}
	}
}
</script>

<style scoped>
.base-container {
	min-height: 60vh;
	background: #fff;
	padding: 12px;
}
.buttonColor {
	color: #fff;
	background: #0b58ff;
}
</style>
