<template>
	<div class="filterDiv">
		<div>
				产品：
				<el-select v-model="productId"  clearable 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> 
		<!-- PT LINE -->
		<el-divider content-position="left"></el-divider>
		<div style="width:100%; height:80vh; " 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 productId=ref('')
const batchId=ref('') 
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() - 1),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)
		console.log('typeof',typeof(productList.value[0].Id))
	})
	// await query_table({ model:'step', fields:'*',order:'Name'}).then(res=>{
	// 	console.log('getStepList',res)
	// 	if(res.code===200) stepList.value.push(...res.data)
	// })

	//显示最近生产的产品
	const req={
		model:'order',
		fields:'ProductId',
		domain:[],
		order:'id desc',
		pageNum:1,
		pageSize:1,
	}
	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})
	await query_table(req).then(res=>{  
		if(res.code==200 && res.data && res.data.length>0){  
			let aar=[]
			aar.push(...res.data) 
			let idIndex=productList.value.findIndex(m=>m.Id==aar[0].ProductId)
			if(idIndex && idIndex>-1)
				productId.value=productList.value[idIndex].Id//aar[0].productId 
		}  
	})
}
const loadData =async () => {
	console.log('loadData',productId.value)
	if(!productId.value){
		close_loading()
		ElMessage({
			message: '请选择产品！',
			type: 'error',
			showClose:true,
			duration: 2000,//自动关闭时间
		})
		return
	}
	show_loading() 
	loadBar() 
	// close_loading()
}
 
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(productId.value){
	// 	var values=''
	// 	for (let key in productIdList.value)
	// 	  values+=productIdList.value[key]+','
	// 	req.domain.push({"FieldName": "ProductId","FieldValue": values,"ConditionalType": 6})
	// }
	if(productId.value){
		req.domain.push({"FieldName": "ProductId","FieldValue": productId.value,"ConditionalType": 0})
	} 
	if(batchId.value){
		req.domain.push({"FieldName": "BatchId","FieldValue": batchId.value,"ConditionalType": 0})
	} 

	//--PT
	req.model='Order'
	req.fields='SN,PTValue,CreateTime'
	req.order='CreateTime'
	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 = [] // ['1日', '2日', '3日', '4日', '5日', '6日', '7日', '8日', '9日', '10日', '11日', '12日', '13日', '14日', '15日'];
		let dataLegend: any[]=[]
		let markLineData={}
		let PTUpFloatValue,PTDownFloatValue
		const productInfo=productList.value.find(m=>m.Id===productId.value)
		if(productInfo && productInfo.PTBaseValue!=0){
			console.error(productInfo.PTBaseValue,productInfo.PTUpFloatValue,productInfo.PTDownFloatValue)
			PTUpFloatValue=productInfo.PTBaseValue+productInfo.PTUpFloatValue
			PTDownFloatValue=productInfo.PTBaseValue-productInfo.PTDownFloatValue
			markLineData={
				data: [[
					{coord:[0,PTUpFloatValue]},
					{coord:[resData.length-1,PTUpFloatValue]}//如何获取grid上侧最大值，目前是写死的
				],[
					{coord:[0,PTDownFloatValue]},
					{coord:[resData.length-1,PTDownFloatValue]}//如何获取grid上侧最大值，目前是写死的
				]],
				lineStyle: {
					color: "red", 
				},
				label:{
					show:true,
					color:'red',
					formatter:function(arr){
						console.log('上下限',arr)
						return arr.dataIndex==0?'上限':'下限'
					}
				}
			} 
		}
		let data ={type:'line',data:[],markLine: markLineData };
		console.log(resData, resData.length,PTUpFloatValue,PTDownFloatValue)
		for(var i=0; i<resData.length;i++){
			dataAxis.push(i+1)
			// dataLegend.push(resData[i]['SN'])
			// data.push({
			// 	name: i+1,
			// 	type: 'line',
			// 	data: [resData[i].PTValue],
			// })
			
			data.data.push(resData[i].PTValue)
		} 

		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',
				axisPointer: { type: 'cross' }, //十字准星指示器
				formatter: function(arr){
					// console.log('tooltip.formatter',arr)
					if(!arr || arr.length<1) return ''

					let result=`索引 : ${arr[0].axisValueLabel}<br/>SN : ${resData[parseInt(arr[0].axisValueLabel)-1].SN}<br/>PT均值 : ${arr[0].value}<br/>时间 : ${formatDateTime(resData[parseInt(arr[0].axisValueLabel)-1].CreateTime)}`
					// arr.forEach(item=>{ 
					// 	result+=`<br/>PT均值 : ${item.value} %` 
					// })
					// seriesIndex

					return result;//'日期1 : {b}<br/>检测量 : {c0} 件<br/>合格率 : {c1} %<br/>不合格率 : {c2} %'  //a0=检测量(件) a1=合格率(%)
				}
			},
			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,
			},
			color : [ '#09d0fb'],
			xAxis: {
				type: 'category', 
				name: '数量',
				axisLabel: {
					/*inside: true,*/
					// rotate:40,//文字倾斜
					interval:0,
					textStyle: {
						color: '#A8ABB2',
						fontSize: 12
					}
				},
				axisTick: {
					show:true,
					alignWithLabel: true
				},
				axisLabel:{
					rotate:45
				},
				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: function(value) {//取最小值向下取整为最小刻度
						console.error(PTDownFloatValue)
						if(!PTDownFloatValue || PTDownFloatValue==0) return value.min;// Math.floor(value.min)
						return (PTDownFloatValue>value.min?value.min:PTDownFloatValue)
					},
					max: function(value) {//取最大值向上取整为最大刻度
						if(!PTUpFloatValue || PTUpFloatValue==0) return value.max;// Math.ceil(value.max) 
						return (PTUpFloatValue>value.max?PTUpFloatValue:value.max)
					}, 
					minInterval:function (value) {
						return (value.max-value.min)/10;
					},
					// minInterval:0.02,
					// interval:0.02,
					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>
