<template>
	<div class="auxiliary-Smart-call-out-template-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="TemplateName">
					<el-input
						v-model="state.queryParams.TemplateName"
						placeholder="请填写模板标题"
						clearable
						@keyup.enter="handleQuery"
						class="keyword-input"
					/>
				</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="timeStartChangeCr"
						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="onAdd" v-auth="'auxiliary:smartCallOut:tem: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, useKey: true }"
					:row-config="{ isCurrent: true, isHover: true, useKey: true, height: 30 }"
					ref="tableRef"
					height="auto"
					auto-resize
					show-overflow
					:scrollY="{ enabled: true, gt: 100 }"
					id="auxiliarySmartCallOutTemplate"
					:custom-config="{ storage: true }"
				>
					<vxe-column field="templateName" title="模板名称" min-width="150"></vxe-column>
					<vxe-column field="callOutTaskCount" title="关联外呼任务" width="150"></vxe-column>
					<vxe-column field="isEnable" title="是否启用" width="100">
						<template #default="{ row }">
							<template v-if="auth('quality:template:edit')">
								<el-switch v-model="row.isEnable" active-text="启用" inactive-text="禁用" @change="changeIsEnable(row)" inline-prompt size="small" />
							</template>
							<span v-else>{{ row.isEnable ? '已启用' : '已禁用' }}</span>
						</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="140" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onEdit(row)" v-auth="'auxiliary:smartCallOut:tem:edit'" title="编辑模板"> 编辑 </el-button>
							<el-button link type="danger" @click="onDelete(row)" v-auth="'auxiliary:smartCallOut:tem:delete'" title="删除模板"> 删除 </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>
		<!-- 新增模板   -->
		<tem-add ref="temAddRef" @updateList="queryList" />
		<!-- 编辑模板   -->
		<tem-edit ref="temEditRef" @updateList="queryList" />
	</div>
</template>

<script lang="tsx" setup name="auxiliarySmartCallOutTemplate">
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 { auth } from '@/utils/authFunction';
import { smartCallOutTemDelete, smartCallOutTemEnable, smartCallOutTemList } from '@/api/auxiliary/smartCallOut';
import other from '@/utils/other';

// 引入组件
const TemAdd = defineAsyncComponent(() => import('@/views/auxiliary/smartCallOut/components/Tem-add.vue')); // 新建模板
const TemEdit = defineAsyncComponent(() => import('@/views/auxiliary/smartCallOut/components/Tem-edit.vue')); // 编辑标签
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页

// 定义变量内容
const state = reactive({
	loading: false, // 加载状态
	queryParams: {
		// 查询参数
		PageIndex: 1,
		PageSize: 20,
		TemplateName: null,
		crTime: [],
		StartTime: null,
		EndTime: null,
	},
	total: 0, // 总条数
	tableData: [], // 表格数据
});
const ruleFormRef = ref<RefType>(null); // 表单ref
/** 搜索按钮操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
const handleTimeChange = (val: string[], startKey: string, endKey: string) => {
	if (val) {
		state.queryParams[startKey] = val[0];
		state.queryParams[endKey] = val[1];
	} else {
		state.queryParams[startKey] = null;
		state.queryParams[endKey] = null;
	}
	handleQuery();
};
// 创建时间
const timeStartChangeCr = (val: string[]) => {
	handleTimeChange(val, 'StartTime', 'EndTime');
};
// 获取列表
const queryList = () => {
	state.loading = true;
	let request = other.deepClone(state.queryParams);
	Reflect.deleteProperty(request, 'crTime'); // 删除无用的参数
	smartCallOutTemList(state.queryParams)
		.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();
	state.queryParams.StartTime = null;
	state.queryParams.EndTime = null;
	queryList();
};
// 新增模板
const temAddRef = ref<RefType>();
const onAdd = () => {
	temAddRef.value.openDialog();
};
// 编辑模板
const temEditRef = ref<RefType>();
const onEdit = (row: any) => {
	temEditRef.value.openDialog(row);
};
// 删除模板
const onDelete = (row: any) => {
	ElMessageBox.confirm('确定要删除当前模板？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			smartCallOutTemDelete(row.id)
				.then(() => {
					ElMessage({
						message: '操作成功',
						type: 'success',
					});
					queryList();
					state.loading = false;
				})
				.catch(() => {})
				.finally(() => {
					state.loading = false;
				});
		})
		.catch(() => {});
};
// 启用和禁用
const changeIsEnable = (row: any) => {
	row.isEnable = !row.isEnable; //保持switch点击前的状态
	ElMessageBox.confirm(`您确定要${row.isEnable ? '禁用' : '启用'}：【${row.templateName}】模板，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			smartCallOutTemEnable({ id: row.id })
				.then(() => {
					ElMessage.success('操作成功');
					queryList();
				})
				.catch(() => {
					queryList();
				});
		})
		.catch(() => {});
};
// 页面加载时
const toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
