<template>
	<view class="index_container">
		<uni-nav-bar dark :border="false" :fixed="true" title="宇光同行">
		</uni-nav-bar>
		<uni-collapse>
			<uni-collapse-item title-border="show" :border="true" :show-animation="true" :open="true">
				<template v-slot:title>
					<uni-section title="待办" type="line" titleFontSize="1.3rem">
						<template v-slot:right>
							<uni-badge :text="unProcessNum" style="margin-left: -10px;"
								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="69.5vh"></process-list>
					</view>
				</view>
			</uni-collapse-item>
		</uni-collapse>

		<!-- 公告列表  -->
		<message-list @clickSegment="getNoticeData" @clickItem="handleToNoticeDetail" @scrollToBottom="getNoticePage"
			:pSize="5" :pageNo="1" :anime="true" :open="false" title="公告"></message-list>

		<!-- 消息列表 -->
		<message-list ref="msgListRef" @readMsg="setAllMsgRead" :unReadNum="unReadMsgNum" @clickSegment="getMessageData"
			@clickItem="handleToMessageDetail" @scrollToBottom="getMessagePage" :defaultCurrent="1" :pSize="5"
			:pageNo="1" :anime="true" :open="true" :segments="{ '全部': '', '未读': '0', '已读': '1' }"
			title="消息"></message-list>

		<!-- 跳转打卡页按钮 -->
		<view class="fab_button toClockInBtn">
			<uni-fab :pattern="{ icon: 'calendar-filled' }" :popMenu="false" horizontal="right"
				@fabClick="toClockInBtn"></uni-fab>
		</view>
		<!-- AI咨询按钮 -->
		<view class="fab_button">
			<uni-fab :pattern="{ icon: 'headphones' }" :popMenu="false" horizontal="right"
				@fabClick="clickFabButton"></uni-fab>
		</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 } 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';

const userStore = useUserStore()

const processListRef = ref(null)
onMounted(() => {
	uni.$on('ReloadProcessData', (res) => {
		processListRef.value.onClickItem()
	})
	uni.$on('showTabBarBadge', showTabBarBadge)
})
onLoad((options) => {
	// 是否跳转打卡页
	if (options.to == 'clockIn') toClockIn()
})
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([])
// 获取消息列表数据
function getMessageData({ 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 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 }) {
	console.log();
	setMsgIsRead(universalid + ',').then((res) => {
		if (Number.isInteger(res)) {
			msgListRef.value.reload();// 调用子组件刷新数据
			$tab.navigateTo('/pages/message/detail/index?messageId=' + messageid + '&universalId=' + universalid)
		} else {
			$modal.confirm('登录状态失效，您可以继续留在该页面，或者重新登录?').then(res => {
				const loginInfo = getLoginInfo();
				userStore.LogOut().then(res => {
					uni.setStorageSync('loginInfo', loginInfo)
					$tab.reLaunch('/pages/login')
				})
			}).catch(() => { })
		}
	})
}

// 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, 10);
		}
		getUnReadMessageNum(userStore.user.useId).then(res => {
			unReadMsgNum.value = parseInt(res.returnParams, 10);
			unReadNum.value = unReadMsgNum.value + unProcessNum.value;
			if (unReadNum.value == 0) {
				uni.removeTabBarBadge({
					index: 0
				})
			} else {
				uni.setTabBarBadge({
					index: 0,
					text: unReadNum.value > 99 ? '99+' : String(unReadNum.value)
				})
			}
		})
	})
}
// 设置所有消息已读
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' })
							})
						}).catch(()=>{})
					}
				})
			})
		}
	}).catch(()=>{})
}
</script>

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

.text {
	text-align: center;
	font-size: 26rpx;
	margin-top: 10rpx;
}

::v-deep .uni-section-header__content {
	max-width: 3rem;
}

.toClockInBtn {
	.uni-fab__circle--rightBottom {
		bottom: 100px;
	}
}
</style>