<template>
	<div class="auxiliary-SMS-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="State">
					<el-select v-model="state.queryParams.State" placeholder="请选择任务状态" @change="handleQuery">
						<el-option v-for="item in smsTaskState" :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:smsTask: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="auxiliarySmsTask"
					:custom-config="{ storage: true }"
					showHeaderOverflow
				>
					<vxe-column field="taskName" title="市民姓名" min-width="200"></vxe-column>
					<vxe-column field="smsTaskStateText" title="任务状态" width="110"></vxe-column>
					<vxe-column field="content" title="短信内容" min-width="200"></vxe-column>
					<vxe-column field="smsCount" title="短信总量" width="110"></vxe-column>
					<vxe-column field="planSendTime" title="计划发送时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.planSendTime, '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="160" 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:smsTask:end'" title="终止任务" v-if="[0].includes(row.smsTaskState)"> 终止任务 </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="auxiliarySmsTask">
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { defaultTimeStartEnd, shortcuts } from "@/utils/constants";
import { smartCallOutSmsBaseData, smartCallOutSmsList, smartCallOutSmsStop } from '@/api/auxiliary/smartCallOut';
import Other from '@/utils/other';

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

// 定义变量内容
const state = reactive<any>({
	loading: false, // 加载状态
	queryParams: {
		// 查询参数
		PageIndex: 1,
		PageSize: 2,
		State: null,
		TaskName: null,
		crTime: [],
		StateTime:null,
		EndTime:null,
	},
	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.StateTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[0];
	request.EndTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[1];
	smartCallOutSmsList(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(() => {
			smartCallOutSmsStop(row.id )
				.then(() => {
					ElMessage({
						type: 'success',
						message: '终止任务成功',
					});
					queryList();
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {});
};
const smsTaskState = ref<EmptyArrayType>([]);
// 获取基础数据
const getBaseData  = () => {
	smartCallOutSmsBaseData().then((res) => {
		smsTaskState.value = res.result?.smsTaskState ?? [];
	});
};
const toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
// 页面加载时
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
	getBaseData();
});
</script>
