<template>
	<page-meta root-font-size="system" />
	<view class="index_container">
		<uni-nav-bar dark :border="false" :fixed="true" :title="config.companyName">
		</uni-nav-bar>
		<!-- 待办消息列表 -->
		<uni-collapse :accordion="true">
			<uni-collapse-item title-border="show" :border="true" :show-animation="true"
				:open="unProcessNum > 0 || false">
				<template v-slot:title>
					<uni-section title="待办" type="line" titleFontSize="1.3rem">
						<template v-slot:right>
							<uni-badge :text="unProcessNum" class="unReadBadge" v-if="unProcessNum > 0"></uni-badge>
						</template>
					</uni-section>
				</template>
				<view class="process_container">
					<view class="process_list">
						<process-list ref="processListRef" @clickSegment="getProcessData"
							@clickItem="handleToProcessDetail" @scrollToBottom="getProcessPage" :current="0" :pSize="5"
							:pageNo="1" contentHeight="63.5vh"></process-list>
					</view>
				</view>
			</uni-collapse-item>
			<!-- 公告列表  -->
			<uni-collapse-item title-border="show" :border="true" :show-animation="true"
				:open="unReadMsgNum > 0 || false">
				<template v-slot:title>
					<uni-section title="公告" type="line" titleFontSize="1.3rem">
					</uni-section>
				</template>
				<view class="notice_list">
					<message-list @clickSegment="getNoticeData" @clickItem="handleToNoticeDetail"
						@scrollToBottom="getNoticePage" :pSize="5" :pageNo="1" :anime="true"
						:open="false"></message-list>
				</view>
			</uni-collapse-item>
			<!-- 消息列表 -->
			<uni-collapse-item title-border="show" :border="true" :show-animation="true"
				:open="unReadMsgNum > 0 || false">
				<template v-slot:title>
					<uni-section title="消息" type="line" titleFontSize="1.3rem">
						<template v-slot:right>
							<uni-badge :text="unReadMsgNum"
								v-if="unReadMsgNum !== undefined && unReadMsgNum > 0"></uni-badge>
							<button @click.stop="setAllMsgRead" class="read_button" v-if="unReadMsgNum !== undefined" :disabled="unReadMsgNum === 0">一键阅读</button>
						</template>
					</uni-section>
				</template>
				<view class="message_list">
					<message-list ref="msgListRef" @clickSegment="getMessageData" @clickItem="handleToMessageDetail"
						@scrollToBottom="getMessagePage" :defaultCurrent="1" :pSize="5" :pageNo="1"
						:segments="{ '全部': '', '未读': '0', '已读': '1' }"></message-list>
				</view>
			</uni-collapse-item>
		</uni-collapse>
		<!-- 跳转打卡页按钮 -->
		<view class="fab_button">
			<view class="toClockInBtn">
				<uni-fab :pattern="{ icon: 'map-pin-ellipse' }" :popMenu="false" horizontal="right"
					@fabClick="toClockInBtn"></uni-fab>
			</view>
			<!-- AI咨询按钮 -->
			<view class="toAiBtn">
				<uni-fab :pattern="{ buttonText: 'headphones' }" :popMenu="false" horizontal="right" @fabClick="clickFabButton"></uni-fab>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { onBeforeMount, onMounted, onUpdated, ref } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app'
import { getMessageList, getNoticeList, getUnReadMessageNum, setMsgIsRead } from '@/api/message.js';
import { getUserProcess, getUnProcessNum, getTacheInfo } from '@/api/process';
import $tab from '@/plugins/tab.js';
import $modal from '@/plugins/modal.js';
import processList from '@/components/ygoa/processList.vue'
import messageList from '@/components/ygoa/messageList.vue'
import { useUserStore } from '@/store/user.js'
import { getLoginInfo } from '@/utils/auth';
import config from '@/config';

const userStore = useUserStore()

