<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="v.value" :name="v.key" v-for="(v, i) in state.statusOptions" :key="i"></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="timeChange"
							value-format="YYYY-MM-DD[T]HH:mm:ss"
						/>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="queryList" :loading="state.loading" v-waves> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
						<el-button @click="resetQuery(ruleFormRef)" v-waves class="default-button" :loading="state.loading">
							<SvgIcon name="ele-Refresh" class="mr5" />重置
						</el-button>
					</el-form-item>
				</el-form>
			</el-tabs>
		</el-card>
		<el-card shadow="never">
			<div class="mb20">
				<el-button type="primary" @click="onApply" v-auth="'knowledge:myApply:add'">
					<SvgIcon name="ele-Plus" class="mr5" />
					发起申请
				</el-button>
			</div>
			<!-- 表格 -->
			<el-table :data="state.tableList" v-loading="state.loading" row-key="id">
				<el-table-column prop="content" label="申请内容" show-overflow-tooltip></el-table-column>
				<el-table-column prop="knowledgeApplyTypeName" label="申请类型" show-overflow-tooltip></el-table-column>
				<el-table-column label="状态" show-overflow-tooltip>
					<template #default="{ row }">
            <span v-if="row.status === 0" class="color-primary">{{ row.statusName }}</span>
            <span v-if="row.status === 1" class="color-success">{{ row.statusName }}</span>
            <span v-if="row.status === 2" class="color-danger">{{ row.statusName }}</span>
            <span v-if="row.status === 3" class="color-info">{{ row.statusName }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="toNo" label="创建时间" show-overflow-tooltip width="170">
					<template #default="{ row }">
						<span>{{ formatDate(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="{ row }">
						<span>{{ formatDate(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="{ row }">
						<span>{{ formatDate(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="{ row }">
						<span>{{ formatDate(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="180" fixed="right" align="center">
					<template #default="{ row }">
						<el-button
							link
							type="primary"
							@click="onDetail(row)"
							title="查看详情"
							v-if="[0, 1, 2].includes(row.status)"
							v-auth="'knowledge:apply:detail'"
						>
							查看详情
						</el-button>
						<el-button link type="primary" @click="onEdit(row)" title="编辑" v-if="[2, 3].includes(row.status)" v-auth="'knowledge:myApply:edit'">
							编辑
						</el-button>
						<el-button link type="danger" @click="onRecall(row)" title="撤回" v-if="[0].includes(row.status)" v-auth="'knowledge:myApply:recall'">
							撤回
						</el-button>
						<el-button link type="danger" @click="onDelete(row)" title="删除" v-if="[2, 3].includes(row.status)" v-auth="'knowledge:myApply:delete'">
							删除
						</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="queryList"
			/>
		</el-card>
		<!-- 新增 -->
		<knowledge-my-apply-add ref="KnowledgeMyApplyAddRef" @updateList="queryList" />
		<!-- 修改 -->
		<knowledge-my-apply-edit ref="KnowledgeMyApplyEditRef" @updateList="queryList" />
		<!-- 详情 -->
		<knowledge-my-apply-detail ref="KnowledgeMyApplyDetailRef" />
	</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 { auth } from '/@/utils/authFunction';
import { formatDate } from '/@/utils/formatTime';
import other from '/@/utils/other';
import { throttle } from '/@/utils/tools';
import { shortcuts } from '/@/utils/constants';
import { KnowledgeApply, KnowledgeRemove, KnowledgeCancel, baseData } from '/@/api/knowledge/apply';
import { getOrgList } from '/@/api/system/organize';
import { KnowledgeGetKnowledge } from '/@/api/knowledge';

// 引入组件
const KnowledgeMyApplyAdd = defineAsyncComponent(() => import('/@/views/knowledge/apply/my/component/Knowledge-my-apply-add.vue')); // 新增组件
const KnowledgeMyApplyEdit = defineAsyncComponent(() => import('/@/views/knowledge/apply/my/component/Knowledge-my-apply-edit.vue')); // 修改组件
const KnowledgeMyApplyDetail = defineAsyncComponent(() => import('/@/views/knowledge/apply/my/component/Knowledge-my-apply-detail.vue')); // 详情组件
// 定义变量内容
const state = reactive(<any>{
	queryParams: {
		PageIndex: 1, // 当前页码
		PageSize: 10, // 每页条数
		Status: ' ',  // 状态
		ApplyType: '',  // 申请类型
		IsOvertime: '', // 是否超时
		StartTime: '',  // 开始时间
		EndTime: '',  // 结束时间
	},
	tableList: [],  // 表格数据
	loading: false,   // 加载状态
	total: 0, // 总条数
	ApplyTypeOptions: [ // 申请类型数据
		{
			label: '新增',
			value: 0,
		},
		{
			label: '修改',
			value: 1,
		},
	],
	orgData: [],  // 组织机构数据
});
const ruleFormRef = ref<FormInstance>();  // 表单实例
// 创建时间
const timeChange = (val: string[]) => {
	if (val) {
		state.queryParams.StartTime = val[0];
		state.queryParams.EndTime = val[1];
	}
};
/** 获取我的知识申请列表 */
const queryList = throttle(() => {
	if (!auth('knowledge:myApply:query')) ElMessage.error('抱歉，您没有权限查看知识申请列表');
	else {
		state.loading = true;
		let request = other.deepClone(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;
			});
	}
}, 500);
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	state.queryParams.PageIndex = 1;
	state.queryParams.StartTime = '';
	state.queryParams.EndTime = '';
	queryList();
}, 500);
// 切换tab 查询列表
const handleClick = () => {
	queryList();
};
// 查看详情
const KnowledgeMyApplyDetailRef = ref<RefType>(); // 详情实例
const onDetail = (row: any) => {
	KnowledgeMyApplyDetailRef.value.openDialog(row);
};
// 发起申请
const KnowledgeMyApplyAddRef = ref<RefType>();  // 新增实例
const onApply = () => {
	KnowledgeMyApplyAddRef.value.openDialog(state.orgData, state.knowledgeOptions);
};
// 修改申请
const KnowledgeMyApplyEditRef = ref<RefType>(); // 修改实例
const onEdit = (row: any) => {
	KnowledgeMyApplyEditRef.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('操作成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 删除
const onDelete = (row: any) => {
	ElMessageBox.confirm(`是否确定删除该申请？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			KnowledgeRemove(row.id).then(() => {
				ElMessage.success('操作成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 页面基础数据
const getBaseData = async () => {
	try {
		const { result } = await baseData();
		state.statusOptions = result.eKnowledgeApplyStatus;
		state.eKnowledgeApplyType = result.eKnowledgeApplyType;
	} catch (error) {
		console.log(error);
	}
};
onMounted(async () => {
	queryList();
	await getBaseData();
	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>
