addPeopleGroups.vue 9.4 KB
Newer Older
1
<template>
2
	<view class="contacts-addPeopleGroups">
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
		<uni-nav-bar color="#999" :fixed="true" background-color="#ffffff" status-bar left-icon="left" @clickLeft="back">
			<view class="segmented-box">
				<uni-segmented-control :current="current" :values="items" @clickItem="setActiveIndex" styleType="button" activeColor="#5fc08e" style="width:120px;"></uni-segmented-control>
			</view>
		</uni-nav-bar>
		<view class="content">
			<uni-search-bar :placeholder="activeIndex?'搜索群名称/群号':'搜索手机号/用户名/用户昵称'" :radius="100"
				class="search-bar"
        bgColor="#eeeeee"
				v-model="keyword"
				@confirm="doSearch"
				@focus="searchFocus = true"
				@blur="searchFocus = false"
				@cancel="doClear"
				@clear="doClear"
			></uni-search-bar>
			
			<view v-if="activeIndex === 0">
				<!-- 搜索 -->
				<view v-if="usersList.length">
					<uni-im-info-card v-for="(item,index) in usersList" :key="index"
						:title="item.nickname" :avatarCircle="true"
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
25
						:avatar="item.avatar_file?.url || '/uni_modules/uni-im/static/avatarUrl.png'"  
26 27
					>
            <text v-if="item.isFriend" class="chat-custom-right grey">已添加</text>
28
						<text v-else-if="item._id === currentUser._id" class="chat-custom-right grey">不能加自己</text>
29 30 31 32 33 34 35 36 37
						<text v-else @click="addUser(index)" class="chat-custom-right">加为好友</text>
					</uni-im-info-card>
				</view>
				<uni-im-load-state v-else :status="loading?'loading':(hasMore?'hasMore':'noMore')"></uni-im-load-state>
			</view>
			<view v-if="activeIndex === 1">
				<view v-if="groupList.length">
					<uni-im-info-card v-for="(item,index) in groupList" :key="index"
						:title="item.name" 
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
38
						:avatar="item.avatar_file?.url || '/uni_modules/uni-im/static/avatarUrl.png'" 
39 40 41 42 43 44 45 46 47 48 49 50 51
					>
            <text v-if="item.isExist" class="chat-custom-right grey">已加入</text>
						<text v-else @click="addUser(index)" class="chat-custom-right">申请加入</text>
					</uni-im-info-card>
				</view>
				<uni-im-load-state v-else :status="loading?'loading':(hasMore?'hasMore':'noMore')"></uni-im-load-state>
			</view>
		</view>
		
		<uni-popup ref="popup" type="dialog">
			<uni-popup-dialog mode="input" :title="activeIndex?'申请加群':'申请添加好友'" 
				placeholder="请输入验证信息" confirmText="发送" message="成功消息" 
				:duration="2000" :before-close="true" :value="value"
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
52
				@close="close" @confirm="confirm" :maxlength="100"
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
			></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
