<template>
	<div class="auxiliary-notice-container layout-pd">
		<el-card shadow="never">
			<el-tabs v-model="listType" @tab-change="queryList">
				<el-tab-pane name="0" label="通知"></el-tab-pane>
				<el-tab-pane name="1" label="公告"></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="queryList" 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="请选择通知类型">
							<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="timeStartChangeCr"
							value-format="YYYY-MM-DD[T]HH:mm:ss"
						/>
					</el-form-item>
				</template>
				<template v-else>
					<el-form-item label="公告类型" prop="BulletinTypeId">
						<el-select v-model="state.queryParams.BulletinTypeId" placeholder="请选择公告类型">
							<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="timeStartChange"
							value-format="YYYY-MM-DD[T]HH:mm:ss"
						/>
					</el-form-item>
				</template>
				<el-form-item>
					<el-button type="primary" @click="queryList" :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>
			<!--   通知表格   -->
			<ProTable
				ref="proTableNoticeRef"
				:columns="columnsNotice"
				:data="state.tableData"
				@updateTable="queryList"
				:loading="state.loading"
				:total="state.total"
				v-model:page-index="state.queryParams.PageIndex"
				v-model:page-size="state.queryParams.PageSize"
				v-if="listType === '0'"
			>
				<!-- 表格 header 按钮 -->
				<template #tableHeader="scope">
					<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>
				</template>
				<template #isProvince="{ row }">
					<span>{{ row.isProvince ? '省工单' : '市工单' }}</span>
				</template>
				<template #isMustRead="{ row }">
					{{ row.isMustRead ? '是' : '否' }}
				</template>
				<template #readedNum="{ 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>
				<!-- 表格操作 -->
				<template #operation="{ 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>
			</ProTable>
			<!--   公告表格   -->
			<ProTable
				ref="proTableBulletinRef"
				:columns="columnsBulletin"
				:data="state.tableData"
				@updateTable="queryList"
				:loading="state.loading"
				:total="state.total"
				v-model:page-index="state.queryParams.PageIndex"
				v-model:page-size="state.queryParams.PageSize"
				v-else
			>
				<!-- 表格 header 按钮 -->
				<template #tableHeader="scope">
					<el-button type="primary" @click="onNoticeAdd('1')" v-auth="'auxiliary:bulletin:add'" title="新增公告">
						<SvgIcon name="ele-Plus" class="mr5" />新增
					</el-button>
				</template>
				<!-- 表格操作 -->
				<template #operation="{ 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="onDetail(row, '1')" v-if="[1, 2].includes(row.bulletinState)"> 查看详情 </el-button>
				</template>
			</ProTable>
		</el-card>
		<!-- 流程审批 -->
		<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, onActivated, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElButton, ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { shortcuts } from '@/utils/constants';
import { formatDate } from '@/utils/formatTime';
import {
	bulletinBaseData,
	bulletinCommit,
	bulletinDelete,
	bulletinList,
	circularBaseData,
	circularCommit,
	circularDelete,
	circularList,
} from '@/api/auxiliary/notice';

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

const proTableNoticeRef = ref<RefType>(); // 表格ref
// 表格配置项
const columnsNotice = ref<any[]>([
	{ prop: 'circularTypeName', label: '通知类型', width: 120 },
	{ prop: 'circularStateText', label: '通知状态', width: 120 },
	{ prop: 'title', label: '通知标题', width: 150 },
	{ prop: 'isMustRead', label: '必须阅读' },
	{ prop: 'readedNum', label: '已阅读数' },
	{ prop: 'circularTypeText', label: '通知对象' },
	{
		prop: 'creationTime',
		label: '通知时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.creationTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{
		prop: 'lostEfficacyTime',
		label: '失效时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.lostEfficacyTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{ prop: 'sourceOrgName', label: '来源单位', width: 120 },
	{ prop: 'circularStateText', label: '审核状态', width: 120 },
	{ prop: 'examinOpinion', label: '审核理由', width: 150 },
	{ prop: 'examinMan.name', label: '审核人' },
	{
		prop: 'examinTime',
		label: '审核时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.examinTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 200, align: 'center' },
]);
const proTableBulletinRef = ref<RefType>(); // 表格ref
// 表格配置项
const columnsBulletin = ref<any[]>([
	{ prop: 'bulletinTypeName', label: '公告类型', width: 120 },
	{ prop: 'bulletinStateText', label: '公告状态', width: 120 },
	{ prop: 'title', label: '公告标题', width: 150 },
	{ prop: 'readedNum', label: '已阅次数' },
	{ prop: 'pushRangesText', label: '公告范围', width: 300 },
	{
		prop: 'creationTime',
		label: '通知时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.creationTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{
		prop: 'loseEfficacyTime',
		label: '失效时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.loseEfficacyTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{ prop: 'creatorOrgName', label: '来源单位', width: 120 },
	{ prop: 'bulletinStateText', label: '审核状态', width: 120 },
	{ prop: 'examinOpinion', label: '审核理由', width: 150 },
	{ prop: 'examinMan.name', label: '审核人' },
	{
		prop: 'examinTime',
		label: '审核时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.examinTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 200, align: 'center' },
]);
// 定义变量内容
const state = reactive({
	loading: false, // 加载状态
	queryParams: {
		// 查询参数
		PageIndex: 1,
		PageSize: 10,
		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 handleTimeChange = (val: string[], startKey: string, endKey: string) => {
	if (val) {
		state.queryParams[startKey] = val[0];
		state.queryParams[endKey] = val[1];
	} else {
		state.queryParams[startKey] = '';
		state.queryParams[endKey] = '';
	}
	queryList();
};
// 甄别时间
const timeStartChangeCr = (val: string[]) => {
	handleTimeChange(val, 'CircularTimeStart', 'CircularTimeEnd');
};
const timeStartChange = (val: string[]) => {
	handleTimeChange(val, 'BulletinTimeStart', 'BulletinTimeEnd');
};
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 queryList = () => {
	state.loading = true;
	switch (listType.value) {
		case '0': //通知
			const requestCircular = {
				title: state.queryParams.Title,
				CircularTypeId: state.queryParams.CircularTypeId,
				CircularTimeStart: state.queryParams.CircularTimeStart,
				CircularTimeEnd: state.queryParams.CircularTimeEnd,
				PageIndex: state.queryParams.PageIndex,
				PageSize: state.queryParams.PageSize,
			};
			circularList(requestCircular)
				.then((res) => {
					state.loading = false;
					state.tableData = res.result.items ?? [];
					state.total = res.result.total ?? 0;
				})
				.finally(() => {
					state.loading = false;
				});
			break;
		case '1': // 公告
			const requestBulletin = {
				title: state.queryParams.Title,
				BulletinTypeId: state.queryParams.BulletinTypeId,
				BulletinTimeStart: state.queryParams.BulletinTimeStart,
				BulletinTimeEnd: state.queryParams.BulletinTimeEnd,
				PageIndex: state.queryParams.PageIndex,
				PageSize: state.queryParams.PageSize,
			};
			bulletinList(requestBulletin)
				.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();
	state.queryParams.BulletinTimeStart = null;
	state.queryParams.BulletinTimeEnd = null;
	state.queryParams.CircularTimeStart = null;
	state.queryParams.CircularTimeEnd = null;
	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,
			isRead: 0,
			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 params = history.state;
// 页面加载时
onMounted(() => {
	getBaseData();
	if (params.index) {
		listType.value = params.index as string;
	}
	queryList();
});
onActivated(() => {
	if (params.index) {
		listType.value = params.index as string;
	}
});
</script>
