// 首页 左
<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_ProcessClassification'
							)
						}}</label>
						<a-select
							style="width: 100%"
							v-model:value="searchParams.category"
							:allowClear="true"
							:loading="categoryListLoading"
							:options="categoryList"
							@change="onSelectChange"
							:placeholder="
								getI18n('common', 'Common_Please_Select', [
									getI18n(
										'system',
										'SYSTEM_Process_Category'
									),
								])
							"
						/>
					</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>
		<!-- 卡片 echartsLoading -->
		<a-row>
			<!-- 发起数 -->
			<a-col :span="8">
				<statistic-card-wrapper
					:class="style['card-wrapper-s']"
					:is-loading="instanceStatisticsNumLoading"
					:card-label="
						getI18n('system', 'SYSTEM_Home_InitiatorsNumber')
					"
					:card-value="instanceStatisticsNumOpt?.startNum"
				/>
			</a-col>
			<!-- 流转中 -->
			<a-col :span="8">
				<statistic-card-wrapper
					:class="style['card-wrapper-i']"
					:is-loading="instanceStatisticsNumLoading"
					:card-label="getI18n('system', 'SYSTEM_Home_InCirculation')"
					:card-value="instanceStatisticsNumOpt?.handleNum"
				/>
			</a-col>
			<!-- 已结束 -->
			<a-col :span="8">
				<statistic-card-wrapper
					:class="style['card-wrapper-e']"
					:is-loading="instanceStatisticsNumLoading"
					:card-label="getI18n('system', 'SYSTEM_Home_Finished')"
					:card-value="instanceStatisticsNumOpt?.endNum"
				/>
			</a-col>
		</a-row>
		<!-- echarts  echartsLoading -->
		<!-- 流程发起Top10 -->
		<div :class="style['title']">
			{{ getI18n('system', 'SYSTEM_Home_ProcessLaunchTop') }}
		</div>
		<echarts-wrapper
			:is-loading="categoryListLoading"
			:echarts-id="echartsLaunchId"
		/>
		<!-- 流程平均耗时Top10 -->
		<div :class="style['title']">
			{{ getI18n('system', 'SYSTEM_Home_ProcessAverageTime') }}
		</div>
		<echarts-wrapper
			:is-loading="categoryListLoading"
			:echarts-id="echartsAverageTimeId"
		/>
		<!-- 流程发起分类 -->
		<div :class="style['title']">
			{{ getI18n('system', 'SYSTEM_Home_ProcessLaunchClassification') }}
		</div>
		<echarts-wrapper
			:is-loading="categoryListLoading"
			:echarts-id="echartsLaunchClassificationId"
		/>
	</a-card>
</template>

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

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

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

import { ProcessCategoryModel } from '@/types/process'
import { getProcessCategoryListApi } from '@/api/process-category'
import { GetProcessCategoryListParamsModel } from '@/api/process-category/model'

import {
	StatisticsAverageTimeModel,
	StatisticsListNumsModel,
	StatisticsNumsModel,
	StatisticsCategoryModel,
} from '@/types/process'

