<template>
	<div class="knowledge-knowledgeDraft-container layout-pd">
		<el-card shadow="never">
			<el-form :model="state.queryParams" ref="ruleFormRef" :inline="true" @submit.native.prevent class="mt15">
				<el-form-item label="标题" prop="street">
					<el-input v-model="state.queryParams.street" placeholder="请填写标题" @keyup.enter="getList" clearable> </el-input>
				</el-form-item>
				<el-form-item label="类型" prop="KnowledgeTypeId">
					<el-cascader
						:options="state.typeData"
						filterable
						:props="{ checkStrictly: true, value: 'id', label: 'name', emitPath: false, children: 'child' }"
						placeholder="请选择类型"
						clearable
						class="w100"
						v-model="state.queryParams.KnowledgeTypeId"
					>
						<template #default="{ node, data }">
							<span>{{ data.name }}</span>
							<span v-if="!node.isLeaf"> ({{ data.child.length }}) </span>
						</template>
					</el-cascader>
				</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="tiemChange"
						value-format="YYYY-MM-DD[T]HH:mm:ss.sss[Z]"
					/>
					<!-- value-format="YYYY-MM-DD" -->
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="getList" :loading="state.loading" v-waves> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
					<el-button @click="resetQuery(ruleFormRef)" v-waves class="default-button"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
				</el-form-item>
			</el-form>
		</el-card>
		<el-card shadow="never">
			<div class="flex-center-between mb20">
				<p class="table-title">信息列表</p>
				<div>
					<el-button type="primary" :disabled="!state.multipleSelection.length" @click="onImportTable">
						<SvgIcon name="iconfont icon-daochu" class="mr5" />导出
					</el-button>
				</div>
			</div>
			<!-- 表格 -->
			<el-table :data="state.tableList" v-loading="state.loading" row-key="id" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" :reserve-selection="true" />
				<el-table-column prop="title" label="标题" show-overflow-tooltip></el-table-column>
				<el-table-column prop="knowledgeTypeName" label="类型" show-overflow-tooltip></el-table-column>
				<el-table-column prop="creationTime" label="创建时间" show-overflow-tooltip width="170">
					<template #default="scope">
						<span>{{ formatDate(scope.row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="120" fixed="right" align="center">
					<template #default="scope">
						<el-button text type="primary" @click="onEdit(scope.row)" title="编辑"> 编辑 </el-button>
						<el-button text type="danger" @click="onDel(scope.row)" title="删除"> 删除 </el-button>
					</template>
				</el-table-column>
				<template #empty>
					<Empty />
				</template>
			</el-table>
			<!-- 分页 -->
			<pagination :total="state.total" v-model:page="state.queryParams.PageIndex" v-model:limit="state.queryParams.PageSize" @pagination="getList" />
		</el-card>
	</div>
</template>

<script lang="ts" setup name="knowledgeDraft">
import { ref, reactive, onMounted, onActivated } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { treelist } from '/@/api/knowledge/type';
import { formatDate } from '/@/utils/formatTime';
import { useRouter } from 'vue-router';
import table2excel from 'js-table2excel';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
// 引入节流
import { throttle } from '/@/utils/tools';
import { mydraftslist, removedrafts } from '/@/api/knowledge/draft';

const shortcuts = [
	{
		text: '近一周',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
			return [start, end];
		},
	},
	{
		text: '近一个月',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
			return [start, end];
		},
	},
	{
		text: '近三个月',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
			return [start, end];
		},
	},
];

// 定义变量内容
const state = reactive(<any>{
	queryParams: {
		PageIndex: 1,
		PageSize: 10,
		Status: '0',
		ApplyType: '',
		IsOvertime: '',
		StartTime: '',
		EndTime: '',
	},
	typeData: [], // 知识分类
	tableList: [],
	loading: false,
	total: 0,
	multipleSelection: [],
	directionList: [
		{
			label: '全部',
			value: '',
		},
		{
			label: '呼入',
			value: 0,
		},
		{
			label: '呼出',
			value: 1,
		},
	],
});
const router = useRouter();
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const ruleFormRef = ref<FormInstance>();
// 创建时间
const tiemChange = (val: string[]) => {
	state.queryParams.StartTime = val[0];
	state.queryParams.EndTime = val[1];
};
/** 获取草稿箱列表 */
const getList = () => {
	state.loading = true;
	let request = JSON.parse(JSON.stringify(state.queryParams));
	Reflect.deleteProperty(request, 'crTime'); // 删除无用的参数
	mydraftslist(request)
		.then((response: any) => {
			state.tableList = response?.result.items ?? [];
			state.total = response?.result.total;
			state.loading = false;
		})
		.catch(() => {
			state.loading = false;
		});
};
// 多选表格
const handleSelectionChange = (val: any) => {
	state.multipleSelection = val;
};
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	state.queryParams.StartTime = '';
	state.queryParams.EndTime = '';
	getList();
}, 1000);
// 修改知识
const onEdit = (row: any) => {
	router.push({
		name: 'knowledgeEdit',
		params: {
			id: row.id,
			tagsViewName: '编辑知识草稿',
		},
	});
};
const onDel = (row: any) => {
	ElMessageBox.confirm(`确定要从草稿箱删除`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			removedrafts(row.id).then(() => {
				ElMessage.success('操作成功');
				getList();
			});
		})
		.catch(() => {});
};
// 导出表格
const onImportTable = () => {
	const tabeHeader = [
		{ key: 'userName', colWidth: '', title: '用户名称', type: 'text', isCheck: true },
		{ key: 'fromNo', colWidth: '', title: '主叫号码', type: 'text', isCheck: true },
		{ key: 'toNo', colWidth: '', title: '被叫号码', type: 'text', isCheck: true },
		{ key: 'callTypeText', colWidth: '', title: '通话类型', type: 'text', isCheck: true },
		{ key: 'callStatusText', colWidth: '', title: '通话状态', type: 'text', isCheck: true },
		{ key: 'callDirectionText', colWidth: '', title: '呼叫方向', type: 'text', isCheck: true },
		{ key: 'endByText', colWidth: '', title: '通话结束方', type: 'text', isCheck: true },
		{ key: 'phoneIspText', colWidth: '', title: '运营商', type: 'text', isCheck: true },
		{ key: 'ringOffTypeText', colWidth: '', title: '挂断类型', type: 'text', isCheck: true },
		{ key: 'attribution', colWidth: '', title: '归属地', type: 'text', isCheck: true },
		// { key: 'creationTime', colWidth: '', title: '创建时间', type: 'text', isCheck: true },
		// { key: 'image', colWidth: '', width: '70', height: '40', title: '图片描述', type: 'image', isCheck: true },
	];
	table2excel(tabeHeader, state.multipleSelection, `${themeConfig.value.globalTitle} ${formatDate(new Date(), 'YYYY-mm-dd HH-MM')}`);
};
// 知识分类
const getKnowledgeType = async () => {
	state.loading = true;
	try {
		const res: any = await treelist({IsEnable:1});
		state.typeData = res.result ?? [];
		state.loading = false;
	} catch (error) {
		state.loading = false;
	}
};
onMounted(() => {
	getList();
	getKnowledgeType();
});
onActivated(() => {
	getList();
});
</script>
<style lang="scss" scoped></style>
