<template>
  <layout-page>
		<view class="height defaultBgc">
			<scroll-view class="scrollBox" scroll-y="true" >
				<view class="box" v-for="item in items" :key="item.id" @tap="handleTo(item)">
					<view class="box-header">
						<template v-if="item.unread === '0'">
							<image
								class="enterAvatar"
								:src="getUserAvatar(item?.userInfoVo?.userInfoResp?.avatar, item?.userInfoVo?.userInfoResp?.sex, !item?.userInfoVo && item.channel_id === 'system' ? true : false)"
							></image>
						</template>
						<template v-else>
							<uni-badge class="uni-badge-left-margin" :text="item.unread" absolute="rightTop" size="small">
								<image
									class="enterAvatar"
									:src="getUserAvatar(item?.userInfoVo?.userInfoResp?.avatar, item?.userInfoVo?.userInfoResp?.sex, !item?.userInfoVo && item.channel_id === 'system' ? true : false)"
								></image>
							</uni-badge>
						</template>
					</view>
					<view class="box-content">
						<view class="box-content-names">
							<view class="name">
								{{ item.thatName }}
								<text class="nameSub">{{ formatName(item.enterpriseAnotherName) }}</text>
								<span class="line" v-if="item.postNameCn && item.enterpriseAnotherName"></span>
								<text class="nameSub">{{ item.postNameCn }}</text>
							</view>
						</view>
						<view class="box-content-text">{{ timesTampChange(+item.timestamp.padEnd(13, '0')) }}</view>
					</view>
				</view>
				<image
					v-if=" items.length===0 "
					src="https://minio.citupro.com/dev/static/nodata.png"
					mode="widthFix"
					style="width: 100%;">
				</image>
				<uni-load-more status="noMore" />
			</scroll-view>
		</view>
  </layout-page>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import layoutPage from '@/layout'
import { getConversationSync } from '@/api/common'
import { onShow, onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { getUserAvatar } from '@/utils/avatar'
import { timesTampChange } from '@/utils/date'
import { userStore } from '@/store/user'
import { useIMStore } from '@/store/im'
import { formatName } from '@/utils/getText'

const useUserStore = userStore()
const userInfo = computed(() => useUserStore?.userInfo)

const IM = useIMStore()


const items = ref([])
watch([() => useUserStore.refreshToken, () => IM.newMsg], () => {
	if (!useUserStore.refreshToken) return items.value = []
	// 检测实例是否存在
	if (!IM.uid?.value) {
		return
	}
	if (!userInfo?.enterpriseId) setTimeout(() => {
		init()
	}, 2000)
	
}, { deep: true })

watch(() => IM.uid, (val) => {
	if (!val) {
		items.value = []
		return
	}
	// 监听uid变化
	if (!userInfo?.enterpriseId) setTimeout(() => {
		init()
	}, 2000)
})

onShow(() => {
	const currentPage = getCurrentPages()[0];  // 获取当前页面实例
	const currentTabBar = currentPage?.getTabBar?.();

	// 设置当前tab页的下标index
	currentTabBar?.setData({ selected: 2 });
	init()
})

onLoad(() => {
  wx.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline']
  })
  onShareAppMessage(() => {
    return {
      title: '门墩儿 专注顶尖招聘',
      path: '/pages/index/position',
			imageUrl: '../../static/img/share-poster.jpg'
    }
  })
	onShareTimeline(() => {
    return {
      title: '门墩儿 专注顶尖招聘',
      path: '/pages/index/position',
			imageUrl: '../../static/img/share-poster.jpg'
    }
  })
})



const handleTo = (item) => {
	const { userInfoVo, thatName, postNameCn, enterpriseAnotherName, channel_id, channel_type } = item
	const query = {
		id: userInfoVo?.userInfoResp?.userId,
		name: thatName,
		channelID: channel_id,
		channelType: channel_type,
		avatar: userInfoVo?.userInfoResp?.avatar,
		sex: userInfoVo?.userInfoResp?.sex,
	}
	const queryStr = Object.keys(query).reduce((r, v) => {
		if (!query[v]) {
			return r
		}
		return r += `${v}=${encodeURIComponent(query[v])}&`
	}, '?')
	uni.navigateTo({
    url: `/pagesA/chart/index${queryStr.slice(0, -1)}`
  })
}

async function init () {
	try {
		const { data } = await getConversationSync({ msg_count: 1, enterpriseId: userInfo.value.enterpriseId })
		if (!data) {
			return
		}
		items.value = data.map(item => {
			return {
				thatName: item?.userInfoVo ? (item.userInfoVo.userInfoResp?.name ? item.userInfoVo.userInfoResp.name : item.userInfoVo.userInfoResp.phone) : '系统消息',
				enterpriseAnotherName: item?.userInfoVo?.userInfoResp?.enterpriseAnotherName || item?.userInfoVo?.userInfoResp?.enterpriseName,
				postNameCn: item?.userInfoVo?.userInfoResp?.postNameCn ?? '',
				...item
			}
		})
	} catch (error) {
	}
}

</script>

<style scoped lang="scss">
.scrollBox {
	padding-bottom: 24rpx;
  box-sizing: border-box;
}
.box {
	background: #FFF;
	height: 130rpx;
	padding: 20rpx;
	box-sizing: border-box;
	display: flex;
	border-bottom: 2rpx solid #eee;
	&-header {
		width: 120rpx;
		height: 100%;
		position: relative;
	}
	&-content {
		flex: 1;
		width: 0;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		&-names {
			display: flex;
			justify-content: space-between;
			
			.name {
				flex: 1;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
				.nameSub {
					font-size: 0.75em;
					color: #999;
				}
				.line {
					display: inline-block;
					width: 2rpx;
					height: 24rpx;
					vertical-align: middle;
					background-color: #e0e0e0;
					margin: 0 6rpx;
				}
			}
			.time {
				color: #999;
				font-size: .85em;
			}
		}
		&-text {
			color: #999;
			font-size: .85em;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
		}
	}
}
.height {
	height: 100vh;
	padding-bottom: 120rpx;
	box-sizing: border-box;
}
.enterAvatar{
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	margin: 0 auto;
}
</style>