import {
	getInstanceStatisticsNumApi,
	getStatisticsInstanceLanchApi,
	getStatisticsInstanceTimeAvgApi,
	getStatisticsInstanceCategoryApi,
} 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: ['handle-search', 'handle-reset'],
	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 instanceStatisticsNumLoading = ref<boolean>(false)
		const instanceStatisticsNumOpt = ref<StatisticsNumsModel>()

		// 流程发起top10
		const statisticsInstanceLanchLoading = ref<boolean>(false)
		const statisticsInstanceLanchOpt = ref<number[]>()
		const statisticsInstanceLanchDataYAxis = ref<string[]>()

		// 流程平均耗时top10
		const statisticsInstanceTimeAvgLoading = ref<boolean>(false)
		const statisticsInstanceTimeAvgOpt = ref<number[]>()
		const statisticsInstanceTimeAvgDataYAxis = ref<string[]>()

		// 流程发起分类统计
		const statisticsInstanceCategoryLoading = ref<boolean>(false)
		const statisticsInstanceCategoryOpt = ref()
		// ref<{ value: number|null; name: string }[]>

		// 流程发起Top10
		const echartsLaunchId = ref<string>(
			getI18n('system', 'SYSTEM_Home_ProcessLaunchTopId')
		)
		// 流程平均耗时Top10
		const echartsAverageTimeId = ref<string>(
			getI18n('system', 'SYSTEM_Home_ProcessAverageTimeId')
		)
		// 流程发起分类
		const echartsLaunchClassificationId = ref<string>(
			getI18n('system', 'SYSTEM_Home_ProcessLaunchClassificationId')
		)

		const initBarEcharts = () => {
			// 流程发起Top10
			const chartProcessLaunchTopDom = document.getElementById(
				getI18n('system', 'SYSTEM_Home_ProcessLaunchTopId')
			)!
			if (chartProcessLaunchTopDom != null) {
				echarts.dispose(chartProcessLaunchTopDom)
			}
			const myProcessLaunchTopChart = echarts.init(
				chartProcessLaunchTopDom
			)

			const optionProcessLaunchTop: echarts.EChartsOption = {
				xAxis: {
					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: statisticsInstanceLanchDataYAxis.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_ProcessLaunchTop'),
						type: 'bar',
						label: {
							show: true,
							position: 'top',
						},
						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' },
									]
								),
							},
						},
						barWidth: '30%',
						barMaxWidth: 20,
						data: statisticsInstanceLanchOpt.value,
					},
				],
			}
			optionProcessLaunchTop &&
				myProcessLaunchTopChart.setOption(optionProcessLaunchTop)

			// 流程平均耗时Top10
			const chartProcessAverageTimeDom = document.getElementById(
				getI18n('system', 'SYSTEM_Home_ProcessAverageTimeId')
			)!
			if (chartProcessAverageTimeDom != null) {
				echarts.dispose(chartProcessAverageTimeDom)
			}
			const myProcessAverageTimeChart = echarts.init(
				chartProcessAverageTimeDom
			)

			const optionProcessAverageTime: 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
						},
					},
					nameLocation: 'end',
					data: statisticsInstanceTimeAvgDataYAxis.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_ProcessAverageTime'
						),
						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: statisticsInstanceTimeAvgOpt.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' },
									]
								),
							},
						},
					},
				],
			}
			optionProcessAverageTime &&
				myProcessAverageTimeChart.setOption(optionProcessAverageTime)

			// 流程发起分类
			const chartLaunchClassificationDom = document.getElementById(
				getI18n('system', 'SYSTEM_Home_ProcessLaunchClassificationId')
			)!
			if (chartLaunchClassificationDom != null) {
				echarts.dispose(chartLaunchClassificationDom)
			}
			const myLaunchClassificationChart = echarts.init(
				chartLaunchClassificationDom
			)
			const optionLaunchClassification: echarts.EChartsOption = {
				legend: {
					left: '10%',
					type: 'scroll',
					orient: 'vertical',
					top: 20,
					bottom: 20,
				},
				tooltip: {
					trigger: 'item',
					formatter: '{b} {c}次 {d}%', // {a} <br/>
				},
				avoidLabelOverlap: true,
				showEmptyCircle: true,
				series: [
					{
						name: getI18n(
							'system',
							'SYSTEM_Home_ProcessLaunchClassification'
						),
						type: 'pie',
						emptyCircleStyle: {
							color: '#eee',
						},
						radius: '70%',
						center: ['60%', '60%'],
						labelLine: {
							show: true,
							lineStyle: {
								width: 2,
							},
						},
						data: statisticsInstanceCategoryOpt.value,
					},
				],
			}
			optionLaunchClassification &&
				myLaunchClassificationChart.setOption(
					optionLaunchClassification
				)

			window.addEventListener('resize', () => {
				myProcessLaunchTopChart && myProcessLaunchTopChart.resize()
				myProcessAverageTimeChart && myProcessAverageTimeChart.resize()
				myLaunchClassificationChart &&
					myLaunchClassificationChart.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 = {
				category: searchParams.category,
				startTime: searchParams.startTime
					? searchParams.startTime + ' 00:00:00'
					: searchParams.startTime,
				endTime: searchParams.endTime
					? searchParams.endTime + ' 23:59:59'
					: searchParams.endTime,
			}

			// 发起实例统计
			instanceStatisticsNumLoading.value = true
			const resNums: RequestResult<StatisticsNumsModel> =
				await getInstanceStatisticsNumApi(params).finally(() => {
					instanceStatisticsNumLoading.value = false
				})
			instanceStatisticsNumOpt.value = resNums.data

			// 流程发起top10
			statisticsInstanceLanchLoading.value = true
			const resListNums: RequestResult<StatisticsListNumsModel[]> =
				await getStatisticsInstanceLanchApi(params).finally(() => {
					statisticsInstanceLanchLoading.value = false
				})
			resListNums.data &&
				((statisticsInstanceLanchOpt.value = resListNums.data.map(v => {
					return v.num
				})),
				(statisticsInstanceLanchDataYAxis.value = resListNums.data.map(
					v => {
						return v.name || ''
					}
				)))

			// 流程平均耗时top10
			statisticsInstanceTimeAvgLoading.value = true
			const resAverageTime: RequestResult<StatisticsAverageTimeModel[]> =
				await getStatisticsInstanceTimeAvgApi(params).finally(() => {
					statisticsInstanceTimeAvgLoading.value = false
				})
			resAverageTime.data &&
				((statisticsInstanceTimeAvgOpt.value = resAverageTime.data.map(
					v => {
						return v.ms
					}
				)),
				(statisticsInstanceTimeAvgDataYAxis.value =
					resAverageTime.data.map(v => {
						return v.name || ''
					})))

			// 流程发起分类统计
			statisticsInstanceCategoryLoading.value = true
			const resCategory: RequestResult<StatisticsCategoryModel[]> =
				await getStatisticsInstanceCategoryApi(params).finally(() => {
					statisticsInstanceCategoryLoading.value = false
				})
			resCategory.data &&
				(statisticsInstanceCategoryOpt.value = resCategory.data.map(
					v => {
						return {
							value: v.num || null,
							name: v.category,
						}
					}
				))

			initBarEcharts()
		}

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

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

		// 流程分类
		const onSelectChange = (val: string) => {
			searchParams.category = val
			onSearchClick()
		}

		// 初始化
		onMounted(() => {
			getProcessCategoryList()
			onSearchClick()
		})

		return {
			searchParams,
			style,
			timeValue,
			getI18n,
			onResetClick,
			onTimeChange,
			onSelectChange,
			categoryList,
			categoryListLoading,
			// echartsLoading,
			echartsLaunchId,
			echartsAverageTimeId,
			echartsLaunchClassificationId,
			instanceStatisticsNumLoading,
			instanceStatisticsNumOpt,
			statisticsInstanceLanchLoading,
			statisticsInstanceTimeAvgLoading,
			statisticsInstanceCategoryLoading,
		}
	},
})
</script>