const processListRef = ref(null)
onMounted(() => {
	uni.$on('showTabBarBadge', showTabBarBadge)
	uni.$on('ReloadProcessData', () => {
		new Promise((resolve, reject) => {
			processListRef.value.onClickItem()
		})
	})
})
onLoad((options) => {
	// 是否跳转打卡页
	if (options.to == 'clockIn'){
		toClockIn()
	}else if(options.noticeId){
		$tab.navigateTo('/pages/message/detail/index?noticeId=' + options.noticeId)
	}
})
onShow(() => {
	showTabBarBadge();
})
onBeforeMount(() => {
	uni.removeTabBarBadge({
		index: 0
	})
})

// 跳转打卡页
function toClockIn() {
	// 确认是否跳转打卡页
	$modal.confirm('当前未打卡，是否前往打卡').then(() => {
		$tab.navigateTo('/pages/mine/clockIn/clockIn')
	}).catch(() => { })
}

//子组件
const msgListRef = ref(null)

// 获取待办消息列表数据
function getProcessData({ pSize, pageNo }, callback) {
	const params = {
		staffId: userStore.user.useId,
		page: pageNo,
		pageNum: pSize,
		modelId: "",
		control: 1
	}
	getUserProcess(params).then(({ returnParams }) => {
		callback(returnParams.list, returnParams.total, pageNo)
	});
}
// 分页获取待办消息列表数据
function getProcessPage({ pSize, pageNo }, callback) {
	const params = {
		staffId: userStore.user.useId,
		page: pageNo,
		pageNum: pSize,
		modelId: "",
		control: 1
	}
	getUserProcess(params).then(({ returnParams }) => {
		callback(returnParams.list, returnParams.total, pageNo)
	});
}
// 点击待办消息列表项
function handleToProcessDetail({ insId, tinsId, insName, control }) {
	$tab.navigateTo('/pages/process/detail/index?insId=' + insId + '&tinsId=' + tinsId + '&insName=' + insName + '&control=' + control)
}

// 获取公告列表数据
function getNoticeData({ pSize, pageNo }, callback) {
	const params = {
		notice_title: "",
		p: pageNo,
		pSize,
		userId: userStore.user.useId,
		unitId: userStore.user.unitId,
	}
	getNoticeList(params).then(({ returnParams }) => {
		// 通知子组件加载完成
		callback(returnParams.noticelist.list, returnParams.total, pageNo)
	})
}
// 分页获取公告数据
function getNoticePage({ pSize, pageNo }, callback) {
	const params = {
		notice_title: "",
		p: pageNo,
		pSize,
		userId: userStore.user.useId,
		unitId: userStore.user.unitId,
	}
	getNoticeList(params).then(({ returnParams }) => {
		// 通知子组件加载完成
		callback(returnParams.noticelist.list, returnParams.total, pageNo)
	})
}
// 点击公告列表项
function handleToNoticeDetail(notice) {
	$tab.navigateTo('/pages/message/detail/index?noticeId=' + notice.id)
}

