<template>
	<div class="auxiliary-notice-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-tabs v-model="listType" @tab-change="handleQuery">
				<el-tab-pane name="0" label="通知" :disabled="state.loading"></el-tab-pane>
				<el-tab-pane name="1" label="公告" :disabled="state.loading"></el-tab-pane>
			</el-tabs>
			<el-form :model="state.queryParams" ref="ruleFormRef" inline @submit.native.prevent class="mt10">
				<el-form-item label="标题" prop="Title">
					<el-input v-model="state.queryParams.Title" placeholder="标题" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<template v-if="listType === '0'">
					<el-form-item label="通知类型" prop="CircularTypeId">
						<el-select v-model="state.queryParams.CircularTypeId" placeholder="请选择通知类型" @change="handleQuery" clearable>
							<el-option v-for="item in circularType" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
						</el-select>
					</el-form-item>
					<el-form-item label="通知时间" prop="exTime">
						<el-date-picker
							v-model="state.queryParams.exTime"
							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>
				</template>
				<template v-if="listType === '1'">
					<el-form-item label="公告类型" prop="BulletinTypeId">
						<el-select v-model="state.queryParams.BulletinTypeId" placeholder="请选择公告类型" @change="handleQuery" clearable>
							<el-option v-for="item in bulletinType" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
						</el-select>
					</el-form-item>
					<el-form-item label="公告时间" prop="Time">
						<el-date-picker
							v-model="state.queryParams.Time"
							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>
				</template>
				<el-form-item>
					<el-button type="primary" @click="handleQuery" :loading="state.loading"> <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>
			<vxe-toolbar
				ref="toolbarRef"
				:loading="state.loading"
				custom
				:refresh="{
					queryMethod: handleQuery,
				}"
			>
				<template #buttons>
					<el-button type="primary" @click="onNoticeAdd('0')" v-if="listType === '0'" v-auth="'auxiliary:notice:add'" title="新增通知">
						<SvgIcon name="ele-Plus" class="mr5" />新增通知
					</el-button>
					<el-button type="primary" @click="onNoticeAdd('1')" v-auth="'auxiliary:bulletin:add'" title="新增公告" v-else>
						<SvgIcon name="ele-Plus" class="mr5" />新增公告
					</el-button>
				</template>
			</vxe-toolbar>
			<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
				<vxe-table
					border
					:loading="state.loading"
					: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
					:scrollY="{ enabled: true, gt: 100 }"
					id="auxiliaryNotice"
					:custom-config="{ storage: true }"
					showHeaderOverflow
				>
					<template v-if="listType === '0'">
						<vxe-column field="circularTypeName" title="通知类型" width="120"></vxe-column>
						<vxe-column field="circularStateText" title="通知状态" width="120"></vxe-column>
						<vxe-column field="title" title="通知标题" min-width="200"></vxe-column>
						<vxe-column field="isMustRead" title="必须阅读" width="100">
							<template #default="{ row }">
								{{ row.isMustRead ? '是' : '否' }}
							</template>
						</vxe-column>
						<vxe-column field="readedNum" title="已阅读数" width="100">
							<template #default="{ row }">
								<el-popover placement="right" :width="450" trigger="click" popper-class="notice-container" v-if="[2].includes(row.circularState)">
									<template #reference>
										<el-button link type="primary">{{ row.readedNum + '/' + row.needReadNum }}</el-button>
									</template>
									<div class="notice-container-box">
										<div class="notice-container-box-inner">
											已读：{{ row.readedNum }}
											<el-scrollbar class="mt5" v-if="row.circularReadGroups?.length">
												<el-tag v-for="item in row.circularReadGroups.filter((i) => i.isRead)"
													>{{ row.circularType === 1 ? item.userName : item.orgName }}
													<span v-if="item.isTimeOut" class="color-danger">(超时阅读)</span>
												</el-tag>
											</el-scrollbar>
										</div>
										<div class="notice-container-box-inner">
											未读：{{ row.needReadNum - row.readedNum }}
											<el-scrollbar class="mt5 mb10" v-if="row.circularReadGroups?.length">
												<el-tag v-for="item in row.circularReadGroups.filter((i) => !i.isRead)">{{
													row.circularType === 1 ? item.userName : item.orgName
												}}</el-tag>
											</el-scrollbar>
										</div>
									</div>
								</el-popover>
							</template>
						</vxe-column>
						<vxe-column field="circularTypeText" title="通知对象" width="100"></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="lostEfficacyTime" title="失效时间" width="160">
							<template #default="{ row }">
								{{ formatDate(row.lostEfficacyTime, 'YYYY-mm-dd HH:MM:SS') }}
							</template>
						</vxe-column>
					</template>
					<template v-if="listType === '1'">
						<vxe-column field="bulletinTypeName" title="公告类型" width="120"></vxe-column>
						<vxe-column field="bulletinStateText" title="公告状态" width="120"></vxe-column>
						<vxe-column field="title" title="公告标题" min-width="200"></vxe-column>
						<vxe-column field="readedNum" title="已阅次数" width="100"></vxe-column>
						<vxe-column field="pushRangesText" title="公告范围" width="150"></vxe-column>
						<vxe-column field="displayLocationText" 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="loseEfficacyTime" title="失效时间" width="160">
							<template #default="{ row }">
								{{ formatDate(row.loseEfficacyTime, 'YYYY-mm-dd HH:MM:SS') }}
							</template>
						</vxe-column>
					</template>
					<vxe-column field="sourceOrgName" title="来源单位" width="140"></vxe-column>
					<vxe-column field="examinOpinion" title="审核理由" min-width="150"></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 title="操作" width="200" fixed="right" :show-overflow="false" v-if="listType === '0'" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onEdit(row, '0')" v-if="[0, 3].includes(row.circularState)" v-auth="'auxiliary:bulletin:edit'">
								编辑
							</el-button>
							<el-button link type="danger" @click="onDelete(row, '0')" v-if="[0].includes(row.circularState)" v-auth="'auxiliary:bulletin:delete'">
								删除
							</el-button>
							<el-button
								link
								type="primary"
								@click="onCommit(row, '0')"
								v-if="[0, 3].includes(row.circularState)"
								title="提交审批"
								v-auth="'auxiliary:bulletin:commit'"
							>
								提交
							</el-button>
							<el-button link type="primary" @click="onDetail(row, '0')" v-if="[1, 2].includes(row.circularState)"> 查看详情 </el-button>
						</template>
					</vxe-column>
					<vxe-column title="操作" width="200" fixed="right" :show-overflow="false" v-if="listType === '1'" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onEdit(row, '1')" v-if="[0, 3].includes(row.bulletinState)" v-auth="'auxiliary:notice:edit'">
								编辑
							</el-button>
							<el-button link type="danger" @click="onDelete(row, '1')" v-if="[0].includes(row.bulletinState)" v-auth="'auxiliary:notice:delete'">
								删除
							</el-button>
							<el-button
								link
								type="primary"
								@click="onCommit(row, '1')"
								v-if="[0, 3].includes(row.bulletinState)"
								title="提交审批"
								v-auth="'auxiliary:notice:commit'"
							>
								提交
							</el-button>
							<el-button
								link
								type="primary"
								@click="onShelfFn(row, '1')"
								v-if="[2].includes(row.bulletinState) && !row.isArrive"
								v-auth="'auxiliary:notice:onShelf'"
							>
								上架
							</el-button>
							<el-button
								link
								type="primary"
								@click="offShelfFn(row, '1')"
								v-if="[2].includes(row.bulletinState) && row.isArrive"
								v-auth="'auxiliary:notice:offShelf'"
							>
								下架
							</el-button>
							<el-button link type="primary" @click="onDetail(row, '1')" v-if="[1, 2].includes(row.bulletinState)"> 查看详情 </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.loading"
			/>
		</div>
		<!-- 流程审批 -->
		<process-audit ref="processAuditRef" @orderProcessSuccess="queryList" />
		<!--  新增通知公告  -->
		<notice-add ref="noticeAddRef" @updateList="queryList" />
		<!--  编辑通知公告  -->
		<notice-edit ref="noticeEditRef" @updateList="queryList" />
	</div>
