<template>
	<div class="case-index-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<splitpanes class="h100" :horizontal="horizontal">
				<pane min-size="16" max-size="25" size="16">
					<el-scrollbar ref="scrollBarRef" noresiz>
						<el-skeleton :loading="state.typeLoading" animated :rows="10">
							<template #default>
								<v-tree-search
									:data="state.typeOptions"
									titleField="name"
									keyField="id"
									selectable
									searchPlaceholder="案例分类名称"
									@select="selectType"
									@unselect="unSelectType"
									ref="treeSearchRef"
								>
									<template #node="{ node }">
										<span>{{ node.name }}</span>
									</template>
								</v-tree-search>
							</template>
						</el-skeleton>
					</el-scrollbar>
				</pane>
				<pane class="h100" style="display: flex; flex: 1; flex-direction: column">
					<el-tabs v-model="state.queryParams.Status" @tab-change="handleClick" v-loading="state.loading">
						<el-tab-pane :label="v.value" :name="v.key" v-for="(v, i) in state.statusOptions" :key="i" :disabled="state.tableLoading"></el-tab-pane>
					</el-tabs>
					<el-form :model="state.queryParams" ref="ruleFormRef" inline @submit.native.prevent :disabled="state.tableLoading">
						<el-form-item label="标题" prop="Title">
							<el-input v-model="state.queryParams.Title" placeholder="标题" clearable @keyup.enter="handleQuery" class="keyword-input" />
						</el-form-item>
						<el-form-item label="创建时间" prop="cjTime">
							<el-date-picker
								v-model="state.queryParams.cjTime"
								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 label="" prop="IsPopular">
							<el-checkbox v-model="state.queryParams.IsPopular" border @change="handleQuery">热门案例</el-checkbox>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="handleQuery" :loading="state.tableLoading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
