// 首页 右
<template>
	<a-card style="margin: 0.5em">
		<!-- 搜索条件 -->
		<a-row>
			<a-col :span="18">
				<a-row>
					<a-col :span="12" class="search-item">
						<!-- 时间 -->
						<label>{{
							getI18n('system', 'SYSTEM_Home_ProcessTime')
						}}</label>
						<a-range-picker
							format="YYYY-MM-DD"
							:value="timeValue"
							@change="onTimeChange"
						/>
					</a-col>
					<a-col :span="12" class="search-item">
						<!-- 流程名称 -->
						<label>{{
							getI18n('system', 'SYSTEM_Home_ProcessName')
						}}</label>
						<a-input
							style="width: 100%"
							:placeholder="
								getI18n('common', 'Common_Please_Enter', [
									getI18n(
										'system',
										'SYSTEM_Home_ProcessName'
									),
								])
							"
							v-model:value="searchParams.name"
						/>
					</a-col>
				</a-row>
			</a-col>

			<a-col :span="6" style="min-width: 90px">
				<div class="button-wrapper">
					<!-- 重置按钮 -->
					<a-button
						@click="onResetClick"
						class="button-item"
						:loading="searchLoading"
					>
						<reload-outlined />
						{{ getI18n('common', 'Common_Clear') }}
					</a-button>
				</div>
			</a-col>
		</a-row>
		<!-- 卡片 -->
		<a-row>
			<!-- 发起数 -->
			<a-col :span="8">
				<statistic-card-wrapper
					:is-loading="taskStatisticsNumLoading"
					:card-label="
						getI18n('system', 'SYSTEM_Home_InitiatorsNumber')
					"
					:card-value="taskStatisticsNumOpt?.startNum"
				/>
			</a-col>
			<!-- 办理中 -->
			<a-col :span="8">
				<statistic-card-wrapper
					:is-loading="taskStatisticsNumLoading"
					:card-label="getI18n('system', 'SYSTEM_Home_InProcess')"
					:card-value="taskStatisticsNumOpt?.handleNum"
				/>
			</a-col>
			<!-- 办理结束 -->
			<a-col :span="8">
				<statistic-card-wrapper
					:is-loading="taskStatisticsNumLoading"
					:card-label="getI18n('system', 'SYSTEM_Home_HandlingEnd')"
					:card-value="taskStatisticsNumOpt?.endNum"
				/>
			</a-col>
		</a-row>

		<!-- 发起任务数量Top10 -->
		<!-- <div :class="style['title']">
			{{ getI18n('system', 'SYSTEM_Home_TaskLaunchTop') }}
		</div>
		<echarts-wrapper
			:is-loading="categoryListLoading"
			:echarts-id="echartsLaunchId"
		/> -->
		<!-- 办理任务数量Top10 -->
		<div :class="style['title']">
			{{ getI18n('system', 'SYSTEM_Home_TaskHandle') }}
		</div>
		<echarts-wrapper
			:is-loading="statisticsTaskHandleLoading"
			:echarts-id="echartsAverageTimeId"
		/>
		<!-- 办理平均耗时Top10 -->
		<div :class="style['title']">
			{{ getI18n('system', 'SYSTEM_Home_TaskAverageTime') }}
		</div>
		<echarts-wrapper
			:is-loading="statisticsTaskTimeAvgLoading"
			:echarts-id="echartsLaunchClassificationId"
		/>

		<!-- 占位 -->
		<div :class="style['title']" style="color: transparent">
			{{ getI18n('system', 'SYSTEM_Home_TaskLaunchTop') }}
		</div>
		<a-row :gutter="24">
			<a-col :span="24">
				<div style="height: 30em; width: 100%"></div>
			</a-col>
		</a-row>
	</a-card>
</template>

<script lang="ts">
import { ReloadOutlined } from '@ant-design/icons-vue'
import { defineComponent, reactive, ref, onMounted, watch } from 'vue'
import style from './index.module.less'
import { getI18n } from '@/utils/i18n'

import { RequestResult } from '@/utils/request/model' // PaginationData

