<template>
	<div class="quality-seats-container layout-pd">
		<el-row :gutter="10">
			<el-col class="mb10">
				<el-card shadow="never">
					<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent inline>
						<el-form-item prop="crTime">
							<statistical-time v-model="state.queryParams.crTime" @change="handleQuery" ref="statisticalTimeRef" :disabled="gridOptions.loading" />
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="handleQuery" :loading="gridOptions.loading">
								<SvgIcon name="ele-Search" class="mr5" />查询
							</el-button>
							<el-button @click="resetQuery(ruleFormRef)" class="default-button" :loading="gridOptions.loading">
								<SvgIcon name="ele-Refresh" class="mr5" />重置
							</el-button>
						</el-form-item>
					</el-form>
				</el-card>
			</el-col>
			<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" class="mb10">
				<el-card shadow="never" style="height: 400px">
					<vxe-grid v-bind="gridOptions" v-on="gridEvents" ref="gridRef">
						<template #toolbar_buttons>
							<h3>质检工单概览</h3>
						</template>
					</vxe-grid>
				</el-card>
			</el-col>
			<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" class="mb10">
				<el-card shadow="never" style="height: 400px">
					<div class="flex-center-between">
						<h3></h3>
						<div>
							<el-select-v2
								v-model="AcceptorId"
								filterable
								:options="seatUser"
								:props="{
									label: 'value',
									value: 'key',
								}"
								placeholder="请选择坐席"
								clearable
								@change="getSeatsData"
								style="width: 240px"
							/>
						</div>
					</div>
					<v-chart :option="option" :loading="seatsLoading" autoresize style="height: 320px" />
				</el-card>
			</el-col>
			<el-col>
				<el-card shadow="never" style="height: 400px">
					<div class="flex-center-between">
						<h3></h3>
						<div class="flex">
							<el-button @click="getYearData" round circle :disabled="yearLoading" title="刷新"> <SvgIcon name="ele-Refresh" /> </el-button>
							<input-number-range v-model="state.queryParams.value" @change="getYearData" />
							<el-select-v2
								v-model="AcceptorId1"
								filterable
								:options="seatUser"
								:props="{
									label: 'value',
									value: 'key',
								}"
								placeholder="请选择坐席"
								clearable
								@change="getYearData"
								style="width: 240px"
							/>
						</div>
					</div>
					<v-chart :option="option1" :loading="yearLoading" autoresize style="height: 320px" />
				</el-card>
			</el-col>
		</el-row>
	</div>
</template>
<script setup lang="tsx" name="qualityWork">
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { FormInstance } from 'element-plus';
import { defaultDate } from '@/utils/constants';
import Other from '@/utils/other';
import { qualityOverview, qualityOverviewExport, qualityScore, qualityScoreBase, qualityScoreGrade } from '@/api/quality';

const StatisticalTime = defineAsyncComponent(() => import('@/components/StatisticalTime/index.vue')); // 日期类型选择组件
const InputNumberRange = defineAsyncComponent(() => import('@/components/NumberRange/index.vue')); // 数字区间

// 定义变量内容
const state = reactive<any>({
	queryParams: {
		// 查询条件
		crTime: defaultDate,
		SortField: null,
		SortRule: null,
		value: [0, 100],
		AcceptorId: null,
	},
	loading: false, // 加载
	total: 0, // 总数
});
const requestParams = ref<EmptyObjectType>({});
const gridOptions = reactive<any>({
	loading: false,
	border: true,
	showOverflow: true,
	columnConfig: {
		resizable: true,
	},
	scrollY: {
		enabled: true,
		gt: 100,
	},
	toolbarConfig: {
		zoom: true,
		custom: true,
		refresh: {
			queryMethod: () => {
				handleQuery();
			},
		},
		tools: [{ toolRender: { name: 'exportAll' } }],
		slots: {
			buttons: 'toolbar_buttons',
		},
	},
	customConfig: {
		storage: true,
	},
	height: 360,
	id: 'qualityWork',
	rowConfig: { isHover: true, height: 30, isCurrent: true, useKey: true },
	columns: [
		{ field: 'qualityItem', title: '质检项' },
		{ field: 'orderNum', title: '质检工单数', sortable: true },
		{ field: 'rate', title: '占比' },
	],
	data: [],
	params: {
		exportMethod: qualityOverviewExport,
		exportParams: requestParams,
	},
	sortConfig: {
		remote: true,
	},
});
/** 搜索按钮操作 */
const handleQuery = () => {
	queryList();
	getSeatsData();
};
/** 获取列表 */
const queryList = async () => {
	gridOptions.loading = true;
	requestParams.value = Other.deepClone(state.queryParams);
	requestParams.value.StartTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[0];
	requestParams.value.EndTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[1];
	Reflect.deleteProperty(requestParams.value, 'crTime');
	Reflect.deleteProperty(requestParams.value, 'value');
	try {
		const { result } = await qualityOverview(requestParams.value);
		gridOptions.data = result ?? [];
		gridOptions.loading = false;
	} catch (e) {
		gridOptions.loading = false;
		console.log(e);
	}
};
const gridEvents = {
	sortChange(val: any) {
		state.queryParams.SortField = val.order ? val.field : null;
		// 0 升序 1 降序
		state.queryParams.SortRule = val.order ? (val.order == 'desc' ? 1 : 0) : null;
		queryList();
	},
};
// 获取坐席质检分值分析
const seatsLoading = ref(false);
const AcceptorId = ref<string | number | null>(null);
const getSeatsData = async () => {
	seatsLoading.value = true;
	try {
		const { result } = await qualityScore({ ...requestParams.value, AcceptorId: AcceptorId.value });
		const legendData = ['90-100分', '80-90分', '70-80分', '60-70分', '60分以下'];
		const data = [
			{
				value: result.ninetyGrade,
				name: '90-100分',
			},
			{
				value: result.eightyGrade,
				name: '80-90分',
			},
			{
				value: result.seventyGrade,
				name: '70-80分',
			},
			{
				value: result.sixtyGrade,
				name: '60-70分',
			},
			{
				value: result.fiftyGrade,
				name: '60分以下',
			},
		];
		setOption(legendData, data);
		seatsLoading.value = false;
	} catch (e) {
		console.log(e);
		seatsLoading.value = false;
	}
};
const option = ref<any>({});
// 坐席质检分值分析
const setOption = (legendData: string[], data: any) => {
	option.value = {
		title: {
			text: '坐席质检分值分析',
			left: '0',
		},
		tooltip: {
			formatter: '{b0}: {c0} ({d}%)',
		},
		toolbox: {
			show: true,
			orient: 'horizontal',
			showTitle: true,
			feature: {
				saveAsImage: {
					type: 'png',
					show: true,
					title: '保存为图片',
				},
			},
		},
		legend: [
			{
				top: '20%',
				right: '20',
				orient: 'vertical',
				data: legendData,
			},
		],
		series: [
			{
				type: 'pie',
				radius: ['0%', '80%'],
				// roseType: 'area',
				label: {
					show: true,
					overflow: 'none',
					formatter: function (params: any) {
						if (params.name !== '') {
							return `${params.name}:${params.data.value}（${params.percent}%）`;
						}
					},
				},
				data: data,
			},
		],
	};
};

