<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>
		<el-row :gutter="12">
			<el-col :span="6">
				<el-card :body-style="{ padding: '0px' }">
				 <div class="kanbanDiv" >
					<span class="kanbanTitle">当日合适率</span><p/>
					<span class="kanbanVal">{{dataList_kanban[0][2]}}</span>%
					<div class="kanbanBottom">
						<p>检测量：{{dataList_kanban[0][0]}}</p><p>合格量：{{dataList_kanban[0][1]}}</p>
					</div>
				 </div>
				</el-card>
			</el-col>
			<el-col :span="6">
				<el-card :body-style="{ padding: '0px' }">
				 <div class="kanbanDiv" >
					<span class="kanbanTitle">当月合适率</span><p/>
					<span class="kanbanVal">{{dataList_kanban[1][2]}}</span>%
					<div class="kanbanBottom">
						<p>检测量：{{dataList_kanban[1][0]}}</p><p>合格量：{{dataList_kanban[1][1]}}</p>
					</div>
				 </div>
				</el-card>
			</el-col>
			<el-col :span="6">
				<el-card :body-style="{ padding: '0px' }">
				 <div class="kanbanDiv" >
					<span class="kanbanTitle">当季合适率</span><p/>
					<span class="kanbanVal">{{dataList_kanban[2][2]}}</span>%
					<div class="kanbanBottom">
						<p>检测量：{{dataList_kanban[2][0]}}</p><p>合格量：{{dataList_kanban[2][1]}}</p>
					</div>
				 </div>
				</el-card>
			</el-col>
			<el-col :span="6">
				<el-card :body-style="{ padding: '0px' }">
				 <div class="kanbanDiv" >
					<span class="kanbanTitle">当年合适率</span><p/>
					<span class="kanbanVal">{{dataList_kanban[3][2]}}</span>%
					<div class="kanbanBottom">
						<p>检测量：{{dataList_kanban[3][0]}}</p><p>合格量：{{dataList_kanban[3][1]}}</p>
					</div>
				 </div>
				</el-card>
			</el-col>
		</el-row>

		<el-divider content-position="left"></el-divider>
		<div style="width:100%; height:60vh; " ref="chartBar"></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_qualified_rate,getchart_qualified_date} from '../api/api.ts'
import * as echarts from 'echarts';

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

