<template>
	<div class="mod-config">
		<el-form :inline="true" @keyup.enter.native="getDataList()">
			<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-form-item>
			<el-form-item>
				<el-button @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>

			<el-row style="margin-top: 28px;">
				<el-col>
					<el-row>
						<small-title :size="'md'">{{ $t('inspect.plTotal') }}</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;">
						<base-table
							v-if="!showGraph"
							:data="dataListDynamic"
							:table-head-configs="tableConfigDynamic"
							:max-height="500"
							@operate-event="handleOperations"
							@refreshDataList="getDataList"
						/>
						<fake-chart v-else :categories="echartCategories" :type-list="echartCheckTypes" :series-data="echartsData" />
					</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('inspect.type'), prop: 'inspectionContent' },
	/** dynamic */
	{ name: i18n.t('inspect.typetotal'), prop: '' },
	{ name: i18n.t('inspect.rate'), prop: '' }
]

const FakeChart = {
	name: 'FakeChart',
	props: {
		categories: {
			type: Array,
			default: () => []
		},
		typeList: {
			type: Array,
			default: () => []
		},
		seriesData: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			calcMaxHeight,
			chart: null,
			defaultOpts: {
				title: {
					text: i18n.t('inspect.typeCount')
				},
				tooltip: {},
				legend: {
					orient: 'vertical',
					top: 10,
					right: 20,
					data: [
						/** dynamic */
					]
				},
				xAxis: {
					data: [
						/** dynamic */
					]
				},
				yAxis: {},
				series: [
					// dynamic
					// {
					// 	name: '销售',
					// 	type: 'bar',
					// 	data: [23, 42, 12, 4, 3]
					// }
				]
			}
		}
	},
	watch: {
		categories: {
			handler: function(val, oldVal) {
				if (val && val !== oldVal) {
					this.defaultOpts.xAxis.data.push(...val)
				}
			},
			immediate: true
		},
		typeList: {
			handler: function(val, oldVal) {
				if (val && val !== oldVal) {
					this.defaultOpts.legend.data.push(...val)
				}
			},
			immediate: true
		},
		seriesData: {
			handler: function(val, oldVal) {
				if (val && val !== oldVal) {
					this.defaultOpts.series.push(...val)
				}
			},
			immediate: true
		},
		defaultOpts: {
			handler: function(val) {
				console.log('defaullt opts change: ', val)
				this.setOptions()
			},
			immediate: true,
			deep: true
		}
	},
	mounted() {
		this.$nextTick(() => {
			this.initChart()
			this.setOptions()
		})
	},
	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 {
			tableConfigStatic,
			tableConfigDynamic,
			dataListStatic: [],
			dataListDynamic: [],
			dict,
			dataType: dict[0], // 表格 | 图形
			showGraph: false,
			datetime: [],
			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,
			echartCheckTypes: []
		}
	},
	mounted() {
		this.getDataList()
	},
	methods: {
		handleOperations() {},
		handleDataTypeChange(value) {
			this.showGraph = value === dict[0] ? false : true
		},
		getDataList() {
			this.showGraph = false
			this.dataType = i18n.t('table2')
			this.echartCategories = null
			this.echartCheckTypes.splice(0)
			/** 设置默认日期 */
			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')

			/** [1] 获取上下片数据 */
			this.fetchList('sx', startTime, endTime).then(({ data: res }) => {
				console.log('sx: ', res)
				this.dataListStatic = res.data || []
			})
			/** [2] 获取产线检测类型 */
			this.fetchList('pl', startTime, endTime).then(({ data: res }) => {
				console.log('pl: ', res)
				/** TODO: 解析 nameData */
				this.parseTableProps(res.data.nameData)

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

				this.buildGraphData()
			})
		},

		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('inspect.type'), prop: 'inspectionContent' },
				...subProps,
				{ name: i18n.t('inspect.typetotal'), prop: 'sumInput' },
				{ name: i18n.t('inspect.rate'), prop: 'scrapRatio', filter: val => (val || val === 0 ? `${val}%` : '-') }
			]

			/** echarts related */
			this.echartCategories = subProps.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: [] })
			})

			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')
					}
				})
			})

			this.echartsData = result
			// [
			// 	{ name: '11', type: 'bar', data: [/**产线1*/ 2, /**产线2*/ 3] },
			// 	{ name: '222', type: 'bar', data: [1, 2, 3] }
			// ]

			console.log('echarts data: ', this.echartsData)
		},

		fetchList(type, startTime, endTime) {
			switch (type) {
				case 'sx':
					return this.$http({
						url: this.$http.adornUrl('/monitoring/qualityInspectionRecord/pageCountRecordNow'),
						method: 'POST',
						data: {
							startTime,
							endTime
						}
					}).catch(err => {
						console.error(err)
					})
				case 'pl':
					return this.$http({
						url: this.$http.adornUrl('/monitoring/qualityInspectionRecord/qualityInspectionRecordsDet'),
						method: 'POST',
						data: {
							startTime,
							endTime
						}
					}).catch(err => {
						console.error(err)
					})
			}
		}
	}
}
</script>

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