<script setup name="rateAnalysis">
import excelCop from '@/components/excel.vue'
import treeCop from '@/components/tree.vue'
import barChartCop from './components/barChart.vue'
import lineChartCop from './components/lineChart.vue'
import CurrentScatterChartCop from './components/current-scatter-chart.vue'
import SubmitBtn from '../../../components/SubmitBtn.vue'
// import { ElMessage } from 'element-plus';
import { onMounted, ref, onActivated, shallowRef, reactive, nextTick } from 'vue'
import request from '@/api/axios.js'
import tools from '@tools/htmlToPdf.js'
// import flowerRes from '@/data/flower.json'
// import lineChartRes from '@/data/lineNew.json'
/**配置参数 */
const treeHeight = ref(window.innerHeight - 150 + 'px') //tree高度
const excelHeight = ref(window.innerHeight - 150 + 'px') //excel高度
const tableHeight = ref(window.innerHeight - 150 + 'px')
/**excel 开始 */
const excelCheckIds = ref([])
const excelList = ref([])
//点击excel项时
const funExcelChange = async (obj) => { 
	excelCheckIds.value = [obj.id] //当为单选展示风机图表时
	chartExcelList.value = excelList.value.map(o=> {
		return {
			...o,
			name: o.windturbine
		}
	})  // 选中excel当前项时, excel列表赋值给dialog 下拉框
	queryForm.checkIds = excelList.value.map(o => o.id)
	checkAll.value = true
	funSubmit()
}
const funExcelCheckChange = ({ checkArr, data }) => {
	excelCheckIds.value = checkArr
}
/**tree 开始 */
const treeData = ref([])
const actTreeNode = ref(null)
const funRepeatMap = (arr) => {
	return arr.map(o => {
		if (o.children) {
			const findIndex = o.children.findIndex(p => !!p.type)
			if (findIndex !== -1) {
				o.childs = o.children
				o.children = []
				if(!actTreeNode.value){
					actTreeNode.value = o
				}
			}
		}
		return {
			...o,
			children: o.children?.length ? funRepeatMap(o.children) : []
		}
	})
}
const funGetTree = async () => {
	const res = await request.get("/power/process/tree")
	actTreeNode.value = null
	excelList.value = []
	treeData.value = funRepeatMap(res.data)
	if(actTreeNode.value){
		funCurrentChange({current: actTreeNode.value, currentNode: null})
		funExcelChange({id: actTreeNode.value.childs[0].id})
	}
}
const funTreeCheckChange = ({ current, checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys }) => {  //tree change  -> excel change
	funCurrentChange({ current, currentNode: '' })
	const checkIds = []
	if (checkedNodes.length) {
		for (const node of checkedNodes) {
			if (node.childs && node.childs.length) {
				for (const child of node.childs) {
					checkIds.push(child.id)
				}
			}
		}
	}
	excelCheckIds.value = checkIds
}
const funCurrentChange = ({ current, currentNode }) => {
	if (current.childs) {
		excelList.value = current.childs.map(o => {
			return {
				id: o.id,
				interval: o.interval,
				path: o.path,
				prepareid: o.prepareid,
				station: o.station,
				time: o.time,
				type: o.type,
				windturbine: o.windturbine,
				name: o.path.substring(o.path.indexOf(o.station + '_') + (o.station + '_').length)
			}
		})
	} else {
		excelList.value = []
	}
}
/**chart */
let chartId = 1
/**submit */
const funSubmit = async () => {
	const tempRes = await request.get('/temperature/rated/power', {
		params: {
			ids: excelCheckIds.value.join(','),
		}
	})
	// const lineRes = await request.get('/wind/deviation/ratio', {
	// 	params: {
	// 		ids: excelCheckIds.value.join(','),
	// 		mode: 0
	// 	}
	// })
	// const rosesRes = flowerRes
	// const lineRes = lineChartRes
	if (tempRes.code === 200) {
		if (tempRes.data?.length) {
			console.log(tempRes.data)
			for (const chart of tempRes.data) {
				barxAxis.data = Object.keys(chart.res1)
				barSeries[0].data = Object.values(chart.res1)
				chartId++
				lineSeries.value = [
					{
						type: 'effectScatter',
						showEffectOn: "emphasis",
						rippleEffect: {
							scale: 1
						},
						legendHoverLink: false,
						name: '',
						symbolSize: 5,
						data: chart.res2,
						yAxisIndex: 0,
					}
				]
				chartId++
			}
		}
	}
	// if(lineRes.code === 200){
	// 	if(lineRes.data?.length){
	// 		lineDataSet.value[0].source = lineRes.data[0].scatter.map(o => {
	// 			return [o.x+'', o.y]
	// 		})
	// 		lineSeries.value = [{
	// 			name: "对风频次",
	// 			type: "line",
	// 			symbol: "line", //设定为实心点
	// 			symbolSize: 0, //设定实心点的大小
	// 			smooth: true, //这个是把线变成曲线
	// 			data: lineRes.data[0].count,
	// 			yAxisIndex: 1,
	// 		},
	// 		{
	// 			type: 'effectScatter',
	// 			showEffectOn: "emphasis",
				
	// 			rippleEffect: {
	// 				scale: 1
	// 			},
	// 			legendHoverLink: false,
	// 			name: '数据散点',
	// 			symbolSize: 5,
	// 			datasetIndex: 0,
	// 			encode: {
	// 				x: 'x',
	// 				y: 'y'
	// 			},
	// 			yAxisIndex: 0,
	// 		}]
	// 	}
	// }
}
/**lineChart */
const linexAxis = reactive({
	type: 'value',
	name: '°C',
	splitLine: {
		show: false
	},
	axisTick: {
		show: true
	},
	axisLine: {
		onZero: false
	}
})
const lineyAxis = reactive([
	{
		type: 'value',
		name: 'kW',
		splitLine: {
		show: false
	},
	axisTick: {
		show: true
	},
	axisLine: {
		onZero: false
	}
	}
])
const lineSeries = ref([])
const lineDataSet = reactive([
	{
		source: []
	}
])
// 圈选散点触发函数
const funChartSelect = async (batch) => {
	const wDataArr = []
	const yDataArr = []
	let scatterls = []
	let dataSetObj = []
	wtData.value = []
	if (batch?.length && actCopList.value[0]?.dataset) {
		scatterls = batch[0].selected[1].dataIndex
		if (scatterls?.length) {
			dataSetObj = JSON.parse(actCopList.value[0].dataset)
			if (scatterls?.length) {
				for (const scatterIndex of scatterls) {
					wDataArr.push(dataSetObj[0].source[scatterIndex].k)
				}
			}
			const wtRes = await request.get('/power/fitting/filter', { params: { yk: yDataArr.join(','), wk: wDataArr.join(',') } })
			if (wtRes.code === 200) {
				let id = 1
				const tempArr = [] //用于以风机id 聚合dataArr
				if (wtRes.data?.length) {
					for (const data of wtRes.data) {
						if (tempArr.length) {
							const findIndex = tempArr.findIndex(o => o.wtId === data.wtId)
							if (findIndex !== -1) {
								if (!tempArr[findIndex].children) {
									tempArr[findIndex].children = []
								}
								tempArr[findIndex].children.push({ ...data, id: id, filter: data.filter === 0 ? '是' : '否' })
								id++
							} else {
								tempArr.push({ ...data, id: id, filter: data.filter === 0 ? '是' : '否' })
								id++
							}
						} else {
							tempArr.push({ ...data, id: id, filter: data.filter === 0 ? '是' : '否' })
							id++
						}
					}
					wtDialog.value = true
					nextTick(() => {
						wtTab.value = 'table'
						wtData.value = tempArr
					})
				}
			}
		}
	}
}
/**barChart */
const barxAxis = reactive({
	type: 'category',
	name: '℃',
	data: [],
	splitLine: {
		show: false
	},
	axisTick: {
		show: true
	},
	axisLine: {
		onZero: false
	}
})
const baryAxis = reactive({
		type: 'value',
		name: 'kW',
		splitLine: {
		show: false
	},
	axisTick: {
		show: true
	},
	axisLine: {
		onZero: false
	}
})
const barSeries = reactive([{
	name: "",
	type: "bar",
	data: [],
}])
/**dialog 数据 */
const wtDialog = ref(false)
const wtData = ref([])
const wtTab = ref('table')
/**dialog */
const dialog = ref(false)
const actChartName = ref('')
const actDiaTitle = ref('')
const diaPanelRef = ref()
const exportLoading = ref(false)
const actCopList = ref([
	// {
	// 	xAxis: [],
	// 	subtext: '',
	// 	title: '',
	// 	isRadar: false,
	// 	series: [],
	// 	yAxis: [],
	// 	dataset: []
	// }
])
// 作为actCopList的备份 在actCopList赋值多个时 同时赋值, 在dialog弹出时清空. 作用: 在actCopList变化时, 重新赋值原始数据
const actCopListBak = ref([]) 
const checkAll = ref(true)
const queryForm = reactive({
	checkIds: []
})
const funCheckAll = () => {
	checkAll.value = !checkAll.value
	if(checkAll.value){
		queryForm.checkIds = chartExcelList.value.map(o => o.id)
	}else{
		queryForm.checkIds = []
	}
}
const chartExcelList = ref([]) //dialog 下拉项
const funActCop = (obj, type) => {
	switch(type){
		case 'barChartCop':
			actChartName.value = 'barChartCop'
			obj.actCop = shallowRef(barChartCop)
			actDiaTitle.value = '平均功率-额定功率'
			break
		case 'lineChartCop':
			actChartName.value = 'lineChartCop'
			obj.actCop = shallowRef(lineChartCop)
			actDiaTitle.value = '额定功率温度分析'
			break
		// case 'CurrentScatterChartCop':
		// 	actChartName.value = 'CurrentScatterChartCop'
		// 	obj.actCop = shallowRef(CurrentScatterChartCop)
		// 	actDiaTitle.value = '静态偏航对风分析图'
		// 	break
	}
	obj.isBrush = false
	obj.id = chartId
	chartId ++
	dialog.value = true
	actCopListBak.value = []
	nextTick(() => {
		actCopList.value = [obj]
	})
}
const funDiaSubmit = async () => {
	let url = ''
	switch(actChartName.value){
		case 'barChartCop':
			url = '/temperature/rated/power'
			break
		case 'lineChartCop':
			url = '/temperature/rated/power'
			break
		// case 'CurrentScatterChartCop':
		// 	url = '' //暂无接口
		// 	break
	}
	if(url){
		const res = await request.get(url, {
			params: {
				ids: queryForm.checkIds.join(','),
				mode: 0
			}
		})
		console.log(res)
		if(res.code===200){
			actCopList.value = []
			actCopListBak.value = [] //清空备份
			if(res.data?.length){
				for(const chart of res.data){

					if(actChartName.value==='barChartCop'){
						actCopList.value.push({
							id: chartId,
							isBrush: false,
							actCop: shallowRef(barChartCop),
							title: chart.wt,
							subtext: '平均功率-额定功率',
							xAxis: {
								...barxAxis,
								data: Object.keys(chart.res1)
							},
							yAxis: baryAxis,
							series: [{
								name: "",
								type: "bar", 
								data: Object.values(chart.res1),
							}]
						})
						chartId++
					}
					if(actChartName.value === 'lineChartCop'){
						actCopList.value.push({
							id: chartId,
							isBrush: false,
							actCop: shallowRef(lineChartCop),
							title: chart.wt,
							subtext: '额定功率温度分析',
							xAxis: linexAxis,
							yAxis: lineyAxis,
							dataset: lineDataSet,
							series: [
								{
									type: 'effectScatter',
									showEffectOn: "emphasis",
									rippleEffect: {
										scale: 1
									},
									legendHoverLink: false,
									name: '',
									symbolSize: 5,
									data: chart.res2,
									yAxisIndex: 0,
								}
							]

						})
						chartId++
					}
				}
				actCopListBak.value = actCopList.value
			}
		}
	}
}
const funDiaExport = () => {
	exportLoading.value = true
	tools.scrollToPDF(diaPanelRef.value, actDiaTitle.value, () => {
		exportLoading.value = false
	})
}
const funDbClick = (obj) => {
	if(actCopListBak.value.length > 1){ //判断大于1时, 才有双击放大功能
		if(actCopList.value.length === 1){
			actCopList.value = actCopListBak.value
		}else{
			actCopList.value = [obj]
		}
	}
}
/**created */
// funGetTree()
/**activated */
onMounted(() => {
	//test
	// funSubmit()
	//
	tableHeight.value = window.innerHeight - 150 + 'px'
	excelHeight.value =(window.innerHeight - 150) + 'px'
	treeHeight.value = (window.innerHeight - 150) + 'px'
	window.addEventListener('resize', () => {
		tableHeight.value = window.innerHeight - 150 + 'px'
		excelHeight.value = (window.innerHeight - 150) + 'px'
		treeHeight.value = (window.innerHeight - 150)  + 'px'
	})
})
onActivated(() => {
	funGetTree()
})
</script>
<template>
	<div class="bg-white py-[10px] px-[10px] relative s-dialog-body">
		<!-- <el-dialog v-model="wtDialog" draggable title="风机功率点位">
			<el-tabs v-model="wtTab">
				<el-tab-pane label="数据" name="table">
					<el-table :data="wtData" row-key="id" :max-height="550">
						<el-table-column property="wtId" align="center" label="风机" />
						<el-table-column property="time" sortable :width="160" align="center" label="时间" />
						<el-table-column property="speed" sortable align="center" label="风速(m/s)" />
						<el-table-column property="power" sortable align="center" label="功率(kw)" />
						<el-table-column property="rr" sortable align="center" label="转速" />
						<el-table-column property="filter" sortable align="center" label="是否有用点" />
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="故障" name="problem" disabled>
				</el-tab-pane>
				<el-tab-pane label="预警" name="warning" disabled>
				</el-tab-pane>
			</el-tabs>
		</el-dialog> -->
		<el-dialog draggable width="80%" v-model="dialog" :title="actDiaTitle">
			<el-form class="whitespace-nowrap" :inline="true" :model="queryForm">
				<el-form-item label="" class="!mb-0">
					<el-select v-model="queryForm.checkIds" clearable @clear="checkAll = false" collapse-tags multiple>
						<el-option label="全选" :class="{'selected': checkAll}" @click="funCheckAll"></el-option>
						<el-option v-for="item in chartExcelList" :key="item.id" :value="item.id" :label="item.name"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item class="!mb-0">
					<submit-btn desc="查询" @click="funDiaSubmit"></submit-btn>
					<submit-btn desc="导出" @click="funDiaExport"></submit-btn>
				</el-form-item>
			</el-form>
			<div v-loading="exportLoading">
				<div ref="diaPanelRef" class="flex flex-wrap justify-center items-center h-[650px] overflow-y-auto overflow-x-hidden">
					<component :is="item.actCop" :width="actCopList.length > 1 ? '50%' : '100%'" height="100%" v-for="item in actCopList"
						:key="item.id" :xAxis="item.xAxis" :subtext="item.subtext" :title="item.title"
						:series="item.series" :isDiaAlone="(actCopList.length === 1)" @dblclick="funDbClick(item)" :yAxis="item.yAxis" :dataset="item.dataset" :brush="item.isBrush" @getSelected="funChartSelect"></component>
				</div>
			</div>
		</el-dialog>
		<div class="relative shadow rounded-[6px] shadow-blue-500 px-[10px] pt-[10px] pb-[10px]">
			<div class="text-[14px] absolute top-[-7px] text-[#B3B3B3] left-[20px]">数据展示</div>
			<el-row :gutter="10">
				<el-col :span="5">
					<tree-cop :data="treeData" @checkChange="funTreeCheckChange" :show-checkbox="false" :height="treeHeight"
						@currentChange="funCurrentChange" @refresh="funGetTree">
					</tree-cop>
				</el-col>
				<el-col :span="3">
					<excel-cop :checkIds="excelCheckIds" :showCheckbox="false" :data="excelList" :height="excelHeight"
						@excelChange="funExcelChange" @checkChange="funExcelCheckChange"></excel-cop>
				</el-col>
				<el-col :span="16">
					<div :style="{ height: tableHeight }"
						class="flex flex-wrap justify-center items-center overflow-x-hidden overflow-y-auto ">
						<div class="mb-[10px] w-[100%] h-[49%] flex flex-col items-end shadow rounded-[6px] shadow-blue-500">
							<el-icon class="mr-[10px] mt-[10px] cursor-pointer" size="18"
								@click="funActCop({xAxis:barxAxis, yAxis:baryAxis, series: barSeries}, 'barChartCop')">
								<ZoomIn />
							</el-icon>
							<bar-chart-cop width="100%" height="100%" subtext="平均功率-额定功率" :xAxis="barxAxis" :yAxis="baryAxis" :series="barSeries"></bar-chart-cop>
						</div>
						<div class="w-[100%] h-[49%] flex flex-col items-end shadow rounded-[6px] shadow-blue-500">
							<el-icon class="mr-[10px] mt-[10px] cursor-pointer" size="18"
								@click="funActCop({xAxis:linexAxis, yAxis:lineyAxis, series: lineSeries}, 'lineChartCop')">
								<ZoomIn />
							</el-icon>
							<line-chart-cop class="" height="100%" width="100%" :xAxis="linexAxis" :yAxis="lineyAxis"
								:series="lineSeries" subtext="额定功率温度分析" :dataset="lineDataSet"></line-chart-cop>
						</div>
						<!-- <div class="mr-[10px] w-[49%] h-[49%] flex flex-col items-end shadow rounded-[6px] shadow-blue-500" v-if="!!lineSeries.length"> -->
							<!-- <el-icon class="mr-[10px] mt-[10px] cursor-pointer" size="18"
								@click="funActCop({ xAxis: linexAxis, yAxis: lineyAxis, series: lineSeries, dataset: lineDataSet }, 'lineChartCop')">
								<ZoomIn />
							</el-icon> -->
							<!-- <current-scatter-chart-cop class="" height="100%" width="100%" :xAxis="linexAxis" :yAxis="lineyAxis"
								:series="lineSeries" subtext="风速功率-温度分析" :dataset="lineDataSet"></current-scatter-chart-cop> -->
						<!-- </div> -->
						<!-- <div class="w-[49%] h-[49%] flex flex-col items-end shadow rounded-[6px] shadow-blue-500" v-if="!!lineSeries.length"> -->
							<!-- <el-icon class="mr-[10px] mt-[10px] cursor-pointer" size="18"
								@click="funActCop({ xAxis: xAxisData, yAxis: { splitLine: { show: false } }, series: seriesData, dataSet: dataSet }, 'CurrentScatterChartCop')">
								<ZoomIn />
							</el-icon> -->
							<!-- <current-scatter-chart-cop class="" height="100%" width="100%" :xAxis="linexAxis" :yAxis="lineyAxis"
								:series="lineSeries" subtext="对风偏差分析图" :dataset="lineDataSet"></current-scatter-chart-cop> -->
						<!-- </div> -->
					</div>
				</el-col>
			</el-row>
		</div>
	</div>
</template>
<style scoped>
.s-dialog-body /deep/ .el-dialog__body{
	padding: 0px 20px;
}
</style>