import uniIm from '@/uni_modules/uni-im/sdk/index.js';
	const db = uniCloud.database();
	export default {
		data() {
			return {
        current:0,
				loading:true,
				hasMore: false,
				activeIndex:0,
				value:'',
				items: ['找人', '找群'],
				searchFocus:false,//是否展示搜索列表
				keyword:'',
				tabs:[
					{
						'title':'添加手机联系人',
						'url':''
					},
					{
						'title':'扫一扫加好友',
						'url':''
					},
					{
						'title':'查找陌生人',
						'url':''
					}
				],
				usersData: [],
				checkIndex:'',//申请加的群index
				groupData:[]
			}
		},
		computed: {
92
      ...uniIm.mapState(['currentUser']),
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
			usersList() {
				let friendList = uniIm.friend.dataList
				return this.usersData.map(item => {
					const isFriend = friendList.find(i=>i._id == item._id)
					return {
						...item,
						isFriend
					}
				})
			},
			groupList() {
				let groupList = uniIm.group.dataList
				console.log('已经加入的groupList',groupList);
				console.log('查到的groupList',this.groupData);
				// return this.groupData.filter(item=> groupList.find(i=>i._id == item._id))
        
        return this.groupData.map(item => {
          const isExist = groupList.find(i=>i._id == item._id)
          return {
            ...item,
            isExist
          }
        })
			}
		},
    onLoad(param) {
    	this.setParam(param)
		},
		methods: {
      setParam(param){
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
123
        // console.log("param: ",param);
124 125 126 127 128 129 130 131 132 133
        if(param.group_id){
          this.current = 1
          this.setActiveIndex({currentIndex: 1})
          this.keyword = param.group_id
          return this.doSearch()
        }
        this.getUserList()
        this.getGroupsList()
      },
			async getGroupsList(){
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
134 135
        const limit = 100
        const skip = this.groupData.length/limit
136
				const res =  await db.collection('uni-im-group')
137
                              .where(`"user_id" != "${this.currentUser._id}"`)
138 139 140
                              .field('_id,name,avatar_file')
                              .orderBy('create_date', 'desc')
                              .skip(skip)
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
141
                              .limit(limit)
142
                              .get()
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
143
				// console.error("uni-im-group: ",res);
144 145 146 147 148 149 150 151 152
				if(res.result.data.length){
					this.loading = false
					this.hasMore = true
					this.groupData = res.result.data
				}
			},
			async getUserList(){
				try{
					let res = await db.collection('uni-id-users')
153
                    .where(`"_id" != "${this.currentUser._id}"`)
154 155 156 157 158 159 160 161 162 163
										.field('_id,nickname,avatar_file')
										.get()
					let data = res.result.data
					// console.log("data: ",data);
					if(data.length){
						this.loading = false
						this.hasMore = true
						this.usersData = data
					}
				}catch(e){
164
					console.error(e);
165 166 167 168 169 170
				}
			},
			back() {
				uni.navigateBack()
			},
			async doSearch(e){
171 172 173
        if(!this.keyword){
          return this.activeIndex === 0 ? this.getUserList() : this.getGroupsList()
        }
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
174
				// console.log("doSearch: ",e,this.keyword);
175 176 177 178
        uni.showLoading({
          title: '搜索中'
        })
				if(this.activeIndex){
179
          const where = `
180 181
              /${this.keyword}/.test(name) || 
							"_id" == "${this.keyword}"
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
182
						`
183
					const res = await db.collection('uni-im-group')
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
184
						.where(where)
185
						.get()
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
186
					// console.log(res);
187 188 189 190 191 192 193 194 195 196
					this.groupData = res.result.data
				}else{
          const whereString = [
            "_id",
            "username",
            "nickname",
            "email",
            "mobile"
          ].map(item => `"${item}" == "${this.keyword}"`).join(' || ')
          // console.log('whereString',whereString);
197
					const res = await db.collection('uni-id-users')
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
										.where(whereString)
										.field('_id,nickname,avatar_file')
										.get()
        	// tip:用户表数据少,或者已做好优化,可以使用:/${this.keyword}/.test(nickname) 模糊匹配用户昵称
					console.log(res);
					this.usersData = res.result.data
				}
        uni.hideLoading()
			},
			doClear() {
        if(this.keyword){
          this.keyword = ''
          this.usersData = []
          this.groupData = []
          this.getUserList()
          this.getGroupsList()
        }
			},
			setActiveIndex(e) {
				// console.log("activeIndex: ",e);
				if (this.activeIndex != e.currentIndex) {
					this.activeIndex = e.currentIndex;
				}
			},
			addUser(index){
				this.checkIndex = index
				this.$refs.popup.open()
			},
			async confirm(value){
				// if(!value){
				// 	uni.showToast({
				// 		title: '验证信息不能为空!',
				// 		icon:'none'
				// 	});
				// 	return
				// }
				// console.log('提供的验证信息',value);
				this.value = value
				this.$refs.popup.close()
				if(this.activeIndex === 0){
					//添加好友
					const uniImCo = uniCloud.importObject("uni-im-co")
					await uniImCo.addFriendInvite({
						"to_uid": this.usersList[this.checkIndex]._id,
						"message": this.value
					}).then((res)=>{
						console.log("res: ",res);
						uni.showToast({
							title: '已申请',
							icon: 'none'
						});
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					})
					
				}else{
					// console.log('1233123132123132',this.groupData,this.checkIndex);
					//申请加群
					db.collection('uni-im-group-join').add({
						"group_id":this.groupList[this.checkIndex]._id,
						"message":this.value
					}).then((res) => {
						console.log("res: ",res);
						uni.showToast({
							icon: 'none',
							title: '已申请'
						})
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					})
				}
				setTimeout(()=> {
					this.value = ''
				}, 100);
				
			},
			close(){
				console.log('取消了');
				this.$refs.popup.close()
			}
		}
	}
</script>

288 289 290 291 292 293 294
<style lang="scss">
@import "@/uni_modules/uni-im/common/baseStyle.scss";
.contacts-addPeopleGroups {
  .segmented-box{
  	flex: 1;
  	justify-content: center;
  	align-items: center;
295
  }
296 297 298 299 300 301 302 303 304 305 306 307 308
  
  .tab-item{
  	border-bottom: #f5f5f5 solid 1px;
  	height:60px;
  	justify-content: center;
  	padding: 0 15rpx;
  }
  .background{
  	background-color: #f5f5f5;
  }
  .chat-custom-right {
  	height:30px;
  	line-height: 30px;
309
    padding: 0 10px;
310 311 312 313 314 315 316 317 318
  	color: #666;
  	font-size: 12px;
  	text-align: center;
  	background-color: #efefef;
  	/* #ifdef H5 */
  	cursor: pointer;
  	/* #endif */
  	border-radius: 100px;
  }
319 320 321
  .grey{
  	color: #aaa;
  }
322 323 324 325 326 327 328 329
  .border{
  	border: #ddd solid 1px;
  }
  .state-text{
  	text-align: center;
  	font-size: 28rpx;
  }
  
330 331 332 333
  /* #ifdef H5 */
  @media screen and (min-device-width:960px){
    .content {
      margin-top: 0;
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
334
      height: calc(100vh - 150px);
335 336 337 338 339 340 341 342 343 344 345 346 347
      overflow: auto;
    }
  	::v-deep .uni-navbar__header-btns-left,
  	::v-deep .uni-navbar__placeholder,
  	{
  		display: none;
  	}
  	::v-deep .uni-navbar--fixed{
  		position: relative;
  		left: 0	
  	}
  }
  /* #endif */
348
}
349
</style>