</template>

<script lang="tsx" setup name="auxiliaryNotice">
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import { formatDate } from '@/utils/formatTime';
import {
	bulletinBaseData,
	bulletinCommit,
	bulletinDelete,
	bulletinList,
	bulletinPutAway,
	circularBaseData,
	circularCommit,
	circularDelete,
	circularList,
} from '@/api/auxiliary/notice';
import Other from '@/utils/other';

// 引入组件
const ProcessAudit = defineAsyncComponent(() => import('@/components/ProcessAudit/index.vue')); // 流程审批
const NoticeAdd = defineAsyncComponent(() => import('@/views/auxiliary/notice/components/Notice-add.vue')); // 通知公告新增
const NoticeEdit = defineAsyncComponent(() => import('@/views/auxiliary/notice/components/Notice-edit.vue')); // 通知公告编辑
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页

// 定义变量内容
const state = reactive<any>({
	loading: false, // 加载状态
	queryParams: {
		// 查询参数
		PageIndex: 1,
		PageSize: 20,
		Title: null,
		BulletinTimeStart: null, // 创建时间 开始
		BulletinTimeEnd: null, // 创建时间 结束
		CircularTimeStart: null,
		CircularTimeEnd: null,
		exTime: [],
		Time: [],
		BulletinTypeId: null, //通知类型
		CircularTypeId: null,
	},
	total: 0, // 总条数
	tableData: [], // 表格数据
});
const ruleFormRef = ref<RefType>(null); // 表单ref
const bulletinType = ref<EmptyArrayType>([]); // 通知类型
const circularType = ref<EmptyArrayType>([]); // 通知类型
const listType = ref<string>('0'); // 列表类型
const getBaseData = async () => {
	try {
		const resCircularType = await circularBaseData();
		circularType.value = resCircularType.result?.circularType ?? [];
		const res = await bulletinBaseData();
		bulletinType.value = res.result.bulletinType ?? [];
	} catch (error) {
		console.log(error);
	}
};
/** 搜索按钮操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
// 获取列表
const requestParams = ref<EmptyObjectType>({});
const queryList = () => {
	state.loading = true;
	switch (listType.value) {
		case '0': //通知
			requestParams.value = Other.deepClone(state.queryParams);
			requestParams.value.CircularTimeStart = state.queryParams.exTime === null ? null : state.queryParams.exTime[0]; // 期满时间
			requestParams.value.CircularTimeEnd = state.queryParams.exTime === null ? null : state.queryParams.exTime[1];
			Reflect.deleteProperty(requestParams.value, 'exTime'); // 删除无用的参数
			circularList(requestParams.value)
				.then((res) => {
					state.loading = false;
					state.tableData = res.result.items ?? [];
					state.total = res.result.total ?? 0;
				})
				.finally(() => {
					state.loading = false;
				});
			break;
		case '1': // 公告
			requestParams.value = Other.deepClone(state.queryParams);
			requestParams.value.BulletinTimeStart = state.queryParams.Time === null ? null : state.queryParams.Time[0]; // 期满时间
			requestParams.value.BulletinTimeEnd = state.queryParams.Time === null ? null : state.queryParams.Time[1];
			Reflect.deleteProperty(requestParams.value, 'Time'); // 删除无用的参数
			bulletinList(requestParams.value)
				.then((res) => {
					state.loading = false;
					state.tableData = res.result.items ?? [];
					state.total = res.result.total ?? 0;
				})
				.finally(() => {
					state.loading = false;
				});
			break;
	}
};
// 重置表单
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
};
// 通知公告新增
const processAuditRef = ref<RefType>(); // 处理流程
const noticeAddRef = ref<RefType>(); // 通知公告新增
const onNoticeAdd = (type: string) => {
	const processType = type === '0' ? '新增通知' : '新增公告';
	noticeAddRef.value.openDialog(processType);
};
// 查看详情
const router = useRouter();
const onDetail = (row: any, type: string) => {
	const tagsViewName = type === '0' ? '通知详情' : '公告详情';
	router.push({
		name: 'auxiliaryNoticeDetail',
		params: {
			id: row.id,
			tagsViewName,
		},
	});
};
// 编辑
const noticeEditRef = ref<RefType>(); // 通知公告编辑
const onEdit = (row: any, type: string) => {
	noticeEditRef.value.openDialog(row, type === '0' ? '编辑通知' : '编辑公告');
};
// 删除
const onDelete = (row: any, type: string) => {
	ElMessageBox.confirm(`您确定要删除：【${row.title}】，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			if (type === '0') {
				circularDelete(row.id).then(() => {
					ElMessage.success('操作成功');
					queryList();
				});
			} else {
				bulletinDelete(row.id).then(() => {
					ElMessage.success('操作成功');
					queryList();
				});
			}
		})
		.catch(() => {});
};
// 提交
const onCommit = (row: any, type: string) => {
	ElMessageBox.confirm(`您确定要提交：【${row.title}】，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			if (type === '0') {
				circularCommit(row.id).then(() => {
					ElMessage.success('操作成功');
					queryList();
				});
			} else {
				bulletinCommit(row.id).then(() => {
					ElMessage.success('操作成功');
					queryList();
				});
			}
		})
		.catch(() => {});
};
// 上架
const onShelfFn = (row: any, type: string) => {
	ElMessageBox.confirm(`您确定要上架：【${row.title}】，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			if (type === '0') {
			} else {
				bulletinPutAway({ id: row.id, isArrive: true }).then(() => {
					ElMessage.success('操作成功');
					queryList();
				});
			}
		})
		.catch(() => {});
};
// 下架
const offShelfFn = (row: any, type: string) => {
	ElMessageBox.confirm(`您确定要下架：【${row.title}】，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			if (type === '0') {
			} else {
				bulletinPutAway({ id: row.id, isArrive: false }).then(() => {
					ElMessage.success('操作成功');
					queryList();
				});
			}
		})
		.catch(() => {});
};
const toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
// 页面加载时
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
	getBaseData();
});
</script>
