<template>
	<div class="business-visit-smart-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-form :model="state.queryParams" ref="ruleFormRef" inline @submit.native.prevent>
				<el-form-item label="任务名称" prop="Keyword">
					<el-input v-model.trim="state.queryParams.Keyword" placeholder="回访任务名称" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item label="任务状态" prop="AiOrderVisitTaskState">
					<el-select v-model="state.queryParams.AiOrderVisitTaskState" placeholder="请选择任务状态" @change="handleQuery" clearable>
						<el-option v-for="item in aiOrderVisitTaskState" :value="item.key" :key="item.key" :label="item.value" />
					</el-select>
				</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="drawer = true" class="default-button"> <SvgIcon name="ele-Search" class="mr5" />更多查询</el-button>
				</el-form-item>
			</el-form>
			<vxe-toolbar
				ref="toolbarRef"
				:loading="state.loading"
				custom
				:refresh="{
					queryMethod: handleQuery,
				}"
				:tools="[{ toolRender: { name: 'exportCurrent' } }, { toolRender: { name: 'exportAll' } }]"
			>
				<template #buttons>
					<el-button type="primary" @click="onAddVisit" v-auth="'business:visit:smart:add'" :loading="state.loading">
						<SvgIcon name="ele-Plus" class="mr5" /> 创建任务
					</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="businessVisitSmart"
					:custom-config="{
						storage: true,
					}"
					:params="{ exportMethod: getSmartVisitExport, exportParams: requestParams }"
					showHeaderOverflow
				>
					<vxe-column field="name" title="回访任务名称" min-width="200"></vxe-column>
					<vxe-column field="beginTime" title="开始时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.beginTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="endTime" title="结束时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.endTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="hasVisitCount" title="回访任务总数量" width="140"></vxe-column>
					<vxe-column field="visitedCount" title="回访任务成功数量" width="140"></vxe-column>
					<vxe-column field="visitedFailCount" title="回访任务失败数量" width="140"></vxe-column>
					<vxe-column field="taskStateText" title="任务完成状态" width="130"></vxe-column>
					<vxe-column field="creatorName" title="创建人" width="130"></vxe-column>
					<vxe-column field="creationTime" title="创建时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column title="操作" fixed="right" width="220" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onDetail(row)" title="回访明细"> 回访明细 </el-button>
							<el-button
								link
								type="primary"
								v-if="[5].includes(row.taskState)"
								@click="onTermination(row)"
								title="终止回访任务"
								v-auth="'business:visit:smart:termination'"
							>
								终止任务
							</el-button>
							<el-button
								link
								type="primary"
								v-if="[5].includes(row.taskState)"
								@click="onStart(row)"
								title="启动任务"
								v-auth="'business:visit:smart:start'"
							>
								启动
							</el-button>
							<el-button
								link
								type="primary"
								v-if="[1, 2].includes(row.taskState)"
								@click="onPause(row)"
								title="暂停任务"
								v-auth="'business:visit:smart:pause'"
							>
								暂停
							</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>
		<el-drawer v-model="drawer" title="更多查询" size="500px">
			<el-form :model="state.queryParams" ref="drawerRuleFormRef" @submit.native.prevent label-width="90px">
				<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 label="开始时间" prop="startTime">
					<el-date-picker
						v-model="state.queryParams.startTime"
						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 label="结束时间" prop="endTime">
					<el-date-picker
						v-model="state.queryParams.endTime"
						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>
			<template #footer>
				<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
				<el-button @click="resetQuery(drawerRuleFormRef)" class="default-button"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
			</template>
		</el-drawer>
		<!--  选择需要智能回访的工单  -->
		<smart-visit-add ref="smartVisitAddRef" @updateList="queryList" />
		<!--  回访明细  -->
		<smart-visit-detail ref="smartVisitDetailRef" @updateList="queryList" />
	</div>
</template>

<script lang="tsx" setup name="businessVisitSmart">
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { getSmartVisitBaseData, getSmartVisitExport, getSmartVisitList } from '@/api/smartVisit';
import { smartCallOutTaskPause, smartCallOutTaskStart, smartCallOutTaskStop } from '@/api/auxiliary/smartCallOut';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import Other from '@/utils/other';

