<template>
	<div class="quality-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-tabs v-model="state.queryParams.Source" @tab-change="handleQuery">
				<el-tab-pane
					:label="item.value"
					:name="item.key"
					v-for="item in qualitySourceOptions"
					:key="item.key"
					:disabled="state.loading"
				></el-tab-pane>
			</el-tabs>
			<el-form :model="state.queryParams" ref="ruleFormRef" inline @submit.native.prevent>
        <el-form-item label="工单标题" prop="Keyword">
          <el-input v-model="state.queryParams.Keyword" placeholder="工单标题" clearable @keyup.enter="handleQuery" class="keyword-input" />
        </el-form-item>
        <el-form-item label="工单编码" prop="No">
          <el-input v-model="state.queryParams.No" placeholder="工单编码" clearable @keyup.enter="handleQuery" class="keyword-input" />
        </el-form-item>
				<el-form-item label="创建时间" prop="crTime">
					<el-date-picker
						v-model="state.queryParams.crTime"
						type="datetimerange"
						unlink-panels
						range-separator="至"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						:shortcuts="shortcuts"
						@change="handleQuery"
						value-format="YYYY-MM-DD[T]HH:mm:ss"
						:default-time="defaultTimeStartEnd"
					/>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
					<el-button @click="resetQuery(ruleFormRef)" v-waves class="default-button"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
				</el-form-item>
			</el-form>
			<vxe-toolbar
				ref="toolbarRef"
				:loading="state.loading"
				custom
				:refresh="{
					queryMethod: handleQuery,
				}"
			>
				<template #buttons>
					<el-button
						type="primary"
						@click="onTransfer"
						:loading="state.loading"
						v-auth="'quality:index:transfer'"
						:disabled="isChecked"
						v-if="state.queryParams.Source === 1"
					>
						录音转写<span v-if="checkTable.length">({{ checkTable.length }})</span>
					</el-button>
					<el-button type="primary" @click="onExport" :loading="state.loading" v-auth="'quality:index:export'" :disabled="isChecked">
						导出质检结果<span v-if="checkTable.length">({{ checkTable.length }})</span>
					</el-button>
				</template>
			</vxe-toolbar>
			<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
				<vxe-table
					border
					:loading="state.loading"
					:data="state.tableData"
					:column-config="{ resizable: true }"
					:row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
					ref="tableRef"
					height="auto"
					auto-resize
					show-overflow
					:scrollY="{ enabled: true, gt: 100 }"
					id="qualityIndex"
					:custom-config="{ storage: true }"
					@checkbox-all="selectAllChangeEvent"
					@checkbox-change="selectChangeEvent"
				>
					<vxe-column type="checkbox" width="50" align="center"></vxe-column>
					<vxe-column field="order.no" title="工单编码" width="140"></vxe-column>
					<vxe-column field="order.title" title="工单标题" min-width="200">
						<template #default="{ row }">
							<order-detail :order="row.order" @updateList="queryList">{{ row.order.title }}</order-detail>
						</template>
					</vxe-column>
					<vxe-column field="transferStateText" title="转写状态" width="100" v-if="state.queryParams.Source === 1">
						<template #default="{ row }">
							<el-text v-if="row.transferState === 0" type="info">{{ row.transferStateText }}</el-text>
							<el-text v-if="row.transferState === 1" type="primary">{{ row.transferStateText }}</el-text>
							<el-text v-if="row.transferState === 2" type="success">{{ row.transferStateText }}</el-text>
							<el-text v-if="row.transferState === 3" type="danger">{{ row.transferStateText }}</el-text>
						</template>
					</vxe-column>
					<vxe-column field="aiQuality" title="质检方式" width="100">
						<template #default="{ row }">
							{{ row.aiQuality ? '智能质检' : '人工质检' }}
						</template>
					</vxe-column>
					<vxe-column field="order.sourceChannel" title="来源渠道" width="110"></vxe-column>
					<vxe-column field="order.creationTime" title="受理时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.order?.creationTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<template v-if="state.queryParams.Source === 2">
						<vxe-column field="order.centerToOrgTime" title="交办时间" width="160">
							<template #default="{ row }">
								{{ formatDate(row.order.centerToOrgTime, 'YYYY-mm-dd HH:MM:SS') }}
							</template>
						</vxe-column>
					</template>
					<template v-if="state.queryParams.Source === 3">
						<vxe-column field="visit.visitStateText" title="回访状态" width="110"></vxe-column>
						<vxe-column field="visit.visitTypeText" title="回访方式" width="110"></vxe-column>
						<vxe-column field="order.filedTime" title="办结时间" width="160">
							<template #default="{ row }">
								{{ formatDate(row.order?.filedTime, 'YYYY-mm-dd HH:MM:SS') }}
							</template>
						</vxe-column>
						<vxe-column field="visit.publishTime" title="发布时间" width="160">
							<template #default="{ row }">
								{{ formatDate(row.visit?.publishTime, 'YYYY-mm-dd HH:MM:SS') }}
							</template>
						</vxe-column>
						<vxe-column field="visit.creationTime" title="回访任务创建时间" width="160">
							<template #default="{ row }">
								{{ formatDate(row.visit?.creationTime, 'YYYY-mm-dd HH:MM:SS') }}
							</template>
						</vxe-column>
						<vxe-column field="visit.employeeName" title="回访人" width="120"></vxe-column>
						<vxe-column field="visit.visitTime" title="回访时间" width="160">
							<template #default="{ row }">
								{{ formatDate(row.visit?.visitTime, 'YYYY-mm-dd HH:MM:SS') }}
							</template>
						</vxe-column>
						<vxe-column field="order.counterSignTypeText" title="是否会签" width="100"></vxe-column>
					</template>
					<vxe-column field="order.statusText" title="工单状态" width="100">
						<template #default="{ row }">
							<el-text type="danger" tag="b" v-if="[1, 2, 3, 9, 101, 102, 103, 104, 105, 200].includes(row.order?.status)">{{
								row.order?.statusText
							}}</el-text>
							<span v-else>{{ row.order?.statusText }}</span>
						</template>
					</vxe-column>
					<vxe-column field="order.acceptType" title="受理类型" width="100"></vxe-column>
					<vxe-column field="order.hotspotName" title="热点分类" width="150"></vxe-column>
					<vxe-column field="order.acceptorName" title="受理人" width="120"></vxe-column>
					<vxe-column field="order.fromPhone" title="来电电话" width="140"></vxe-column>
					<vxe-column title="操作" fixed="right" width="90" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onQualityInspection(row)" v-auth="'quality:inspection'" title="质检"> 质检 </el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
			<pagination
				@pagination="queryList"
				:total="state.total"
				v-model:current-page="state.queryParams.PageIndex"
				v-model:page-size="state.queryParams.PageSize"
				:disabled="state.loading"
			/>
		</div>
		<!-- 质检 -->
		<z-g-quality ref="qualityInspectionRef" @updateList="queryList" />
	</div>
