<template>
	<div class="knowledge-apply-my-container layout-pd">
		<el-card shadow="never">
			<el-tabs v-model="state.queryParams.Status" @tab-change="handleClick">
				<el-tab-pane label="全部" name=" "></el-tab-pane>
				<el-tab-pane label="处理中" name="0"></el-tab-pane>
				<el-tab-pane label="处理完成" name="1"></el-tab-pane>
				<el-tab-pane label="已退回" name="2"></el-tab-pane>
				<el-tab-pane label="已撤销" name="3"></el-tab-pane>
				<el-form :model="state.queryParams" ref="ruleFormRef" :inline="true" @submit.native.prevent class="mt15">
					<el-form-item label="申请类型" prop="ApplyType">
						<el-select v-model="state.queryParams.ApplyType" placeholder="请选择申请类型" class="w100">
							<el-option v-for="item in state.ApplyTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="是否超时" prop="IsOvertime">
						<el-select v-model="state.queryParams.IsOvertime" placeholder="请选择是否超时" class="w100">
							<el-option label="否" value="1" />
							<el-option label="是" value="0" />
						</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="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-tabs>
		</el-card>
		<el-card shadow="never">
			<div class="flex-center-between mb20">
				<p class="table-title">信息列表</p>
				<div>
					<el-button type="primary" @click="onApply"> <SvgIcon name="ele-Plus" class="mr5" /> 发起申请 </el-button>
					<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="content" label="申请内容" show-overflow-tooltip></el-table-column>
				<el-table-column prop="knowledgeApplyType" label="申请类型" show-overflow-tooltip>
					<template #default="{ row }">
						<span>
							{{ row.knowledgeApplyType === 0 ? '新增' : '更新' }}
						</span>
					</template>
				</el-table-column>
				<el-table-column label="状态" show-overflow-tooltip>
					<template #default="{ row }">
						<span style="color: var(--el-color-primary)" v-if="row.status === 0">处理中</span>
						<span style="color: var(--el-color-success)" v-if="row.status === 1">处理完成</span>
						<span style="color: var(--el-color-danger)" v-if="row.status === 2">已退回</span>
						<span style="color: var(--el-color-info)" v-if="row.status === 3">已撤销</span>
					</template>
				</el-table-column>
				<el-table-column prop="toNo" 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 prop="toNo" label="处理完成时间" show-overflow-tooltip width="170">
					<template #default="scope">
						<span>{{ formatDate(scope.row.handleTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="toNo" label="撤回时间" show-overflow-tooltip width="170">
					<template #default="scope">
						<span>{{ formatDate(scope.row.revokeTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="toNo" label="退回时间" show-overflow-tooltip width="170">
					<template #default="scope">
						<span>{{ formatDate(scope.row.returnTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
					</template>
				</el-table-column>
				<el-table-column label="是否超时" show-overflow-tooltip>
					<template #default="{ row }">
						{{ row.isOvertime ? '是' : '否' }}
					</template>
				</el-table-column>
				<el-table-column label="操作" width="160" fixed="right" align="center">
					<template #default="{ row }">
						<el-button text type="primary" @click="onDetail(row)" title="查看详情" v-if="[0, 1, 2].includes(row.status)"> 查看详情 </el-button>
						<el-button text type="primary" @click="onEdit(row)" title="编辑" v-if="[2, 3].includes(row.status)"> 编辑 </el-button>
						<el-button text type="danger" @click="onRecall(row)" title="撤回" v-if="[0].includes(row.status)"> 撤回 </el-button>
						<el-button text type="danger" @click="onDelete(row)" title="删除" v-if="[2, 3].includes(row.status)"> 删除 </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>
		<!-- 新增 -->
		<MyApplyAdd ref="myApplyAddRef" @updateList="getList" />
		<!-- 修改 -->
		<MyApplyEdit ref="myApplyEditRef" @updateList="getList" />
		<!-- 详情 -->
		<MyApplyDetail ref="myApplyDetailRef" />
	</div>
</template>

<script lang="ts" setup name="MyknowledgeApply">
import { ref, reactive, onMounted, defineAsyncComponent } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute } from 'vue-router';
import { formatDate } from '/@/utils/formatTime';
import table2excel from 'js-table2excel';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
// 引入节流
import { throttle } from '/@/utils/tools';
import { KnowledgeApply, KnowledgeRemove, KnowledgeCancel } from '/@/api/knowledge/apply';
import { getOrgList } from '/@/api/system/organize';
import { KnowledgeGetknowledge } from '/@/api/knowledge';

// 引入组件
const MyApplyAdd = defineAsyncComponent(() => import('/@/views/knowledge/apply/my/component/MyApplyAdd.vue'));
const MyApplyEdit = defineAsyncComponent(() => import('/@/views/knowledge/apply/my/component/MyApplyEdit.vue'));
const MyApplyDetail = defineAsyncComponent(() => import('/@/views/knowledge/apply/my/component/MyApplyDetail.vue'));
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: ' ',
		ApplyType: '',
		IsOvertime: '',
		StartTime: '',
		EndTime: '',
	},
	tableList: [],
	loading: false,
	total: 0,
	multipleSelection: [],
	ApplyTypeOptions: [
		{
			label: '新增',
			value: 0,
		},
		{
			label: '修改',
			value: 1,
		},
	],
	orgData: [],
});
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const ruleFormRef = ref<FormInstance>();
const myApplyAddRef = ref();
const myApplyEditRef = ref();
const myApplyDetailRef = ref();
const route = useRoute();
// 创建时间
const tiemChange = (val: string[]) => {
	if (val) {
		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'); // 删除无用的参数
	KnowledgeApply(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.PageIndex = 1;
	state.queryParams.StartTime = '';
	state.queryParams.EndTime = '';
	getList();
}, 1000);
// 切换tab 查询列表
const handleClick = () => {
	getList();
};
// 查看详情
const onDetail = (row: any) => {
	myApplyDetailRef.value.openDialog(row);
};
// 发起申请
const onApply = () => {
	myApplyAddRef.value.openDialog(state.orgData, state.knowledgeOptions);
};
// 修改申请
const onEdit = (row: any) => {
	myApplyEditRef.value.openDialog(row, state.orgData, state.knowledgeOptions);
};
// 撤回
const onRecall = (row: any) => {
	ElMessageBox.confirm(`是否确定要撤回申请？撤回后请到【主动撤回】中进行查看和管理`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			KnowledgeCancel(row.id).then(() => {
				ElMessage.success('操作成功');
				getList();
			});
		})
		.catch(() => {});
};
// 删除
const onDelete = (row: any) => {
	ElMessageBox.confirm(`是否确定删除该申请？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			KnowledgeRemove(row.id).then(() => {
				ElMessage.success('操作成功');
				getList();
			});
		})
		.catch(() => {});
};
// 导出表格
const onImportTable = () => {
	const tabeHeader = [
		{ key: 'content', colWidth: '', title: '申请内容', type: 'text', isCheck: true },
		{ key: 'knowledgeApplyType', colWidth: '', title: '申请类型', type: 'text', isCheck: true },
		{ key: 'status', colWidth: '', title: '状态', type: 'text', isCheck: true },
		{ key: 'creationTime', colWidth: '', title: '创建时间', type: 'text', isCheck: true },
		{ key: 'handleTime', colWidth: '', title: '处理完成时间', type: 'text', isCheck: true },
		{ key: 'revokeTime', colWidth: '', title: '撤回时间', type: 'text', isCheck: true },
		{ key: 'returnTime', colWidth: '', title: '退回时间', type: 'text', isCheck: true },
		{ key: 'isOvertime', colWidth: '', title: '是否超时', type: 'text', isCheck: true },
	];
	table2excel(
		tabeHeader,
		state.multipleSelection,
		`${themeConfig.value.globalTitle}-${route.meta.title} ${formatDate(new Date(), 'YYYY-mm-dd HH-MM')}`
	);
};

onMounted(async () => {
	getList();
	try {
		const res: any = await Promise.all([getOrgList(), KnowledgeGetknowledge()]);
		state.orgData = res[0].result ?? [];
		state.knowledgeOptions = res[1].result ?? [];
		state.knowledgeOptions = state.knowledgeOptions.map((v: any) => ({
			label: v.title,
			value: v.id,
			...v,
		}));
	} catch (error) {
		console.log(error);
	}
});
</script>
