<template>
	<div class="filterDiv">
		<div>
				产品：
				<el-select v-model="productIdList" multiple collapse-tags collapse-tags-tooltip placeholder="可多选" style="width: 240px" >
					<el-option v-for="item in productList" :key="item.Id" :label="item.Name" :value="item.Id" />
				</el-select>
		</div>
		<div>
			批次：
			<el-input v-model="batchId" clearable wid placeholder="批次号" style="width: 150px;" />
		</div>
		<div>
			日期：
			<el-date-picker
				v-model="queryDate"
				type="daterange"
				align="right"
				unlink-panels
				range-separator="至"
				start-placeholder="开始日期"
				end-placeholder="结束日期"
				:picker-options="pickerOptions">
			</el-date-picker>
		</div>
		<div>
			<el-button type="primary" @click="onClickQuery">查询</el-button>
		</div>
	</div>
	<div>
		<div style="width:100%; height:40vh; " ref="chartPie"></div>

		<el-divider content-position="left"></el-divider>
		<div style="width:100%; height:40vh; " ref="chartBar"></div> 
		
		<el-divider content-position="left"></el-divider>
		<div style="width:100%; height:40vh; " ref="chartBar_PT"></div>
	</div>
</template>

<script setup lang="ts">
const { isDark, toggleDark } = useDarks()
const theme = computed(() => (isDark.value ? 'dark' : 'light'))

const { formatTableDateTime,formatTableDate,formatDateTime,formatDate,formatNum,show_loading,close_loading }= utils()
import {query_table,getchart_defects_date,getchart_defects_total} from '../api/api.ts'
import * as echarts from 'echarts';

const queryDate=ref(false)
const productIdList=ref([])
const batchId=ref('')
const chartPie=ref('')//图表div
const chartBar=ref('')//图表div
const chartBar_PT=ref('')//图表div

const productList=ref([])