import { Moment } from 'moment' // moment,

import * as echarts from 'echarts'
import {
	EchartsWrapper,
	StatisticCardWrapper,
} from '@/views/home/components/components'

// import { ProcessConstant } from '@/utils/constant'
import {
	StatisticsAverageTimeModel,
	StatisticsListNumsModel,
	StatisticsNumsModel,
} from '@/types/process'
// import { getProcessCategoryListApi } from '@/api/process-category'
// import { GetProcessCategoryListParamsModel } from '@/api/process-category/model'

import {
	getTaskStatisticsNumApi,
	getStatisticsTaskHandleApi,
	getStatisticsTaskTimeAvgApi,
} from '@/api/process-deployments'
import { GetInstanceStatisticsParamsModel } from '@/api/process-deployments/model'

export default defineComponent({
	components: {
		ReloadOutlined,
		EchartsWrapper,
		StatisticCardWrapper,
	},
	props: {
		// 查询重置按钮loading
		searchLoading: {
			type: Boolean,
			default: false,
		},
	},
	emits: [],
	setup() {
		// 列表参数
		const searchParams = reactive<GetInstanceStatisticsParamsModel>({
			// startTime: moment().startOf('month').format('YYYY-MM-DD'),
			// endTime: moment().format('YYYY-MM-DD'),
		})
		// 时间
		const timeValue = ref<Moment[]>([]) // moment().startOf('month'), moment()

		// 任务数统计
		const taskStatisticsNumLoading = ref<boolean>(false)
		const taskStatisticsNumOpt = ref<StatisticsNumsModel>()

		// 办理任务数top10
		const statisticsTaskHandleLoading = ref<boolean>(false)
		const statisticsTaskHandleOpt = ref<string[]>()
		const statisticsTaskHandleOptDataYAxis = ref<string[]>()

		// 办理任务平均耗时top10
		const statisticsTaskTimeAvgLoading = ref<boolean>(false)
		const statisticsTaskTimeAvgOpt = ref<number[]>()
		const statisticsTaskTimeAvgDataYAxis = ref<string[]>()

		// 发起任务数量Top10
		// const echartsLaunchId = ref<string>(
		// 	getI18n('system', 'SYSTEM_Home_TaskLaunchTopId')
		// )
		// 办理任务数量Top10
		const echartsAverageTimeId = ref<string>(
			getI18n('system', 'SYSTEM_Home_TaskHandleId')
		)
		// 办理平均耗时Top10
		const echartsLaunchClassificationId = ref<string>(
			getI18n('system', 'SYSTEM_Home_TaskAverageTimeId')
		)

		const initBarEcharts = () => {
			// 发起任务数量Top10
			// const chartTaskLaunchDom = document.getElementById(
			// 	getI18n('system', 'SYSTEM_Home_TaskLaunchTopId')
			// )!
			// if (chartTaskLaunchDom != null) {
			// 	echarts.dispose(chartTaskLaunchDom)
			// }
			// const myTaskLaunchChart = echarts.init(chartTaskLaunchDom)
			// const optionTaskLaunch: echarts.EChartsOption = {
			// 	tooltip: {
			// 		trigger: 'axis',
			// 		axisPointer: {
			// 			type: 'shadow',
			// 		},
			// 	},
			// 	xAxis: {
			// 		show: false,
			// 	},
			// 	yAxis: {
			// 		show: true,
			// 		type: 'name',
			// 		data: echartsTaskLaunchDataAxis.value,
			// 		axisTick: {
			// 			show: true,
			// 			interval: 'auto',
			// 		},
			// 		axisLabel: {
			// 			interval: 0,
			// 		},
			// 	},
			// 	series: [
			// 		{
			// 			name: getI18n('system', 'SYSTEM_Home_TaskLaunchTop'),
			// 			type: 'bar',
			// 			barWidth: '90%',
			// 			label: {
			// 				show: true,
			// 				position: 'right',
			// 			},
			// 			itemStyle: {
			// 				color: new echarts.graphic.LinearGradient(
			// 					0,
			// 					0,
			// 					1,
			// 					0,
			// 					[
			// 						{ offset: 0, color: '#83bff6' },
			// 						{ offset: 0.5, color: '#188df0' },
			// 						{ offset: 1, color: '#188df0' },
			// 					]
			// 				),
			// 			},
			// 			emphasis: {
			// 				itemStyle: {
			// 					color: new echarts.graphic.LinearGradient(
			// 						0,
			// 						0,
			// 						1,
			// 						0,
			// 						[
			// 							{ offset: 0, color: '#2378f7' },
			// 							{ offset: 0.7, color: '#2378f7' },
			// 							{ offset: 1, color: '#83bff6' },
			// 						]
			// 					),
			// 				},
			// 			},
			// 			data: echartsTaskLaunchData.value,
			// 		},
			// 	],
			// }
			// optionTaskLaunch && myTaskLaunchChart.setOption(optionTaskLaunch)

			// 办理任务数量Top10
			const chartTaskHandleDom = document.getElementById(
				getI18n('system', 'SYSTEM_Home_TaskHandleId')
			)!
			if (chartTaskHandleDom != null) {
				echarts.dispose(chartTaskHandleDom)
			}
			const myTaskHandleChart = echarts.init(chartTaskHandleDom)
			const optionTaskHandle: echarts.EChartsOption = {
				xAxis: {
					type: 'category',
					show: true,
					axisLine: {
						show: false,
					},
					axisTick: {
						show: false,
					},
					axisLabel: {
						lineHeight: 14,
						interval: 0,
						formatter: function (params) {
							let newParamsName = '' // 最终拼接成的字符串
							let paramsNameNumber = params.length // 实际标签的个数
							let provideNumber = 5 // 每行能显示的字的个数
							let rowNumber = Math.ceil(
								paramsNameNumber / provideNumber
							) // 换行的话，需要显示几行，向上取整
							/**
							 * 判断标签的个数是否大于规定的个数， 如果大于，则进行换行处理 如果不大于，即等于或小于，就返回原标签
							 */
							// 条件等同于rowNumber>1
							if (paramsNameNumber > provideNumber) {
								/** 循环每一行,p表示行 */
								for (let p = 0; p < rowNumber; p++) {
									let tempStr = '' // 表示每一次截取的字符串
									let start = p * provideNumber // 开始截取的位置
									let end = start + provideNumber // 结束截取的位置
									// 此处特殊处理最后一行的索引值
									if (p == rowNumber - 1) {
										// 最后一次不换行
										tempStr = params.substring(
											start,
											paramsNameNumber
										)
									} else {
										// 每一次拼接字符串并换行
										tempStr =
											params.substring(start, end) + '\n'
									}
									newParamsName += tempStr // 最终拼成的字符串
								}
							} else {
								// 将旧标签的值赋给新标签
								newParamsName = params
							}
							// 将最终的字符串返回
							return newParamsName
						},
					},
					data: statisticsTaskHandleOptDataYAxis.value,
				},
				splitLine: {
					show: true,
					lineStyle: {
						type: 'dashed',
					},
				},
				triggerEvent: true,

				yAxis: {
					type: 'value',
					axisLine: {
						show: false,
					},
				},
				tooltip: {
					trigger: 'item',
					formatter: '{b} {c}', // {a} <br/>
				},
				series: [
					{
						name: getI18n('system', 'SYSTEM_Home_TaskHandle'),
						type: 'bar',
						label: {
							show: true,
							position: 'top',
						},
						barWidth: '30%',
						barMaxWidth: 20,
						data: statisticsTaskHandleOpt.value,
						itemStyle: {
							color: new echarts.graphic.LinearGradient(
								0,
								0,
								0,
								1,
								[
									{ offset: 0, color: '#83bff6' },
									{ 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: '#83bff6' },
									]
								),
							},
						},
					},
				],
			}
			optionTaskHandle && myTaskHandleChart.setOption(optionTaskHandle)

			// 办理平均耗时Top10
			const chartTaskAverageTimeDom = document.getElementById(
				getI18n('system', 'SYSTEM_Home_TaskAverageTimeId')
			)!
			if (chartTaskAverageTimeDom != null) {
				echarts.dispose(chartTaskAverageTimeDom)
			}
			const myTaskAverageTimeChart = echarts.init(chartTaskAverageTimeDom)
			const optionTaskAverageTime: echarts.EChartsOption = {
				yAxis: {
					type: 'category',
					show: true,
					axisLine: {
						show: false,
					},
					axisTick: {
						show: false,
					},
					axisLabel: {
						lineHeight: 14,
						interval: 0,
						formatter: function (params: string) {
							let newParamsName = '' // 最终拼接成的字符串
							let paramsNameNumber = params.length // 实际标签的个数
							let provideNumber = 5 // 每行能显示的字的个数
							let rowNumber = Math.ceil(
								paramsNameNumber / provideNumber
							) // 换行的话，需要显示几行，向上取整
							/**
							 * 判断标签的个数是否大于规定的个数， 如果大于，则进行换行处理 如果不大于，即等于或小于，就返回原标签
							 */
							// 条件等同于rowNumber>1
							if (paramsNameNumber > provideNumber) {
								/** 循环每一行,p表示行 */
								for (let p = 0; p < rowNumber; p++) {
									let tempStr = '' // 表示每一次截取的字符串
									let start = p * provideNumber // 开始截取的位置
									let end = start + provideNumber // 结束截取的位置
									// 此处特殊处理最后一行的索引值
									if (p == rowNumber - 1) {
										// 最后一次不换行
										tempStr = params.substring(
											start,
											paramsNameNumber
										)
									} else {
										// 每一次拼接字符串并换行
										tempStr =
											params.substring(start, end) + '\n'
									}
									newParamsName += tempStr // 最终拼成的字符串
								}
							} else {
								// 将旧标签的值赋给新标签
								newParamsName = params
							}
							// 将最终的字符串返回
							return newParamsName
						},
					},
					data: statisticsTaskTimeAvgDataYAxis.value,
				},
				xAxis: {
					show: false,
				},
				grid: {
					left: '1%', // 与容器左侧的距离
					right: '2%', // 与容器右侧的距离
					top: '10%', // 与容器顶部的距离
					bottom: '10%', // 与容器底部的距离
					borderWidth: 10,
					containLabel: true,
				},
				tooltip: {
					trigger: 'item',
					formatter: '{b}', // {a} <br/>
				},
				series: [
					{
						name: getI18n('system', 'SYSTEM_Home_TaskAverageTime'),
						type: 'bar',
						label: {
							show: true,
							color: '#000',
							position: [10, 5],
							formatter: (params: any) => {
								let _day = Math.floor(
									Math.floor(
										Math.floor(
											Math.round(params.data / 1000) / 60
										) / 60
									) / 24
								)
								let _hour =
									Math.floor(
										Math.floor(
											Math.round(params.data / 1000) / 60
										) / 60
									) % 24
								let _minute =
									Math.floor(
										Math.round(params.data / 1000) / 60
									) % 60
								let _second =
									Math.round(params.data / 1000) % 60
								return `${_day ? _day + '天' : ''}${
									_hour ? _hour + '小时' : ''
								}${_minute ? _minute + '分钟' : ''}${
									_second ? _second + '秒' : ''
								}`
							},
						},
						barWidth: '50%',
						barMaxWidth: 20,
						data: statisticsTaskTimeAvgOpt.value,
						itemStyle: {
							color: new echarts.graphic.LinearGradient(
								0,
								0,
								1,
								0,
								[
									{ offset: 0, color: '#83bff6' },
									{ offset: 0.5, color: '#188df0' },
									{ offset: 1, color: '#188df0' },
								]
							),
						},
						emphasis: {
							itemStyle: {
								color: new echarts.graphic.LinearGradient(
									0,
									0,
									1,
									0,
									[
										{ offset: 0, color: '#2378f7' },
										{ offset: 0.7, color: '#2378f7' },
										{ offset: 1, color: '#83bff6' },
									]
								),
							},
						},
					},
				],
			}
			optionTaskAverageTime &&
				myTaskAverageTimeChart.setOption(optionTaskAverageTime)

			window.addEventListener('resize', () => {
				myTaskHandleChart && myTaskHandleChart.resize()
				myTaskAverageTimeChart && myTaskAverageTimeChart.resize()
			})
		}

		// 获取流程分类
		// const categoryListLoading = ref<boolean>(false)
		// const categoryList = ref<ProcessCategoryModel[]>([])
		// const getProcessCategoryList = async () => {
		// 	categoryListLoading.value = true
		// 	let params: GetProcessCategoryListParamsModel = {
		// 		fileds: 'id,name',
		// 	}
		// 	const res: RequestResult<PaginationData<ProcessCategoryModel>> =
		// 		await getProcessCategoryListApi(params).finally(() => {
		// 			categoryListLoading.value = false
		// 		})
		// 	categoryList.value = JSON.parse(
		// 		JSON.stringify(res.data.records)
		// 			.replace(/id/g, 'value')
		// 			.replace(/name/g, 'label')
		// 	)
		// }

		// 查询按钮点击事件
		const onSearchClick = async () => {
			// 参数
			let params: GetInstanceStatisticsParamsModel = {
				name: searchParams.name,
				startTime: searchParams.startTime
					? searchParams.startTime + ' 00:00:00'
					: searchParams.startTime,
				endTime: searchParams.endTime
					? searchParams.endTime + ' 23:59:59'
					: searchParams.endTime,
			}

			// 任务数统计
			taskStatisticsNumLoading.value = true
			const resNums: RequestResult<StatisticsNumsModel> =
				await getTaskStatisticsNumApi(params).finally(() => {
					taskStatisticsNumLoading.value = false
				})
			taskStatisticsNumOpt.value = resNums.data

			// 办理任务数top10
			statisticsTaskHandleLoading.value = true
			const resListNums: RequestResult<StatisticsListNumsModel[]> =
				await getStatisticsTaskHandleApi(params).finally(() => {
					statisticsTaskHandleLoading.value = false
				})
			resListNums.data &&
				((statisticsTaskHandleOpt.value = resListNums.data.map(v => {
					return v.num?.toString()
				})),
				(statisticsTaskHandleOptDataYAxis.value = resListNums.data.map(
					v => {
						return v.name || ''
					}
				)))

			// 办理任务平均耗时top10
			statisticsTaskTimeAvgLoading.value = true
			const resAverageTime: RequestResult<StatisticsAverageTimeModel[]> =
				await getStatisticsTaskTimeAvgApi(params).finally(() => {
					statisticsTaskTimeAvgLoading.value = false
				})

			resAverageTime.data &&
				((statisticsTaskTimeAvgOpt.value = resAverageTime.data.map(
					v => {
						return v.ms // v.ms?.toString()
					}
				)),
				(statisticsTaskTimeAvgDataYAxis.value = resAverageTime.data.map(
					v => {
						return v.name || ''
					}
				)))
			initBarEcharts()
		}

		// 重置按钮点击事件
		const onResetClick = () => {
			searchParams.name = undefined
			searchParams.startTime = undefined
			searchParams.endTime = undefined
			timeValue.value = []
			// context.emit('handle-reset', params)
			onSearchClick()
		}

		// 时间参数获取
		const onTimeChange = (val: Moment[], dateString: string[]) => {
			timeValue.value = val
			searchParams.startTime = dateString[0]
			searchParams.endTime = dateString[1]
			onSearchClick()
		}

		watch(
			() => searchParams.name,
			() => {
				onSearchClick()
			}
		)

		onMounted(() => {
			// await getProcessCategoryList()
			onSearchClick()
		})

		return {
			searchParams,
			style,
			timeValue,
			getI18n,
			// onSearchClick,
			onResetClick,
			onTimeChange,

			echartsAverageTimeId,
			echartsLaunchClassificationId,

			taskStatisticsNumOpt,
			taskStatisticsNumLoading,
			statisticsTaskHandleLoading,
			statisticsTaskTimeAvgLoading,
		}
	},
})
</script>