<!--							<el-button @click="drawer = true" class="default-button"> <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.tableLoading"
						custom
						:refresh="{
							queryMethod: handleQuery,
						}"
						:tools="[{ toolRender: { name: 'exportCurrent' } }, { toolRender: { name: 'exportAll' } }]"
					>
						<template #buttons>
							<el-button type="primary" @click="onAdd" v-auth="'case:index:add'" :loading="state.tableLoading">
								<SvgIcon name="ele-Plus" class="mr5" />创建案例
							</el-button>
							<el-dropdown v-auth="'case:index:export:detail'" @command="onExportDetail" class="ml12 mr12" :disabled="isChecked">
								<el-button type="primary" :disabled="isChecked" :loading="state.tableLoading">
									导出案例详情<SvgIcon name="ele-ArrowDown" class="ml3" />
								</el-button>
								<template #dropdown>
									<el-dropdown-menu>
										<el-dropdown-item :command="item.key" v-for="item in exportType" :key="item.key">{{ item.value }}</el-dropdown-item>
									</el-dropdown-menu>
								</template>
							</el-dropdown>
							<el-button type="primary" :disabled="isChecked" :loading="state.tableLoading" v-auth="'case:index:hot'" @click="setHot">
								设为热门案例
							</el-button>
							<el-button type="primary" :disabled="isChecked" :loading="state.tableLoading" v-auth="'case:index:unHot'" @click="cancelHot">
								取消热门案例
							</el-button>
						</template>
					</vxe-toolbar>
					<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
						<vxe-table
							border
							:loading="state.tableLoading"
							: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
							:print-config="{}"
							:scrollY="{ enabled: true, gt: 100 }"
							id="caseManage"
							:custom-config="{ storage: true }"
							showHeaderOverflow
							:params="{ exportMethod: getCaseExport, exportParams: requestParams }"
							@checkbox-all="selectAllChangeEvent"
							@checkbox-change="selectChangeEvent"
						>
							<vxe-column type="checkbox" width="50" align="center"></vxe-column>
							<vxe-column field="title" title="标题" min-width="200">
								<template #default="{ row }">
									<el-button link type="primary" @click="onPreview(row)">{{ row.title }}</el-button>
								</template>
							</vxe-column>
							<vxe-column field="caseTypeText" title="案例分类" width="150"></vxe-column>
							<vxe-column field="orderTitle" title="关联工单" width="160">
								<template #default="{ row }">
									<order-detail :order="{ id: row.orderId }">{{ row.orderTitle }}</order-detail>
								</template>
							</vxe-column>
							<vxe-column field="knowledgeTitle" title="关联知识" width="160">
								<template #default="{ row }">
									<el-button link type="primary" @click="onPreviewKnowledge(row)">{{ row.knowledgeTitle }}</el-button>
								</template>
							</vxe-column>
							<vxe-column field="keywords" title="关键词" width="150"></vxe-column>
							<vxe-column field="statusName" title="案例状态" width="110"></vxe-column>
							<vxe-column field="pageView" title="阅读次数" width="100"></vxe-column>
							<vxe-column field="onShelfTime" title="上架时间" width="160">
								<template #default="{ row }">
									{{ formatDate(row.onShelfTime, 'YYYY-mm-dd HH:MM:SS') }}
								</template>
							</vxe-column>
							<vxe-column field="offShelfTime" title="下架时间" width="160">
								<template #default="{ row }">
									{{ formatDate(row.offShelfTime, 'YYYY-mm-dd HH:MM:SS') }}
								</template>
							</vxe-column>
							<vxe-column field="expiredTime" title="到期时间" width="160">
								<template #default="{ row }">
									{{ formatDate(row.expiredTime, 'YYYY-mm-dd HH:MM:SS') }}
								</template>
							</vxe-column>
							<vxe-column field="creatorName" title="创建人" width="120"></vxe-column>
							<vxe-column field="creatorOrgName" title="创建部门" width="150"></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 field="examinMan.name" title="审批人" width="120"></vxe-column>
							<vxe-column field="examinTime" title="审批时间" width="160">
								<template #default="{ row }">
									{{ formatDate(row.examinTime, 'YYYY-mm-dd HH:MM:SS') }}
								</template>
							</vxe-column>
							<vxe-column field="examinOpinion" title="审批意见" width="200"></vxe-column>
							<vxe-column title="操作" fixed="right" width="150" align="center" :show-overflow="false">
								<template #default="{ row }">
									<el-button link type="primary" @click="onEdit(row)" title="编辑" v-auth="'case:index:edit'" v-if="[4, 7, 5].includes(row.status)">
										编辑
									</el-button>
									<el-button
										link
										type="danger"
										@click="onRowDel(row)"
										title="删除"
										v-auth="'case:index:delete'"
										v-if="[4, 7, 5].includes(row.status)"
									>
										删除
									</el-button>
									<el-button
										link
										type="primary"
										@click="offShelfFn(row)"
										title="下架"
										v-auth="'case:index:undercarriage'"
										v-if="[3].includes(row.status)"
									>
										下架
									</el-button>
									<el-button
										link
										type="primary"
										@click="groundingFn(row)"
										title="上架"
										v-auth="'case:index:grounding'"
										v-if="[4].includes(row.status)"
									>
										上架
									</el-button>
									<el-button link type="primary" @click="onAudit(row)" title="审批" v-if="[1].includes(row.status)" v-auth="'case:index:audit'">
										审批
									</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.tableLoading"
					/>
				</pane>
			</splitpanes>
		</div>
		<!--	更多查询	-->
		<el-drawer v-model="drawer" title="更多查询" size="500px">
			<el-form :model="state.queryParams" ref="drawerRuleFormRef" @submit.native.prevent label-width="100px">
				<el-form-item label="上架时间" prop="sjTime">
					<el-date-picker
						v-model="state.queryParams.sjTime"
						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 label="下架时间" prop="xjTime">
					<el-date-picker
						v-model="state.queryParams.xjTime"
						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 label="更新时间" prop="gxTime">
					<el-date-picker
						v-model="state.queryParams.gxTime"
						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>
			<template #footer>
				<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
				<el-button @click="resetQuery(drawerRuleFormRef)" class="default-button"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
			</template>
		</el-drawer>
		<!-- 流程审批 -->
		<process-audit ref="processAuditRef" @orderProcessSuccess="queryList" />
		<!-- 审核记录 -->
		<audit-progress ref="auditProgressRef" />
		<!-- 批量审批 -->
		<to-end ref="toEndRef" @updateList="queryList" />
		<!-- 删除或者更新提交审核 -->
		<case-audit ref="caseAuditRef" @updateList="handleQuery" />
		<!-- 删除或者更新提交审核 -->
		<edit-submit-audit ref="editSubmitAuditRef" @updateList="handleQuery" />
	</div>
</template>

