<template>
	<div class="auxiliary-Smart-call-out-task-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="TaskName">
					<el-input v-model="state.queryParams.TaskName" placeholder="请填写任务名称" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item label="任务状态" prop="AiCallOutTaskState">
					<el-select v-model="state.queryParams.AiCallOutTaskState" placeholder="请选择任务状态" @change="handleQuery" clearable>
						<el-option v-for="item in aiCallOutTaskState" :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>
			<vxe-toolbar
				ref="toolbarRef"
				:loading="state.loading"
				custom
				:refresh="{
					queryMethod: handleQuery,
				}"
			>
				<template #buttons>
					<el-button type="primary" @click="addTask" v-auth="'auxiliary:smartCallOut:add'">
						<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="auxiliarySmartCallOutTask"
					:custom-config="{ storage: true }"
					showHeaderOverflow
				>
					<vxe-column field="taskName" title="市民姓名" min-width="200"></vxe-column>
					<vxe-column field="aiCallOutTaskStateText" title="任务状态" width="110"></vxe-column>
					<vxe-column field="hasVisitCount" title="外呼总量" width="120"></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="creatorName" title="创建人" width="120"></vxe-column>
					<vxe-column field="creatorOrgName" title="创建部门" width="140"></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="210" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onDetail(row)" title="外呼明细"> 外呼明细 </el-button>
							<!-- 已结束，已终止不能终止任务 其他状态都可以中止任务 -->
							<el-button
								link
								type="primary"
								@click="onEnd(row)"
								v-auth="'auxiliary:smartCallOut:end'"
								title="终止任务"
								v-if="[5].includes(row.aiCallOutTaskState)"
							>
								终止任务
							</el-button>
							<el-button
								link
								type="primary"
								v-if="[5].includes(row.aiCallOutTaskState)"
								@click="onStart(row)"
								title="启动任务"
								v-auth="'auxiliary:smartCallOut:start'"
							>
								启动
							</el-button>
							<el-button
								link
								type="primary"
								v-if="[1, 2].includes(row.aiCallOutTaskState)"
								@click="onPause(row)"
								title="暂停任务"
								v-auth="'auxiliary:smartCallOut: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>
		<!-- 创建任务   -->
		<create-task ref="createTaskRef" @updateList="queryList" />
		<task-detail ref="taskDetailRef" />
	</div>
</template>

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

// 引入组件
const CreateTask = defineAsyncComponent(() => import('@/views/auxiliary/smartCallOut/components/Create-task.vue')); // 创建任务
const TaskDetail = defineAsyncComponent(() => import('@/views/auxiliary/smartCallOut/components/Task-detail.vue')); // 任务详情
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页

const proTableRef = ref<RefType>(); // 表格ref
// 表格配置项
const columns = ref<any[]>([
	{ prop: 'taskName', label: '任务名称', minWidth: 200 },
	{ prop: 'aiCallOutTaskStateText', label: '任务状态', minWidth: 100 },
	{ prop: 'hasVisitCount', label: '外呼总量' },
	{
		prop: 'beginTime',
		label: '任务开始时间',
		minWidth: 160,
		render: (scope) => {
			return <span>{formatDate(scope.row.beginTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{
		prop: 'endTime',
		label: '任务结束时间',
		minWidth: 160,
		render: (scope) => {
			return <span>{formatDate(scope.row.endTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{ prop: 'creatorName', label: '创建人', minWidth: 120 },
	{ prop: 'creatorOrgName', label: '创建部门', minWidth: 140 },
	{
		prop: 'creationTime',
		label: '创建时间',
		width: 160,
		render: (scope) => {
			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: 20,
		TaskName: null, // 任务名称
		AiCallOutTaskState: null, // 任务状态
		crTime: [],
	},
	total: 0, // 总条数
	tableData: [], // 表格数据
});
const ruleFormRef = ref<RefType>(null); // 表单ref
/** 搜索按钮操作 */
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');
	smartCallOutTaskList(request)
		.then((res) => {
			state.loading = false;
			state.tableData = res.result.items ?? [];
			state.total = res.result.total ?? 0;
		})
		.finally(() => {
			state.loading = false;
		});
};
// 重置表单
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
};
// 创建任务
const createTaskRef = ref<RefType>();
const addTask = () => {
	createTaskRef.value.openDialog();
};
// 任务明细
const taskDetailRef = ref<RefType>();
const onDetail = (row: any) => {
	taskDetailRef.value.openDialog(row);
};
// 终止任务
const onEnd = (row: any) => {
	ElMessageBox.confirm(`您确定要终止外呼任务【${row.taskName}】吗？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			// 1 :智能回访 2：批量外呼
			smartCallOutTaskStop({ id: row.id, typeId: 2 })
				.then(() => {
					ElMessage({
						type: 'success',
						message: '终止任务成功',
					});
					queryList();
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {});
};
// 启动任务
const onStart = (row: any) => {
	ElMessageBox.confirm(`您确定要启动外呼任务【${row.taskName}】吗？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			smartCallOutTaskStart({ id: row.id, typeId: 2 })
				.then(() => {
					ElMessage({
						type: 'success',
						message: '启动任务成功',
					});
					queryList();
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {
			// 取消
		});
};
// 暂停任务
const onPause = (row: any) => {
	ElMessageBox.confirm(`您确定要暂停外呼任务【${row.taskName}】吗？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			smartCallOutTaskPause({ id: row.id, typeId: 2 })
				.then(() => {
					ElMessage({
						type: 'success',
						message: '暂停任务成功',
					});
					queryList();
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {
			// 取消
		});
};
// 获取基础数据
const aiCallOutTaskState = ref([]);
const getBaseData = async () => {
	try {
		const { result } = await smartCallOutTaskBaseData();
		aiCallOutTaskState.value = result.aiCallOutTaskState;
	} catch (e) {
		console.log(e);
	}
};const toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
// 页面加载时
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
	getBaseData();
});
</script>