// 引入组件
const SmartVisitAdd = defineAsyncComponent(() => import('@/views/business/visit/components/Smart-visit-add.vue')); // 选择需要智能回访的工单
const SmartVisitDetail = defineAsyncComponent(() => import('@/views/business/visit/components/Smart-visit-Detail.vue')); // 回访明细
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页

// 定义变量内容
const state = reactive<any>({
	loading: false, // 加载状态
	queryParams: {
		// 查询参数
		PageIndex: 1,
		PageSize: 20,
		Keyword: null,
		AiOrderVisitTaskState: null,
		crTime: [],
		StartTime: null,
		EndTime: null,
    startTime:[],
    AiVisitTimeBeginStart:null,
    AiVisitTimeBeginEnd:null,
    endTime:[],
    AiVisitTimeEndStart:null,
    AiVisitTimeEndEnd:null
	},
	total: 0, // 总条数
	tableData: [], // 表格数据
});
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
const requestParams = ref<EmptyObjectType>({});
// 获取参数列表
const queryList = () => {
	return new Promise((resolve, reject) => {
		state.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');
		requestParams.value.AiVisitTimeBeginStart = state.queryParams.startTime === null ? null : state.queryParams.startTime[0];
		requestParams.value.AiVisitTimeBeginEnd = state.queryParams.startTime === null ? null : state.queryParams.startTime[1];
		Reflect.deleteProperty(requestParams.value, 'startTime');
		requestParams.value.AiVisitTimeEndStart = state.queryParams.endTime === null ? null : state.queryParams.endTime[0];
		requestParams.value.AiVisitTimeEndEnd = state.queryParams.endTime === null ? null : state.queryParams.endTime[1];
		Reflect.deleteProperty(requestParams.value, 'endTime');
		getSmartVisitList(requestParams.value)
			.then((res) => {
				state.tableData = res.result.items ?? [];
				state.total = res.result.total ?? 0;
				state.loading = false;
				resolve(res);
			})
			.catch(() => {
				state.loading = false;
				reject();
			});
	})
};
// 页面基础数据
const aiOrderVisitTaskState = ref<EmptyArrayType>([]);
const getBaseData = async () => {
	try {
		const { result } = await getSmartVisitBaseData();
		aiOrderVisitTaskState.value = result.aiOrderVisitTaskState;
	} catch (e) {
		console.log(e);
	}
};
// 重置表单
const drawerRuleFormRef = ref();
const ruleFormRef = ref<RefType>(null); // 表单ref
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	ruleFormRef.value?.resetFields();
	queryList();
};
// 新增回访任务
const smartVisitAddRef = ref<RefType>();
const onAddVisit = () => {
	smartVisitAddRef.value.openDialog();
};
// 回访明细
const smartVisitDetailRef = ref<RefType>();
const onDetail = (row: any) => {
	smartVisitDetailRef.value.openDialog(row);
};
// 终止智能回访任务
const onTermination = (row: any) => {
	ElMessageBox.confirm(`您确定要终止回访任务【${row.name}】吗？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			// 1 :智能回访 2：批量外呼
			smartCallOutTaskStop({ id: row.id, typeId: 1 })
				.then(() => {
					ElMessage({
						type: 'success',
						message: '终止任务成功',
					});
					queryList();
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {
			// 取消
		});
};
// 启动任务
const onStart = (row: any) => {
	ElMessageBox.confirm(`您确定要启动回访任务【${row.name}】吗？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			smartCallOutTaskStart({ id: row.id, typeId: 1 })
				.then(() => {
					ElMessage({
						type: 'success',
						message: '启动任务成功',
					});
					queryList();
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {
			// 取消
		});
};
// 暂停任务
const onPause = (row: any) => {
	ElMessageBox.confirm(`您确定要暂停回访任务【${row.name}】吗？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			smartCallOutTaskPause({ id: row.id, typeId: 1 })
				.then(() => {
					ElMessage({
						type: 'success',
						message: '暂停任务成功',
					});
					queryList();
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {
			// 取消
		});
};
const drawer = ref(false);
const toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
// 页面加载时
onMounted(() => {
	queryList().then(()=>{
		getBaseData();
	})
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