<script lang="tsx" setup name="caseManage">
import { ref, reactive, onMounted, defineAsyncComponent, computed } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import type { FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';
import Other from '@/utils/other';
import { downloadFileByStream } from '@/utils/tools';
import { VxeUI } from 'vxe-pc-ui';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import { VTreeSearch } from '@wsfe/vue-tree';
import { caseTreeList } from '@/api/case/type';
import { caseDetailExport, caseHot, caseOffShelf, caseOnShelf, getCaseBaseData, getCaseExport, getCaseList } from '@/api/case';

// 引入组件
const ProcessAudit = defineAsyncComponent(() => import('@/components/ProcessAudit/index.vue')); // 流程审批
const AuditProgress = defineAsyncComponent(() => import('@/views/knowledge/components/Audit-progress.vue')); // 编写规范
const ToEnd = defineAsyncComponent(() => import('@/views/knowledge/index/components/To-end.vue')); // 批量审批
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页
const CaseAudit = defineAsyncComponent(() => import('@/views/case/index/components/Case-audit.vue')); // 审批新增 修改 删除
const EditSubmitAudit = defineAsyncComponent(() => import('@/views/case/index/components/Edit-submit-audit.vue')); // 删除或者更新 提交审核
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情

const router = useRouter(); //路由
const horizontal = ref(false);

// 定义变量内容
const state = reactive<any>({
	queryParams: {
		PageIndex: 1, //页码
		PageSize: 20, //每页条数
		Keyword: null, //关键字
		Status: 3, //状态 默认已上架
		Title: null, //标题
		sjTime: [], // 上架时间
		StartOnShelfTime: null,
		EndOnShelfTime: null,
		xjTime: [], // 下架时间
		StartOffShelfTime: null,
		EndOffShelfTime: null,
		cjTime: [], // 创建时间
		CreationTimeStart: null,
		CreationTimeEnd: null,
		gxTime: [], // 更新时间
		StartUpdateTime: null,
		EndUpdateTime: null,
		IsPopular: null, // 是否热门
	},
	activeName: '1', //tab切换 默认案例分类
	tableData: [], //表格数据
	total: 0, //总条数
	loading: false, //表格loading
	tableLoading: false, //表格loading
	typeOptions: [], // 类型数据
	statusOptions: [], //状态数据
	typeLoading: false, // 类型loading
});
// 切换tab 查询列表
const handleClick = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
/** 搜索按钮操作 节流操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
// 获取案例分类
const getCaseType = async () => {
	state.typeLoading = true;
	try {
		const { result } = await caseTreeList({ IsEnable: true });
		state.typeOptions = result ?? [];
		state.typeLoading = false;
	} catch (error) {
		state.typeLoading = false;
	}
};
const exportType = ref<EmptyArrayType>([]);
const getBaseDataFn = async () => {
	try {
		const { result } = await getCaseBaseData();
		state.statusOptions = result?.tabStatusName ?? []; // 列表状态
		exportType.value = result?.fileType ?? []; // 导出文件类型
		state.loading = false;
	} catch (error) {
		state.loading = false;
	}
};
/** 获取列表 */
const requestParams = ref<EmptyObjectType>({});
const queryList = () => {
	state.tableLoading = true;
	requestParams.value = Other.deepClone(state.queryParams);
	requestParams.value.StartOnShelfTime = state.queryParams.sjTime === null ? null : state.queryParams.sjTime[0]; // 上架时间
	requestParams.value.EndOnShelfTime = state.queryParams.sjTime === null ? null : state.queryParams.sjTime[1];
	Reflect.deleteProperty(requestParams.value, 'sjTime'); // 删除无用的参数
	requestParams.value.StartOffShelfTime = state.queryParams.xjTime === null ? null : state.queryParams.xjTime[0]; // 受理时间
	requestParams.value.EndOffShelfTime = state.queryParams.xjTime === null ? null : state.queryParams.xjTime[1]; //下架时间
	Reflect.deleteProperty(requestParams.value, 'xjTime'); // 删除无用的参数
	requestParams.value.CreationTimeStart = state.queryParams.cjTime === null ? null : state.queryParams.cjTime[0]; // 创建时间
	requestParams.value.CreationTimeEnd = state.queryParams.cjTime === null ? null : state.queryParams.cjTime[1];
	Reflect.deleteProperty(requestParams.value, 'cjTime'); // 删除无用的参数
	requestParams.value.StartUpdateTime = state.queryParams.gxTime === null ? null : state.queryParams.gxTime[0]; // 更新时间
	requestParams.value.EndUpdateTime = state.queryParams.gxTime === null ? null : state.queryParams.gxTime[1];
	Reflect.deleteProperty(requestParams.value, 'gxTime'); // 删除无用的参数
	getCaseList(requestParams.value)
		.then((response: any) => {
			state.tableData = response?.result.items ?? [];
			state.total = response?.result.total;
			tableRef.value.clearCheckboxRow();
			checkTable.value = [];
			state.tableLoading = false;
		})
		.catch(() => {
			tableRef.value.clearCheckboxRow();
			checkTable.value = [];
			state.tableLoading = false;
		});
};
// 选择分类
const selectType = (data: any) => {
	state.queryParams.CaseTypeID = data.id;
	handleQuery();
};
// 取消选择
const unSelectType = () => {
	state.queryParams.CaseTypeID = null;
	handleQuery();
};
/** 重置按钮操作 */
const drawerRuleFormRef = ref();
const ruleFormRef = ref<RefType>(); // 表单ref
const drawer = ref(false);
const treeSearchRef = ref<RefType>();
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	ruleFormRef.value?.resetFields();
	treeSearchRef.value.setSelected(state.queryParams.OrgCode, false); // 清空选择
	treeSearchRef.value.clearKeyword(); // 清空搜索关键词
	treeSearchRef.value.search(); // 搜索
	resetNode();
	setTimeout(() => {
		treeSearchRef.value.setExpandAll(false); // 默认全部收起
	}, 300);
};
// 重置选中的节点
const resetNode = () => {
	state.queryParams.CaseTypeID = null;
	handleQuery();
};
// 新增案例
const onAdd = () => {
	router.push({
		name: 'caseEdit',
		params: {
			tagsViewName: '新增案例',
		},
	});
};
// 修改
const onEdit = (row: any) => {
	router.push({
		name: 'caseEdit',
		params: {
			id: row.id,
			tagsViewName: '编辑案例',
		},
	});
};
// 预览
const onPreview = (row: any) => {
	router.push({
		name: 'casePreview',
		params: {
			id: row.id,
			tagsViewName: row.title,
		},
	});
};
// 预览知识库
const onPreviewKnowledge = (row: any) => {
	router.push({
		name: 'knowledgePreview',
		params: {
			id: row.knowledgeId,
			tagsViewName: row.knowledgeTitle,
		},
	});
};
// 审批
const caseAuditRef = ref<RefType>();
const onAudit = (row: any) => {
	caseAuditRef.value.openDialog(row);
};
// 下架
const offShelfFn = (row: any) => {
	ElMessageBox.confirm(`是否确定要下架【${row.title}】？，案例下架后，将不会被检索到！`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			caseOffShelf(row.id).then(() => {
				ElMessage.success('下架成功');
				handleQuery();
			});
		})
		.catch(() => {});
};
// 上架
const groundingFn = (row: any) => {
	ElMessageBox.confirm(`是否确定要上架【${row.title}】？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			caseOnShelf(row.id).then(() => {
				ElMessage.success('上架成功');
				handleQuery();
			});
		})
		.catch(() => {});
};
// 删除案例
const editSubmitAuditRef = ref<RefType>();
const onRowDel = (row: any) => {
	editSubmitAuditRef.value.openDialog(row, 'delete');
};
// 导出详情
const onExportDetail = (command: string | number | object) => {
	state.loading = true;
	const ids = checkTable.value.map((item: any) => item.id);
	VxeUI.modal.message({
		content: `导出中，请稍等`,
		status: 'loading',
		id: 'exportDetail',
		duration: -1,
	});
	caseDetailExport({ ids, fileType: command })
		.then((res: any) => {
			downloadFileByStream(res);
			state.loading = false;
			VxeUI.modal.close('exportDetail');
			VxeUI.modal.message({
				content: `导出成功`,
				status: 'success',
			});
		})
		.catch((e) => {
			console.log(e, '导出错误');
			state.loading = false;
			VxeUI.modal.close('exportDetail');
			VxeUI.modal.message({
				content: `导出失败`,
				status: 'error',
			});
		});
};
const tableRef = ref<RefType>();
const checkTable = ref<EmptyArrayType>([]);
const selectAllChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '所有勾选事件' : '所有取消事件', records);
	}
};

const selectChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '勾选事件' : '取消事件', records);
	}
};
const isChecked = computed(() => {
	return !Boolean(checkTable.value.length);
});
const toolbarRef = ref<RefType>();

// 设置热门
const setHot = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	ElMessageBox.confirm(`确定要将选中的案例设置热门？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			caseHot({ ids: ids, Popular: true })
				.then(() => {
					ElMessage.success('设置成功');
					handleQuery();
				})
				.catch((e) => {
					console.log(e);
				});
		})
		.catch(() => {});
};
// 取消热门
const cancelHot = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	ElMessageBox.confirm(`确定要将选中的案例取消热门？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			caseHot({ ids: ids, Popular: false })
				.then(() => {
					ElMessage.success('设置成功');
					handleQuery();
				})
				.catch((e) => {
					console.log(e);
				});
		})
		.catch(() => {});
};
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
	getBaseDataFn();
	getCaseType();
});
</script>