const productList=ref([])
const dataList_kanban = ref([[0,0,0],[0,0,0],[0,0,0],[0,0,0]])



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 loadKanban()
	loadBar()
	// close_loading()
}

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

		//
		const resDataList=res.data//JSON.parse(res.data)
		dataList_kanban.value.length=0
		//日
		let nums=resDataList[0]
		let rate=nums[1]?parseInt(Math.round(nums[1]*100/nums[0])):0
		dataList_kanban.value.push([nums[0],nums[1],rate])
		// //月
		nums=resDataList[1]
		rate=nums[1]?parseInt(Math.round(nums[1]*100/nums[0])):0
		dataList_kanban.value.push([nums[0],nums[1],rate])
		// //季
		nums=resDataList[2]
		rate=nums[1]?parseInt(Math.round(nums[1]*100/nums[0])):0
		dataList_kanban.value.push([nums[0],nums[1],rate])
		// //年
		nums=resDataList[3]
		rate=nums[1]?parseInt(Math.round(nums[1]*100/nums[0])):0
		dataList_kanban.value.push([nums[0],nums[1],rate])
		console.log(dataList_kanban.value)
		// //看板数据滚动动画0-n
		// $(".shu1").numScroll();
	})
}
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})
	}
	console.log(req)
	await getchart_qualified_date(req).then(res=>{
		console.log('getchart_qualified_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 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 = [];
		var data3 = [];
		for (var i = 0; i < resData.length; i++) {
			var day=new Date(resData[i].Date)
			dataAxis.push(`${day.getMonth()+1}月${day.getDate()}日`)
			data.push(resData[i].Total)
			data2.push(resData[i].Qualified?parseInt(resData[i].Qualified*100/resData[i].Total) :0);
			data3.push(100-data2[i]);
		}

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

		//----
		let option = {
			title: {
				text: '合格率分析',
				subtext: '',
				textStyle: {
					color: '#A8ABB2',
					fontSize: 15
				}
			},
			toolbox: {//工具按钮
				show: true,
				feature: {
					dataView: { readOnly: false },
					magicType: { type: ['line', 'bar'] },/*动态类型切换,比如把数据转换为条形图或柱形图*/
					// restore: {},/*配置项还原*/ //问题：还原到第一次的查询条件数据！！！！
					saveAsImage: {}/*保存为图片*/
				}
			},
			tooltip: {
				trigger: 'axis',//axis-柱/拆线等有轴图  item-散点图，饼图
				axisPointer: { type: 'cross' }, //十字准星指示器
				// formatter:'日期 : {b}<br/>检测量 : {c0} 件<br/>合格率 : {c1} %<br/>不合格率 : {c2} %',  //a0=检测量(件) a1=合格率(%)
				formatter: function(arr){
					// console.log('tooltip.formatter',arr)
					if(!arr || arr.length<1) return ''

					let result=`日期 : ${arr[0].axisValueLabel}`
					arr.forEach(item=>{
						switch(item.seriesIndex){
							case 0:
								result+=`<br/>检测量 : ${item.value} 件`
								break
							case 1:
								result+=`<br/>合格率 : ${item.value} %`
								break
							case 2:
								result+=`<br/>不合格率 : ${item.value} %`
								break
						}
					})
					// seriesIndex

					return result;//'日期1 : {b}<br/>检测量 : {c0} 件<br/>合格率 : {c1} %<br/>不合格率 : {c2} %'  //a0=检测量(件) a1=合格率(%)
				}
			},
		  	legend: {
				top: 10,
				left: 'center',
				data: ['检测量(件)', '合格率(%)', '不合格率(%)'], //勾选图例，必需=x/yAxis.name
				textStyle: {
					color: '#4DD0D6',
					fontSize: 12
				}
			},
			grid:{ //图表到周边边距
				left:40,
				right:40,
				top:80,
				btttom:20,
			},
			xAxis: [{
					type: 'category',
					axisTick: {
						show:true,
						alignWithLabel: true
					},
					data: dataAxis,
					axisLabel:{
						rotate:40
					},
					axisLine: { //轴箭头
						show: true,
						symbol:['none', 'arrow'],
						symbolOffset: 12,
						lineStyle:{//箭头样式
							color: '#A8ABB2',
						}
					},
				}
			],
			yAxis: [
				{
				type: 'value',
				name: '检测量(件)',
				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;
						},
				position: 'left',
						axisLine: { //轴箭头
							show: true,
							symbol:['none', 'arrow'],
							symbolOffset: 12,
							lineStyle:{//箭头样式
								color: '#A8ABB2',
							}
						},
						axisLabel: {
							textStyle: {
								color: '#A8ABB2',
								fontSize: 12
							}
						},
				},
				{
				type: 'value',
				name: '不/合格率(%)',
				min: 0,
				max: 100,
						interval:10,
				position: 'right',
				axisLabel: {
					formatter: '{value} %',
							textStyle: {
								color: '#A8ABB2',
								fontSize: 12
							}
				},
						axisLine: { //轴箭头
							show: true,
							symbol:['none', 'arrow'],
							symbolOffset: 12,
							lineStyle:{//箭头样式
								color: '#A8ABB2',
							}
						},
				},
					//Y轴第1后个之后的配置可以只配置type
				// {
				//   type: 'value',
				// }
			],
			series: [
				{
				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'}
									]
								)
							}
						},
				},
				{
				name: '合格率(%)',
				type: 'line',
				smooth: true,
				yAxisIndex: 1,
				data: data2,
						itemStyle: {
							normal: {
								color:'#1efdff',//折线点的颜色
								lineStyle: {
									color: "#0EF00F",//折线的颜色
									width:2,
								}
							},
						},
				},
				{
				name: '不合格率(%)',
				type: 'line',
				smooth: true,
				yAxisIndex: 1,
				data: data3,
						itemStyle: {
							normal: {
								color: "#F06C6C",//折线点的颜色
								lineStyle: {
									color: "#F56C6C",//折线的颜色
									width:2,
								}
							},
						},
				}
			]
		};
		// 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);
	})
}

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>
