<template>
	<div class="plan-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>
							<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="'plan:index:add'" :loading="state.tableLoading">
								<SvgIcon name="ele-Plus" class="mr5" />创建预案
							</el-button>
							<el-dropdown v-auth="'plan: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>
						</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="planManage"
							:custom-config="{ storage: true }"
							showHeaderOverflow
							:params="{ exportMethod: getPlanExport, 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="planTypeText" title="预案分类" width="150"></vxe-column>
							<vxe-column field="statusName" title="预案状态" width="110"></vxe-column>
<!--							<vxe-column field="isPublic" title="是否公开" width="100">
								<template #default="{ row }">
									{{ row.isPublic ? '是' : '否' }}
								</template>
							</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="'plan:index:edit'" v-if="[4, 7, 5].includes(row.status)">
										编辑
									</el-button>
									<el-button
										link
										type="danger"
										@click="onRowDel(row)"
										title="删除"
										v-auth="'plan:index:delete'"
										v-if="[4, 7, 5].includes(row.status)"
									>
										删除
									</el-button>
									<el-button
										link
										type="primary"
										@click="offShelfFn(row)"
										title="下架"
										v-auth="'plan:index:undercarriage'"
										v-if="[3].includes(row.status)"
									>
										下架
									</el-button>
									<el-button
										link
										type="primary"
										@click="groundingFn(row)"
										title="上架"
										v-auth="'plan: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="'plan: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>
		<!-- 审核记录 -->
		<audit-progress ref="auditProgressRef" />
		<!-- 批量审批 -->
		<to-end ref="toEndRef" @updateList="queryList" />
		<!-- 删除或者更新提交审核 -->
		<plan-audit ref="planAuditRef" @updateList="handleQuery" />
		<!-- 删除或者更新提交审核 -->
		<edit-submit-audit ref="editSubmitAuditRef" @updateList="handleQuery" />
	</div>
</template>

<script lang="tsx" setup name="planManage">
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 { getPlanBaseData, getPlanExport, getPlanList, planDetailExport, planOffShelf, planOnShelf } from '@/api/plan';
import { VTreeSearch } from '@wsfe/vue-tree';
import { planTreeList } from '@/api/plan/type';

// 引入组件
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 PlanAudit = defineAsyncComponent(() => import('@/views/plan/index/components/Plan-audit.vue')); // 审批新增 修改 删除
const EditSubmitAudit = defineAsyncComponent(() => import('@/views/plan/index/components/Edit-submit-audit.vue')); // 删除或者更新 提交审核

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

// 定义变量内容
const state = reactive<any>({
	queryParams: {
		PageIndex: 1, //页码
		PageSize: 20, //每页条数
		Keyword: null, //关键字
		Status: 3, //状态 默认已上架
		Title: null, //标题
		Attribution: '中心预案库',
		sjTime: [], // 上架时间
		StartOnShelfTime: null,
		EndOnShelfTime: null,
		xjTime: [], // 下架时间
		StartOffShelfTime: null,
		EndOffShelfTime: null,
		cjTime: [], // 创建时间
		CreationTimeStart: null,
		CreationTimeEnd: null,
		gxTime: [], // 更新时间
		StartUpdateTime: null,
		EndUpdateTime: 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 getPlanType = async () => {
	state.typeLoading = true;
	try {
		const { result } = await planTreeList({ IsEnable: true });
		state.typeOptions = result ?? [];
		state.typeLoading = false;
	} catch (error) {
		state.typeLoading = false;
	}
};
const exportType = ref<EmptyArrayType>([]);
const getBaseDataFn = async () => {
	try {
		const { result } = await getPlanBaseData();
		state.statusOptions = result?.tabStatusName ?? []; // 列表状态
		exportType.value = result?.fileType ?? []; // 导出文件类型
		state.tabNewDraftsNames = result?.tabNewDraftsNames.map((item: any) => {
			return {
				label: item.value,
				value: item.key,
			};
		});
		state.tabAuditingNames = result?.tabAuditingNames.map((item: any) => {
			return {
				label: item.value,
				value: item.key,
			};
		});
		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'); // 删除无用的参数
	getPlanList(requestParams.value)
		.then((response: any) => {
			state.tableData = response?.result.items ?? [];
			state.total = response?.result.total;
			state.tableLoading = false;
		})
		.catch(() => {
			state.tableLoading = false;
		});
};
// 选择分类
const selectType = (data: any) => {
	state.queryParams.PlanTypeID = data.id;
	handleQuery();
};
// 取消选择
const unSelectType = () => {
	state.queryParams.PlanTypeID = 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.PlanTypeID = null;
	handleQuery();
};
// 新增预案
const onAdd = () => {
	router.push({
		name: 'planEdit',
		params: {
			tagsViewName: '新增预案',
		},
	});
};
// 修改
const onEdit = (row: any) => {
	router.push({
		name: 'planEdit',
		params: {
			id: row.id,
			tagsViewName: '编辑预案',
		},
	});
};
// 预览
const onPreview = (row: any) => {
	router.push({
		name: 'planPreview',
		params: {
			id: row.id,
			tagsViewName: row.title,
		},
	});
};
// 审批
const planAuditRef = ref<RefType>();
const onAudit = (row: any) => {
	planAuditRef.value.openDialog(row);
};
// 下架
const offShelfFn = (row: any) => {
	ElMessageBox.confirm(`是否确定要下架【${row.title}】？，预案下架后，将不会被检索到！`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			planOffShelf(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(() => {
			planOnShelf(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,
	});
	planDetailExport({ ids, fileType: command })
		.then((res) => {
			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>();
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
	getBaseDataFn();
	getPlanType();
});
</script>