// 消息列表
// const messages = ref([])
// 获取消息列表数据
const msgPoint = ref(0)
function getMessageData({ pSize, pageNo, type, segmentValue }, callback) {
	const flag = msgPoint.value = new Date().getTime()
	const params = {
		currentUser: userStore.user.useId,
		isRead: segmentValue,
		pSize: pSize,
		type: type,
		p: pageNo,
	}
	getMessageList(params).then(({ returnParams }) => {
		returnParams.list.forEach(item => {
			if ('(流程提醒)您有一个流程' == item.title.substring(0, 12)) {
				item.title = '(流程提醒)' + item.title.slice(12)
			}
		})

		// 通知子组件加载完成
		if (flag == msgPoint.value) {
			callback(returnParams.list, returnParams.total, pageNo)
		}
	})
}
// 分页获取消息数据
function getMessagePage({ pSize, pageNo, type, segmentValue }, callback) {
	const params = {
		currentUser: userStore.user.useId,
		isRead: segmentValue,
		pSize: pSize,
		type: type,
		p: pageNo,
	}
	getMessageList(params).then(({ returnParams }) => {
		returnParams.list.forEach(item => {
			if ('(流程提醒)您有一个流程' == item.title.substring(0, 12)) {
				item.title = '(流程提醒)' + item.title.slice(12)
			}
			// return item
		})
		// 通知子组件加载完成
		callback(returnParams.list, returnParams.total, pageNo)
	})
}
//点击消息列表项
function handleToMessageDetail({ messageid, universalid, jump_id, title }) {
	// 设置消息已读
	setMsgIsRead(universalid + ',').then((res) => {
		if (Number.isInteger(res)) {
			msgListRef.value.reload();//调用子组件刷新数据
		} else {
			$modal.confirm('登录状态失效，您可以继续留在该页面，或者重新登录?').then(res => {
				const loginInfo = getLoginInfo();
				userStore.LogOut().then(res => {
					uni.setStorageSync('loginInfo', loginInfo)
					$tab.reLaunch('/pages/login?type=autoLogin')
				})
			}).catch(() => { })
		}
	})
	debugger
	if(jump_id) {
		try {
			// 解析jump_id JSON字符串
			// const jumpInfo = JSON.parse(jump_id);
			const { modelId, insId, tinsId, opType, insName } = jump_id;
			
			if (opType === 'process') {
				getTacheInfo(tinsId).then(({returnParams}) => {
					if(returnParams.oldTacheStatus == 1) {
						//跳到流程办理页面
						$tab.navigateTo('/pages/process/detail/index?insId=' + insId + '&tinsId=' + tinsId + '&insName=' + insName + '&control=1')
					} else {
						//跳到流程到流程查看页面
						$tab.navigateTo('/pages/process/detail/index?insId=' + insId + '&insName=' + insName + '&control=0')
					}
				})
				
			} else if (opType === 'view') {
				//跳到流程到流程查看页面
				$tab.navigateTo('/pages/process/detail/index?insId=' + insId + '&insName=' + insName + '&control=0')
			} else {
				// 未知操作类型，跳转到消息详情页
				$tab.navigateTo('/pages/message/detail/index?messageId=' + messageid + '&universalId=' + universalid)
			}
		} catch (error) {
			console.error('jump_id解析失败:', error);
			// 解析失败，跳转到消息详情页
			$tab.navigateTo('/pages/message/detail/index?messageId=' + messageid + '&universalId=' + universalid)
		}
	} else {
		// jump_id为空，跳转到消息详情页
		$tab.navigateTo('/pages/message/detail/index?messageId=' + messageid + '&universalId=' + universalid)
	}
}

// AI咨询按钮
function clickFabButton() {
	// console.log('clickFabButton');
	$tab.navigateTo('/pages/message/chat/index')
}
//跳转打卡页
function toClockInBtn() {
	$tab.navigateTo('/pages/mine/clockIn/clockIn')
}
//待办流程数
const unProcessNum = ref(0)
//未读消息数
const unReadMsgNum = ref(0)
//待阅消息数+待办流程数(用于tarbar导航栏)
const unReadNum = ref(0)
function showTabBarBadge() {
	getUnProcessNum(userStore.user.useId, "").then(res => {
		if ("failed" == res.returnMsg) {
			$modal.showToast('待办流程数获取失败')
			return
		} else {
			unProcessNum.value = parseInt(res.returnParams?.total || 0, 10);
		}
		getUnReadMessageNum(userStore.user.useId).then(res => {
			unReadMsgNum.value = parseInt(res.returnParams ?? 0, 10);
			unReadNum.value = unReadMsgNum.value + unProcessNum.value;
			setThisTabBarBadge(0,unReadNum.value)
			setThisTabBarBadge(1,unProcessNum.value)
		})
	})
}
// 提取通用 badge 设置逻辑
function setThisTabBarBadge(index, count) {
	if (count <= 0) {
		uni.removeTabBarBadge({ index });
	} else {
		uni.setTabBarBadge({
			index,
			text: count > 99 ? "99+" : String(count)
		});
	}
}
// 设置所有消息已读
function setAllMsgRead() {
	$modal.confirm('是否全部已读').then(res => {
		if (res) {
			const params = {
				currentUser: userStore.user.useId,
				isRead: "0",
				pSize: unReadMsgNum.value,
				type: "",
				p: 1,
			}
			getMessageList(params).then(({ returnParams }) => {
				const unReadMsgIds = returnParams.ids === "" ? "" : returnParams.ids + ",";
				setMsgIsRead(unReadMsgIds).then((res) => {
					if (Number.isInteger(res)) {
						switch (res) {
							case -1:
								$modal.msgError('操作失败')
								break
							case -2:
							case 0:
								$modal.msg('不存在未读消息')
								msgListRef.value.reload();// 调用子组件刷新数据
								showTabBarBadge()
								break
							default:
								$modal.msgSuccess('操作成功')
								//刷新页面
								msgListRef.value.reload();// 调用子组件刷新数据
								showTabBarBadge()
						}
					} else {
						$modal.confirm('登录状态失效，您可以继续留在该页面，或者重新登录?').then(res => {
							userStore.LogOut().then(res => {
								uni.reLaunch({ url: '/pages/login?type=autoLogin' })
							})
						}).catch(() => { })
					}
				})
			})
		}
	}).catch(() => { })
}
</script>

