<template>
	<el-dialog
		v-model="state.dialogVisible"
		width="60%"
		draggable
		title="新增智能回访任务"
		@close="close"
		append-to-body
		destroy-on-close
		@opened="opened"
	>
		<el-divider content-position="left" class="mb30">
			<el-text tag="b" size="large"> 回访任务内容 </el-text>
		</el-divider>
		<el-form :model="state.ruleForm" label-width="90px" ref="ruleFormRef" v-loading="state.loading">
			<el-row :gutter="10">
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="任务名称" prop="name" :rules="[{ required: true, message: '请填写任务名称', trigger: 'blur' }]">
						<el-input v-model="state.ruleForm.name" placeholder="请填写任务名称" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="时间段" prop="crTime" :rules="[{ required: true, message: '请选择时间段', trigger: 'change' }]">
						<el-date-picker
							v-model="state.ruleForm.crTime"
							type="datetimerange"
							unlink-panels
							range-separator="至"
							start-placeholder="开始时间"
							end-placeholder="结束时间"
							:shortcuts="shortcuts"
							value-format="YYYY-MM-DD[T]HH:mm:ss"
							:default-time="defaultTimeStartEnd"
						/>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="节日禁呼" prop="festivalBan" :rules="[{ required: true, message: '请选择节日禁呼', trigger: 'change' }]">
						<el-radio-group v-model="state.ruleForm.festivalBan">
							<el-radio :value="1">是</el-radio>
							<el-radio :value="0">否</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<el-divider content-position="left" class="mb30">
			<el-text tag="b" size="large"> 回访任务名单 </el-text>
		</el-divider>
		<el-form :model="state.queryParams" ref="queryFormRef" @submit.native.prevent>
			<el-row :gutter="20">
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="8">
					<el-form-item label="工单标题" prop="Title">
						<el-input v-model="state.queryParams.Title" placeholder="工单标题" clearable @keyup.enter="queryList" />
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="8">
					<el-form-item label="工单编码" prop="No">
						<el-input v-model="state.queryParams.No" placeholder="工单编码" clearable @keyup.enter="queryList" />
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="8">
					<el-form-item label="受理类型" prop="AcceptType">
						<el-select v-model="state.queryParams.AcceptType" placeholder="请选择受理类型" clearable class="w100" @change="queryList">
							<el-option v-for="item in state.acceptTypeOptions" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="8">
					<el-form-item label="热点分类" prop="Hotspot">
						<el-input v-model="state.queryParams.Hotspot" placeholder="热点分类名称" clearable @keyup.enter="queryList" />
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="8">
					<el-form-item>
						<el-button type="primary" @click="queryList" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
						<el-button @click="resetQuery(queryFormRef)" class="default-button" :loading="state.loading">
							<SvgIcon name="ele-Refresh" class="mr5" />重置
						</el-button>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<vxe-toolbar
			ref="toolbarRef"
			:loading="state.loading"
			custom
			:refresh="{
				queryMethod: queryList,
			}"
		>
		</vxe-toolbar>
		<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"
			@checkbox-all="selectAllChangeEvent"
			@checkbox-change="selectChangeEvent"
			show-overflow
			:scrollY="{ enabled: true, gt: 100 }"
			id="smartVisitAdd"
			:custom-config="{ storage: true }"
			max-height="300px"
		>
			<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="工单标题" width="200">
				<template #default="{ row }">
					<order-detail :order="row.order" @updateList="queryList">{{ row.order?.title }}</order-detail>
				</template>
			</vxe-column>
			<vxe-column field="order.sourceChannel" title="来源渠道" width="110"></vxe-column>
			<vxe-column field="visitStateText" title="回访状态" width="110"></vxe-column>
			<vxe-column field="order.acceptType" title="受理类型" width="110"></vxe-column>
			<vxe-column field="order.hotspotName" title="热点分类" width="150"></vxe-column>
			<vxe-column field="order.currentStepName" title="当前节点" width="110"></vxe-column>
			<vxe-column field="order.acceptorName" title="受理人" width="120"></vxe-column>
			<vxe-column field="order.orgLevelOneName" title="一级部门" width="140"></vxe-column>
			<vxe-column field="order.actualHandleOrgName" title="接办部门" width="140"></vxe-column>
			<vxe-column field="order.startTime" title="受理时间" width="160">
				<template #default="{ row }">
					{{ formatDate(row.order?.creationTime, 'YYYY-mm-dd HH:MM:SS') }}
				</template>
			</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="publishTime" title="发布时间" width="160">
				<template #default="{ row }">
					{{ formatDate(row.publishTime, 'YYYY-mm-dd HH:MM:SS') }}
				</template>
			</vxe-column>
			<vxe-column field="employeeName" title="回访人" width="120"></vxe-column>
		</vxe-table>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="state.dialogVisible = false" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading" :disabled="!isChecked">确 定</el-button>
			</span>
		</template>
	</el-dialog>
</template>
<script setup lang="tsx">
import { formatDate } from '@/utils/formatTime';
import { ElMessage, FormInstance } from 'element-plus';
import { reactive, ref, defineAsyncComponent, computed, onMounted } from 'vue';
import { getSmartVisitRecord } from '@/api/smartVisit';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import { smartVisitAdd, smartVisitBaseData } from '@/api/smartVisit';

const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情
const emit = defineEmits(['updateList']);
const state = reactive({
	queryParams: {
		Title: null,
		No: null,
		AcceptType: null,
		Hotspot: null,
	},
	tableData: [], //表格
	loading: false, // 加载
	dialogVisible: false, // 弹窗
	ruleForm: {
		name: '',
		crTime: [],
		festivalBan: 1,
	}, // 表单数据
	acceptTypeOptions: [],
});
const isChecked = computed(() => {
	return Boolean(checkTable.value.length);
});
// 基础信息
const getBaseData = async () => {
	const acceptTypeOptions = await smartVisitBaseData();
	state.acceptTypeOptions = acceptTypeOptions.result?.acceptTypeOptions;
};
// 打开弹窗
const openDialog = () => {
	state.dialogVisible = true;
	getBaseData();
	queryList();
};
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
};
// 获取所有工单列表
const queryList = async () => {
	state.loading = true;
	try {
		const { result } = await getSmartVisitRecord(state.queryParams);
		state.tableData = result;
		state.loading = false;
	} catch (e) {
		console.log(e);
		state.loading = false;
	}
};
// 重置所有工单列表
const queryFormRef = ref<RefType>();
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
};
// 保存
const ruleFormRef = ref<RefType>();
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		const request = {
			name: state.ruleForm.name,
			beginTime: state.ruleForm.crTime[0],
			endTime: state.ruleForm.crTime[1],
			festivalBan: state.ruleForm.festivalBan,
			aiOrderVisitDetails: checkTable.value.map((item: any) => {
				return {
					orderId: item.order?.id,
					orderVisitId: item.id,
					outerNo: item.order?.contact,
				};
			}),
		};
		smartVisitAdd(request)
			.then(() => {
				state.loading = false;
				state.dialogVisible = false;
				ElMessage.success('操作成功');
				emit('updateList');
			})
			.catch(() => {
				state.loading = false;
			});
	});
};
const tableRef = 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 toolbarRef = ref<RefType>();
const opened = () => {
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
};
defineExpose({
	openDialog,
});
</script>
