<script setup>
	/**
	 * 发起群聊
	 */
	import {
		ref,
		reactive,
		computed
	} from 'vue'
	import {
		useStore
	} from 'vuex'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	// 工具库
	import util from '@/common/js/util.js'
	// 通讯录
	import book from './book'
	// 头部
	import apex from '@/components/header/apex.vue'
	// 腾讯云聊天
	import TencentCloudChat from '@tencentcloud/chat';

	const store = useStore()
	// 已选择的用户id
	const ids = reactive([])
	// 名称
	const name = ref('')
	// 列表
	const list = reactive([])
	// 用户信息
	const userinfo = computed(() => {
		let result = store.state.userinfo
		return result
	})

	onLoad(() => {
		// 获取朋友列表
		getFriendList()
	})

	// 获取朋友列表
	function getFriendList() {
		// 验证sdk是否准备完毕
		let isReady = uni.$chat.isReady();

		if (!isReady) {
			setTimeout(function() {
				getFriendList()
			}, 200);
			return
		}

		uni.$chat.getFriendList().then(rs => {
			if (rs.code == 0) {
				const result = rs.data
				// 
				list.push(...result)
			}
		})
	}

	// 新建群组
	function handleCreateGroup() {
		if (!name.value) {
			util.alert('群聊名称不能为空')
			return
		}
		if (ids.length < 2) {
			util.alert('请至少选择两名用户')
			return
		}
		// 成员列表
		const memberList = [{
				userID: userinfo.value.userId,
			},
			...ids.map(item => {
				return {
					userID: item
				}
			})
		]

		// 创建好友工作群
		uni.$chat.createGroup({
			type: TencentCloudChat.TYPES.GRP_WORK,
			name: name.value,
			memberList,
		}).then(rs => {
			console.log('createGroup success', rs)
			util.alert('创建成功')
		}).catch(rs => {
			console.log('createGroup catch', rs);
		})
	}
</script>

<template>
	<view class="app">
		<uni-search-bar placeholder="请输入群聊名称" v-model="name" style="background: #fff;" />

		<view class="jy-chat-box mt30">
			<book :list="list" v-model:ids="ids" />
		</view>

		<view class="fill" style="height: 120rpx;"></view>

		<view class="footer plr30 bfff shadow">
			<view class="btn lg colourful" @click="handleCreateGroup">新建群聊</view>
		</view>
	</view>
</template>

<style scoped lang="scss">
	// 
</style>