<style lang="scss" scoped>
// @import "@/static/font/ygoa/iconfont.css";

::v-deep .uni-badge {
	height: calc(1.5rem + 0px) !important;
	min-width: calc(1.5rem + 0px) !important;
	line-height: calc(1.375rem + 0px) !important;
	font-size: calc(1.125rem + 0px) !important;
}

::v-deep .process_container {
	.process_list {
		.process_contant {
			font-size: calc(14px + .5*(1rem - 16px));
		}

		.flow_step_section {
			.uni-section .uni-section-header {
				padding: 5px 10px;
			}
		}

		.flow_step_container {
			min-height: 60px;
			margin: 10px 15px;

			.u-steps {
				.u-steps-item {
					padding-bottom: 11px;

					.u-text__value--content {
						font-size: calc(13px + .5*(1rem - 16px)) !important;
					}

					.u-text__value--main {
						font-size: calc(13px + .5*(1rem - 16px)) !important;
						font-weight: 500 !important;
					}

					.u-text__value--tips {
						font-size: calc(12px + .5*(1rem - 16px)) !important;
					}

					.redcontent {
						.u-text__value--content {
							color: #ff4500;
						}
					}

					.active_step_circle {
						width: 20px;
						height: 20px;
						box-sizing: border-box;
						flex-shrink: 0;
						border-radius: 100px;
						border-width: 1px;
						border-color: #A78BFA;
						background-color: #A78BFA;
						border-style: solid;
						display: flex;
						flex-direction: row;
						align-items: center;
						justify-content: center;
						transition: background-color .3s;

						.active_step_text {
							color: #fff;
							font-size: 11px;
							display: flex;
							flex-direction: row;
							align-items: center;
							justify-content: center;
							text-align: center;
							line-height: 11px;
						}
					}
				}

				.u-steps-item view:last-of-type {
					margin-top: 0 !important;
				}
			}
		}
	}
}

::v-deep .notice_list {
	.msg_list_container {
		.zp-l-text-rpx {
			font-size: calc(30rpx + .5*(1rem - 16px));
		}
	}
}

.read_button {
	position: absolute;
	top: calc(12px + .5 * (1rem - 16px));
	right: 3.125rem;
	height: calc(1.75rem + 0px);
	line-height: 1.75rem;
	font-size: calc(0.875rem + 0px);
	background-color: #007aff;
	color: #fff;
}

.read_button[disabled] {
	background-color: #f5f5f5;
	color: #666;
	opacity: 0.5;
}

::v-deep .message_list {
	.msg_list_container {
		.segmented_control_container {
			.segmented-control__text {
				font-size: calc(14px + .5*(1rem - 16px));
			}
		}

		.zp-paging-container-content {
			.zp-l-text-rpx {
				font-size: calc(30rpx + .5*(1rem - 16px));
			}
		}
	}
}

::v-deep .fab_button {
	.toClockInBtn {
		.uni-fab__circle--rightBottom {
			bottom: 100px;
		}
	}
	
	.toAiBtn {
		uni-icons {
			text {
				font-family: 'ygoa_work_icon' !important;
			}
			text:before {
				content: "\e660" !important;
			}
		}
	}

	.uni-fab__circle {
		width: calc(55px + .5*(1rem - 16px)) !important;
		height: calc(55px + .5*(1rem - 16px)) !important;

		.uni-icons {
			font-size: calc(32px + .5*(1rem - 16px)) !important;
		}
	}
}
</style>