const AcceptorId1 = ref<string | number | null>(null);
const yearLoading = ref(false);
// 获取近一年质检分值分析
const getYearData = async () => {
	yearLoading.value = true;
	try {
		const { result } = await qualityScoreGrade({
			...requestParams.value,
			AcceptorId: AcceptorId1.value,
			MinGrade: state.queryParams.value[0],
			MaxGrade: state.queryParams.value[1],
		});
		const xData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
		const data = result.map((item: any) => item.num);
		// const data = [1,2,45,213,45,65,7,8,1,23]
		setOption1(data, xData);
		yearLoading.value = false;
	} catch (e) {
		console.log(e);
		yearLoading.value = false;
	}
};
const option1 = ref<any>({});
// 近一年质检分值分析
const setOption1 = (data: any, xData: any) => {
	option1.value = {
		title: {
			text: '近一年质检分值分析',
			left: '0',
		},
		legend: {
			show: false,
		},
		tooltip: {
			show: true,
			trigger: 'item',
		},
		grid: {
			top: '20%',
			left: '5%',
			right: '1%',
			bottom: '12%',
		},
		toolbox: {
			show: true,
			// top: '20%',
			orient: 'horizontal',
			showTitle: true,
			feature: {
				saveAsImage: {
					type: 'png',
					show: true,
					title: '保存为图片',
				},
			},
		},
		xAxis: [
			{
				type: 'category',
				data: xData,
				axisTick: {
					show: false, // 是否显示坐标轴轴线
				},
				axisLabel: {
					color: '#000',
					fontSize: 14,
				},
				splitLine: {
					show: false,
				},
				boundaryGap: true,
				axisLine: {
					//坐标轴轴线相关设置。
					show: true,
					inside: false,
				},
			},
		],
		yAxis: [
			{
				type: 'value',
				name: '单位：件',
				nameGap: 15,
				nameTextStyle: {
					fontSize: 14,
					color: '#aaa',
					align: 'center',
					padding: [10, 0, 0, -5],
				},
				axisLabel: {
					//坐标轴刻度标签的相关设置。
					show: true,
				},
				axisLine: {
					show: true,
				},
				axisTick: {
					show: false,
				},
				splitLine: {
					show: true,
				},
				show: true,
			},
		],
		series: [
			{
				name: '',
				type: 'bar',
				barMaxWidth: 30,
				data: data,
				itemStyle: {
					color: {
						type: 'linear',
						x: 0,
						y: 0,
						x2: 0,
						y2: 1,
						colorStops: [
							{
								offset: 0,
								color: 'rgba(31, 129, 255, 1)',
							},
							{
								offset: 1,
								color: 'rgba(31, 134, 255, .5)',
							},
						],
					},
				},
				label: {
					show: true,
					position: 'top',
					fontSize: 14,
					color: '#333',
				},
			},
			{
				name: '',
				type: 'line',
				barMaxWidth: 30,
				data: data,
				itemStyle: {
					color: {
						type: 'linear',
						x: 0,
						y: 0,
						x2: 0,
						y2: 1,
						colorStops: [
							{
								offset: 0,
								color: 'rgba(31, 129, 255, 1)',
							},
							{
								offset: 1,
								color: 'rgba(31, 134, 255, .5)',
							},
						],
					},
				},
			},
		],
	};
};
const ruleFormRef = ref<RefType>();
/** 重置按钮操作 */
const statisticalTimeRef = ref<RefType>();
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	AcceptorId.value = null;
	statisticalTimeRef.value.reset();
	queryList();
	getSeatsData();
	getYearData();
};
// 获取基础信息
const seatUser = ref<EmptyArrayType>([]);
const getBaseData = async () => {
	try {
		const { result } = await qualityScoreBase();
		seatUser.value = result.seats ?? [];
	} catch (e) {
		console.log(e);
	}
};
onMounted(() => {
	queryList();
	getSeatsData();
	getYearData();
	getBaseData();
});
</script>
