<template>
	<div class="business-visit-smart-container layout-pd">
		<el-card shadow="never">
			<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="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 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)" class="default-button"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
				</el-form-item>
			</el-form>
		</el-card>
		<el-card shadow="never">
			<ProTable
				ref="proTableRef"
				:columns="columns"
				:data="state.tableData"
				@updateTable="queryList"
				:loading="state.loading"
				:total="state.total"
				v-model:page-index="state.queryParams.PageIndex"
				v-model:page-size="state.queryParams.PageSize"
				:toolButton="['refresh', 'setting', 'exportCurrent', 'exportAll']"
				@export-current="exportTable($event)"
				@export-all="exportTable($event, true)"
			>
				<template #tableHeader="scope">
					<el-button type="primary" @click="onAddVisit" v-auth="'business:visit:smart:add'">
						<SvgIcon name="ele-Plus" class="mr5" /> 创建任务
					</el-button>
				</template>
				<!-- 表格操作 -->
				<template #operation="{ 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>
			</ProTable>
		</el-card>
		<!--  选择需要智能回访的工单  -->
		<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 { smartCallOutTaskExport, smartCallOutTaskPause, smartCallOutTaskStart, smartCallOutTaskStop } from "@/api/auxiliary/smartCallOut";
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import Other from '@/utils/other';
import { downloadFileByStream } from '@/utils/tools';
import { exportOrder } from '@/api/business/order';

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

const proTableRef = ref<RefType>(); // 表格ref
// 表格配置项
const columns = ref<any[]>([
	{ prop: 'name', label: '回访任务名称' },
	{ prop: 'hasVisitCount', label: '回访任务总数量' },
	{ prop: 'visitedCount', label: '回访任务成功数量' },
	{ prop: 'visitedFailCount', label: '回访任务失败数量' },
	{ prop: 'taskStateText', label: '任务完成状态' },
	{ prop: 'creatorName', label: '创建人' },
	{
		prop: 'creationTime',
		label: '创建时间',
		width: 170,
		render: (scope: any) => {
			return <span>{formatDate(scope.row.creationTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 210, align: 'center' },
]);
// 定义变量内容
const state = reactive<any>({
	loading: false, // 加载状态
	queryParams: {
		// 查询参数
		PageIndex: 1,
		PageSize: 10,
		Keyword: null,
		AiOrderVisitTaskState: null,
		crTime: [],
		StartTime: null,
		EndTime: null,
	},
	total: 0, // 总条数
	tableData: [], // 表格数据
});
const ruleFormRef = ref<RefType>(null); // 表单ref
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
// 获取参数列表
const queryList = () => {
	state.loading = true;
	let request = Other.deepClone(state.queryParams);
	request.StartTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[0];
	request.EndTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[1];
	Reflect.deleteProperty(request, 'crTime');
	getSmartVisitList(request)
		.then((res) => {
			state.loading = false;
			state.tableData = res.result.items ?? [];
			state.total = res.result.total ?? 0;
		})
		.finally(() => {
			state.loading = false;
		});
};
// 页面基础数据
const aiOrderVisitTaskState = ref([]);
const getBaseData = async () => {
	try {
		const { result } = await getSmartVisitBaseData();
		aiOrderVisitTaskState.value = result.aiOrderVisitTaskState;
	} catch (e) {
		console.log(e);
	}
};
// 重置表单
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.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 exportTable = (val: any, isExportAll = false) => {
	let request = Other.deepClone(state.queryParams);
	request.StartTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[0];
	request.EndTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[1];
	Reflect.deleteProperty(request, 'crTime');
	const columnInfos = val.map((item: any) => {
		return {
			prop: item.prop,
			name: item.label,
		};
	});
	const req = {
		queryDto: request,
		columnInfos,
		isExportAll,
	};
	state.loading = true;
  getSmartVisitExport(req)
		.then((res: any) => {
			state.loading = false;
			downloadFileByStream(res);
		})
		.catch(() => {
			state.loading = false;
		});
};
// 页面加载时
onMounted(() => {
	getBaseData();
	queryList();
});
</script>