</template>

<script lang="tsx" setup name="qualityIndex">
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { qualityBaseData, qualityList, qualityRecordTransfer } from '@/api/quality';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import Other from '@/utils/other';
import { exportQuality } from '@/utils/tools';

// 引入组件
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情
const ZGQuality = defineAsyncComponent(() => import('@/views/quality/index/components/ZG-quality.vue')); // 质检
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页

// 定义变量内容
const state = reactive<any>({
	loading: false, // 加载状态
	queryParams: {
		// 查询参数
		PageIndex: 1,
		PageSize: 20,
		Source: 1, // 受理待质检
		crTime: [], // 创建时间
		CreationTimeStart: null, // 创建时间 开始
		CreationTimeEnd: null, // 创建时间 结束
		State: 0, // 待质检
		Keyword: null,
    No:null
	},
	total: 0, // 总条数
	tableData: [], // 表格数据
});
const ruleFormRef = ref<RefType>(null); // 表单ref
const qualitySourceOptions = ref<EmptyArrayType>([]); // 违禁词分类
const qualityStateOptions = ref<EmptyArrayType>([]); // 违禁词属性
const getBaseData = async () => {
	try {
		const res = await qualityBaseData();
		qualitySourceOptions.value = res.result?.qualitySource ?? [];
		qualityStateOptions.value = res.result?.qualityState ?? [];
	} catch (error) {
		console.log(error);
	}
};
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
// 查询质检列表
const requestParams = ref<EmptyObjectType>({});
const queryList = () => {
	state.loading = true;
	requestParams.value = Other.deepClone(state.queryParams);
	requestParams.value.CreationTimeStart = state.queryParams.crTime === null ? null : state.queryParams.crTime[0]; // 创建时间
	requestParams.value.CreationTimeEnd = state.queryParams.crTime === null ? null : state.queryParams.crTime[1];
	Reflect.deleteProperty(requestParams.value, 'crTime'); // 删除无用的参数
	qualityList(requestParams.value)
		.then((res) => {
			state.loading = false;
			state.tableData = res.result.items ?? [];
			state.total = res.result.total ?? 0;
			tableRef.value?.clearCheckboxRow();
			checkTable.value = [];
		})
		.finally(() => {
			state.loading = false;
			tableRef.value?.clearCheckboxRow();
			checkTable.value = [];
		});
};
// 重置表单
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	state.queryParams.CreationTimeStart = null;
	state.queryParams.CreationTimeEnd = null;
	queryList();
};
// 质检
const qualityInspectionRef = ref<RefType>();
const onQualityInspection = (row: any) => {
	qualityInspectionRef.value.openDialog(row, state.queryParams.Source);
};
// 页面加载时
const toolbarRef = ref<RefType>();
const checkTable = ref<EmptyArrayType>([]);
const selectAllChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '所有勾选事件' : '所有取消事件', records);
	}
};

const selectChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '勾选事件' : '取消事件', records);
	}
};
const isChecked = computed(() => {
	return !checkTable.value.length;
});
const tableRef = ref<RefType>();
// 录音转写
const onTransfer = () => {
	const ids = checkTable.value.map((item) => {
		return { id: item.id };
	});
	ElMessageBox.confirm(`您确定要选中的质检转写录音，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			qualityRecordTransfer(ids)
				.then(() => {
					ElMessage.success('转写任务创建成功');
					handleQuery();
				})
				.catch((err) => {});
		})
		.catch(() => {});
};
// 质检单导出
const onExport = () => {
	const ids = checkTable.value.map((item) => item.id);
	exportQuality(ids);
};
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
	getBaseData();
});
</script>