const pickerOptions={
	shortcuts: [{
		text: '最近一周',
		onClick(picker) {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
			picker.$emit('pick', [start, end]);
		}
	}, {
		text: '最近一个月',
		onClick(picker) {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
			picker.$emit('pick', [start, end]);
		}
	}, {
		text: '最近三个月',
		onClick(picker) {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
			picker.$emit('pick', [start, end]);
		}
	}]
}
//
onMounted(async () => {
		console.log("onMounted - DOM挂载完毕");
		let now=new Date()
		queryDate.value=[now.setDate(now.getDate() - 30),new Date()]
		show_loading()
		await getFiltersData()
		loadData()
})
const onClickQuery=()=>{
	loadData()
}
const getFiltersData =async () => {
	await query_table({ model:'product', fields:'*',order:'Name'}).then(res=>{
		console.log('getProductList',res)
		if(res.code===200) productList.value.push(...res.data)
	})
	// await query_table({ model:'step', fields:'*',order:'Name'}).then(res=>{
	// 	console.log('getStepList',res)
	// 	if(res.code===200) stepList.value.push(...res.data)
	// })
}
const loadData =async () => {
	show_loading()
	await loadPie()
	loadBar() 
	// close_loading()
}
const loadPie=async ()=>{
	const req={
		domain:[],
	}
	if(queryDate.value){//0-等于 3-大于等于  5-小于等于 6-IN "CSharpTypeName":"int"
		console.log(queryDate.value)
		req.domain.push({"FieldName": "CreateTime","FieldValue": formatDate(queryDate.value[0]),"ConditionalType": 3})
		req.domain.push({"FieldName": "CreateTime","FieldValue": formatDate(queryDate.value[1])+' 23:59:59',"ConditionalType": 5})
	}
	if(productIdList.value.length>0){
		var values=''
		for (let key in productIdList.value)
		  values+=productIdList.value[key]+','
		req.domain.push({"FieldName": "ProductId","FieldValue": values,"ConditionalType": 6})
	}
	if(batchId.value){
		req.domain.push({"FieldName": "BatchId","FieldValue": batchId.value,"ConditionalType": 0})
	}
	console.log(req)
	await getchart_defects_total(req).then(res=>{
		console.log('getchart_defects_total',res)
		if(res.code!==200){
			close_loading()
			ElMessage({
				message: res.data,
				type: 'error',
				showClose:true,
				duration: 1000,//自动关闭时间
			})
			return
		}
		// close_loading()
		//
		const resData= JSON.parse(res.data)[0]
		// const resData=JSON.parse(data.data )
		//指定图表的配置项和数据
		var dataAxis =[]// ['堵孔', '脏污'];
		var data =[]// [{value: 1548, name: '堵孔'},{value: 1548, name: '脏污'},];

		dataAxis=Object.keys(resData)
		dataAxis.forEach(key=>{
			// console.log(key,resData[key])
			data.push({name:key,value:resData[key]})
		})

		let option = {
			title: {
				text: '缺陷分布',
				subtext: '',
				left: 'left',
				textStyle: {
					color: '#A8ABB2',
					fontSize: 15
				}
			},
			toolbox: {//工具按钮
				show: true,
				feature: {
					dataView: { readOnly: false },
					// magicType: { type: ['line', 'bar'] },/*动态类型切换,比如把数据转换为条形图或柱形图*/
					restore: {},/*配置项还原*/ //问题：还原到第一次的查询条件数据！！！！
					saveAsImage: {}/*保存为图片*/
				}
			},
			tooltip: {
				trigger: 'item',
				formatter: '{b} <br/>{c} ({d}%)'
			},
			legend: {
				type: 'scroll',
				orient: 'vertical',
				right: 110,
				top: 40,
				data: dataAxis,
				textStyle: {
					color: '#4DD0D6',
					fontSize: 12
				}

			},
			color : [ '#09d0fb', '#f88cfb', '#95f8fe', '#f9f390',  '#ecfeb7' ],
			series: [
				{
					type: 'pie',
					roseType: 'area',//值超大突出超大，从大到小排序
					radius: '85%',//大小比例
					center: ['40%', '50%'],//左，上位置比例
					selectedMode: 'single',//'single'，'multiple'，'series'  单选，多选以及选择整个系列
					data:data,
					emphasis: {
						itemStyle: {
							shadowBlur: 10,
							shadowOffsetX: 0,
							shadowColor: 'rgba(0, 0, 0, 0.5)'
						}
					}
				}
			]
		};
		// Enable data zoom when user click bar.
		/*var zoomSize = 6;
		myChart.on('click', function (params) {
			console.log(dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)]);
			myChart.dispatchAction({
				type: 'dataZoom',
				startValue: dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)],
				endValue: dataAxis[Math.min(params.dataIndex + zoomSize / 2, data.length - 1)]
			});
		});*/

		//获取dom容器
		var myChart = echarts.init(chartPie.value);//(chartPie.value,'dark') //'dark' : 'light'
		myChart.setOption(option,true);
	})
}
const loadBar=async ()=>{
	const req={
		domain:[],
	}
	if(queryDate.value){//0-等于 3-大于等于  5-小于等于 6-IN "CSharpTypeName":"int"
		console.log(queryDate.value)
		req.domain.push({"FieldName": "CreateTime","FieldValue": formatDate(queryDate.value[0]),"ConditionalType": 3})
		req.domain.push({"FieldName": "CreateTime","FieldValue": formatDate(queryDate.value[1])+' 23:59:59',"ConditionalType": 5})
	}
	if(productIdList.value.length>0){
		var values=''
		for (let key in productIdList.value)
		  values+=productIdList.value[key]+','
		req.domain.push({"FieldName": "ProductId","FieldValue": values,"ConditionalType": 6})
	}
	if(batchId.value){
		req.domain.push({"FieldName": "BatchId","FieldValue": batchId.value,"ConditionalType": 0})
	}

	//--Defect 
	console.log(req)
	getchart_defects_date(req).then(res=>{
		console.log('getchart_defects_date',res)
		if(res.code!==200){
			close_loading()
			ElMessage({
				message: res.data,
				type: 'error',
				showClose:true,
				duration: 1000,//自动关闭时间
			})
			return
		}
		close_loading()

		//
		const resData= JSON.parse(res.data)
		// const resData=JSON.parse(data.data )
		//指定图表的配置项和数据
		var dataLegend=[]
		var dataAxis =[]// ['1日', '2日', '3日', '4日', '5日', '6日', '7日', '8日', '9日', '10日', '11日', '12日', '13日', '14日', '15日'];
		var data =[]// [420, 382, 401, 434, 600, 630, 610, 223, 842, 621, 190, 309, 410, 222, 400];
		var data2 = []
		console.log(resData,resData.length)
		for (var i = 0; i < resData.length; i++) {
			if(i===0){
				dataLegend=Object.keys(resData[i])
			}

			//
			dataLegend.forEach(key=>{
				// console.log('行'+i,key,resData[i][key])

				if(key=='Date'){
					let day=new Date(resData[i][key])
					dataAxis.push(`${day.getMonth()+1}月${day.getDate()}日`)
				}
				else if(key=='Total'){
					data.push(resData[i][key])
				}
				else if(i===0){
					data2.push({
						name: key,
						type: 'line',
						yAxisIndex: 1,
						data:[],
					})
				}
				// console.log(data2)
			})
		}
		for (var i = 0; i < resData.length; i++) {
			for (var j = 0; j < data2.length; j++) {
				data2[j].data.push(resData[i][data2[j].name])
			}
		}

		if(data.length>0){
			data2.splice(0,0,{
				name: '检测量(件)',
				type: 'bar',
				yAxisIndex: 0,
				data: data,
				itemStyle: {//柱子颜色
					color: new echarts.graphic.LinearGradient(
						0, 0, 0, 1,
						[
							{offset: 0, color: '#0efdff'},
							{offset: 0.5, color: '#188df0'},
							{offset: 1, color: '#188df0'}
						]
					)
				},
				emphasis: {//选中柱子时的颜色
					itemStyle: {
						color: new echarts.graphic.LinearGradient(
							0, 0, 0, 1,
							[
								{offset: 0, color: '#2378f7'},
								{offset: 0.7, color: '#2378f7'},
								{offset: 1, color: '#0efdff'}
							]
						)
					}
				},
			})
		}
		//删除日期属性
		let delIndex=dataLegend.findIndex(m=>m==='Date')
		if(delIndex>-1) dataLegend.splice(delIndex,1)
		delIndex=dataLegend.findIndex(m=>m==='Total')
		if(delIndex>-1) dataLegend.splice(delIndex,1)

		console.log('dataLegend',dataLegend)
		console.log('dataAxis',dataAxis)
		console.log('data',data)
		console.log('data2',data2)

		//----
		let option = {
			title: {
				text: '缺陷趋势',
				subtext: '',
				textStyle: {
					color: '#A8ABB2',
					fontSize: 15
				}
			},
			tooltip: {
				trigger: 'axis'
			},
			legend: {
				top: 10,
				left: 'center',
				textStyle: {
					color: '#4DD0D6',
					fontSize: 12,
				},
				data: dataLegend
			},
			toolbox: {//工具按钮
				show: true,
				feature: {
					dataView: { readOnly: false },
					magicType: { type: ['line', 'bar'] },/*动态类型切换,比如把数据转换为条形图或柱形图*/
					restore: {},/*配置项还原*/ //问题：还原到第一次的查询条件数据！！！！
					saveAsImage: {}/*保存为图片*/
				}
			},
			grid:{ //图表到周边边距
				left:40,
				right:40,
				top:60,
				btttom:20,
			},
			xAxis: {
				type: 'category',
				axisLabel: {
					/*inside: true,*/
					rotate:40,//文字倾斜
					interval:0,
					textStyle: {
						color: '#A8ABB2',
						fontSize: 12
					}
				},
				axisTick: {
					show:true,
				  alignWithLabel: true
				},
				axisLine: { //轴箭头
					show: true,
					symbol:['none', 'arrow'],
					symbolOffset: 12,
					lineStyle:{//箭头样式
						color: '#A8ABB2',
					}
				},
				data: dataAxis//['1日', '2日', '3日', '4日', '5日', '6日', '7日']
			},
			yAxis: [
				{
					type: 'value',
					name: '检测量(件)',
					position: 'left',
					min: 0,
					// min: function (value) {
					// 		return value.min;
					// },
					max: function (value) {
							return parseInt(value.max/10+1)*10;//+ parseInt(value.max/10)
					},
					interval:function (value) {
							return (parseInt(value.max/10+1)*10)/5;
					},
					axisLine: { //轴箭头
						show: true,
						symbol:['none', 'arrow'],
						symbolOffset: 12,
						lineStyle:{//箭头样式
							color: '#A8ABB2',
						}
					},
					axisTick: {
						show: false
					},
					axisLabel: {
						textStyle: {
							color: '#A8ABB2',
							fontSize: 12
						}
					}
				}, {
		      type: 'value',
		      name: '缺陷数',
		      position: 'right',
		      min: 0,
		      // min: function (value) {
		      // 		return value.min;
		      // },
		      max: function (value) {
		      		return parseInt(value.max/10+1)*10;//+ parseInt(value.max/10)
		      },
		      interval:function (value) {
		      		return (parseInt(value.max/10+1)*10)/5;
		      },
		      axisLabel: {
		        formatter: '{value}',
						textStyle: {
							color: '#A8ABB2',
							fontSize: 12
						}
		      },
					axisLine: { //轴箭头
						show: true,
						symbol:['none', 'arrow'],
						symbolOffset: 12,
						lineStyle:{//箭头样式
							color: '#A8ABB2',
						}
					},
		    },
			],
			series: data2
		};

		// Enable data zoom when user click bar.
		/*var zoomSize = 6;
		myChart.on('click', function (params) {
			console.log(dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)]);
			myChart.dispatchAction({
				type: 'dataZoom',
				startValue: dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)],
				endValue: dataAxis[Math.min(params.dataIndex + zoomSize / 2, data.length - 1)]
			});
		});*/

		//获取dom容器
		var myChart = echarts.init(chartBar.value);//(chartBar.value,'dark') //'dark' : 'light'
		myChart.setOption(option,true);
	})

	//--PT
	console.error('--------------PT-------------')
	req.model='Order',
	req.fields='ProductId,BatchId,SN,PT1,PT2,PT3,PT5,PT6,PTValue'
	req.order='CreateTime desc'
	console.log(req)
	// await getchart_defects_date(req).then(res=>{
	await query_table(req).then(res=>{
		console.log('query_table PT',res)
		if(res.code!==200){
			close_loading()
			ElMessage({
				message: res.data,
				type: 'error',
				showClose:true,
				duration: 1000,//自动关闭时间
			})
			return
		}
		close_loading()

		//
		const resData = res.data
		// const resData=JSON.parse(data.data )
		//指定图表的配置项和数据
		let dataAxis = ['PT1', 'PT2', 'PT3', 'PT4', 'PT5', 'PT均值'] // ['1日', '2日', '3日', '4日', '5日', '6日', '7日', '8日', '9日', '10日', '11日', '12日', '13日', '14日', '15日'];
		let dataLegend: any[]=[]
		let data =  [];

		console.log(resData, resData.length)
		for(var i=0;i<10 && i<resData.length;i++){
			dataLegend.push(resData[i]['SN'])
			data.push({
				name: resData[i]['SN'],
				type: 'line',
				data: [resData[i].PT1,resData[i].PT2,resData[i].PT3,resData[i].PT5,resData[i].PT6,resData[i].PTValue],
			})
		}
		 
/*
		if(data.length>0){
			data2.splice(0,0,{
				name: '检测量(件)',
				type: 'bar',
				yAxisIndex: 0,
				data: data,
				itemStyle: {//柱子颜色
					color: new echarts.graphic.LinearGradient(
						0, 0, 0, 1,
						[
							{offset: 0, color: '#0efdff'},
							{offset: 0.5, color: '#188df0'},
							{offset: 1, color: '#188df0'}
						]
					)
				},
				emphasis: {//选中柱子时的颜色
					itemStyle: {
						color: new echarts.graphic.LinearGradient(
							0, 0, 0, 1,
							[
								{offset: 0, color: '#2378f7'},
								{offset: 0.7, color: '#2378f7'},
								{offset: 1, color: '#0efdff'}
							]
						)
					}
				},
			})
		}
*/
		console.log('dataLegend',dataLegend)
		console.log('dataAxis',dataAxis)
		console.log('data',data) 

		//----
		let option = {
			title: {
				text: 'PT值变化趋势',
				subtext: '',
				textStyle: {
					color: '#A8ABB2',
					fontSize: 15
				}
			},
			tooltip: {
				trigger: 'axis'
			},
			legend: {
				top: 10,
				left: 'center',
				textStyle: {
					color: '#4DD0D6',
					fontSize: 12,
				},
				data: dataLegend
			},
			toolbox: {//工具按钮
				show: true,
				feature: {
					dataView: { readOnly: false },
					magicType: { type: ['line', 'bar'] },/*动态类型切换,比如把数据转换为条形图或柱形图*/
					restore: {},/*配置项还原*/ //问题：还原到第一次的查询条件数据！！！！
					saveAsImage: {}/*保存为图片*/
				}
			},
			grid:{ //图表到周边边距
				left:40,
				right:40,
				top:60,
				btttom:20,
			},
			xAxis: {
				type: 'category',
				axisLabel: {
					/*inside: true,*/
					rotate:40,//文字倾斜
					interval:0,
					textStyle: {
						color: '#A8ABB2',
						fontSize: 12
					}
				},
				axisTick: {
					show:true,
				  alignWithLabel: true
				},
				axisLine: { //轴箭头
					show: true,
					symbol:['none', 'arrow'],
					symbolOffset: 12,
					lineStyle:{//箭头样式
						color: '#A8ABB2',
					}
				},
				data: dataAxis//['1日', '2日', '3日', '4日', '5日', '6日', '7日']
			},
			yAxis: [
				{
					type: 'value',
					name: 'PT值',
					position: 'left',
					// min: 0,
					min: function (value) {
							return value.min;
					},
					max: function (value) {
						return value.max//parseInt(value.max/10+1)*10;//+ parseInt(value.max/10)
					},
					interval:function (value) {
						return (parseInt(value.max/10+1)*10)/5;
					},
					axisLine: { //轴箭头
						show: true,
						symbol:['none', 'arrow'],
						symbolOffset: 12,
						lineStyle:{//箭头样式
							color: '#A8ABB2',
						}
					},
					axisTick: {
						show: false
					},
					axisLabel: {
						textStyle: {
							color: '#A8ABB2',
							fontSize: 12
						}
					}
				}, 
			],
			series: data
		};

		// Enable data zoom when user click bar.
		/*var zoomSize = 6;
		myChart.on('click', function (params) {
			console.log(dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)]);
			myChart.dispatchAction({
				type: 'dataZoom',
				startValue: dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)],
				endValue: dataAxis[Math.min(params.dataIndex + zoomSize / 2, data.length - 1)]
			});
		});*/

		//获取dom容器
		var myChart2 = echarts.init(chartBar_PT.value);//(chartBar.value,'dark') //'dark' : 'light'
		myChart2.setOption(option,true);
	})

}
 

const formatQualifiedRatio=(row)=> {
	return parseInt(Math.round(row.Qualified*100/row.Total))
}
</script>

<style scoped>
	.filterDiv{
		/* background-color: azure; */
		border-bottom:1px solid #CDD0D6;
		margin: 0px;
		margin-bottom: 10px;
		padding-bottom: 10px;
		width: 100%;
		display: flex;
		justify-content:space-around;
	}
	.paging{
		margin: 10px;
		width: 100%;
/* 		display: flex;
		justify-content: flex-end; */
	}

	.kanbanDiv{
		padding:14px 14px 0px 14px;
		font-size:12px;
	}
	.kanbanTitle{
		font-weight:bold;
		font-size:16px;
		margin-right: 80px;
	}
	.kanbanVal {
		font-weight:bold;
	  font-size: 34px;
	  color: rgba(14,253,255,0.5);
		margin-right: 10px;
	}
	.kanbanBottom{
		width: 100%;
		display: flex;
		justify-content:space-around;
		margin-top: 5px;
		padding: 5px;
		border-top:1px solid #909399;
		p{margin:5px;}
	}

</style>
