<template>
	<view class="voiceRoom blacks_style campus_room">
		<Nav className="black_nav" :scroll="scroll">
			<block slot="content" class="campus_title">
				<template v-if="(form.school && form.school.id) || (form.team && form.team.id)">
					<view class="attr omit" @click="schoolVisible = true" v-if="form.school && form.school.id">{{ form.school.fullName | across }}</view>
					<view class="attr omit" @click="teamOpen" v-if="form.team && form.team.id">{{ form.team.teamName | across }}</view>
				</template>
				<template v-else>
					<view class="attr omit" v-if="form.captain">{{ form.captain.nickname | across }}发起的交流</view>
				</template>
			</block>
		</Nav>
		<view class="body_scroll" :style="getHeight">
			<view id="model">
				<view class="th">
					<view class="schedule">
						<view class="txt" v-if="restrictedCopyTxt">{{ restrictedCopyTxt }}</view>
						<view class="txt">{{ form.realParticipateNum || 0 }}人参与过</view>
					</view>
					<view class="home" @click="$backPage">
						<view class="icomoon icon-home_grey">
							<i class="inline path1"></i>
							<i class="inline path2"></i>
							<i class="inline path3"></i>
						</view>
					</view>
				</view>
				<view class="sit_down">
					<view class="core">
						<view class="name" @click="topicOpen">
							<view class="lineClamp2">{{ form.topic | across }}</view>
						</view>
						<view class="member">
							<view class="user" v-for="(i, k) in form.users" :key="k" :class="'user_0' + (k + 1)">
								<view v-if="i.uid" @click="userChange(i, 'seat')">
									<view class="n" v-if="k < 4">
										<view class="n_t omit">{{ i.nickname | across }}</view>
										<view class="ico" v-if="i.isVolunteer === '1'">
											<image class="pic" mode="aspectFill" src="https://daifeiclub.com/image/pics/me_userInfo_logo.png"></image>
										</view>
									</view>
									<view class="pic">
										<image class="photo" mode="aspectFill" :src="i.avatarUrl"></image>
										<view class="ide" v-if="i.isRoomOwner === '1'">
											<view class="icomoon icon-leaderSymbol_black" style="font-size: 24rpx;">
												<i class="inline path1"></i>
												<i class="inline path2"></i>
												<i class="inline path3"></i>
											</view>
										</view>
									</view>
									<view class="n" v-if="k >= 4">
										<view class="n_t omit">{{ i.nickname | across }}</view>
										<view class="ico" v-if="i.isVolunteer === '1'">
											<image class="pic" mode="aspectFill" src="https://daifeiclub.com/image/pics/me_userInfo_logo.png"></image>
										</view>
									</view>
								</view>
								<view v-else @click="takeOrLeaveSeatChange(k + 1, 1)">
									<view class="n" v-if="k < 4"></view>
									<image class="pic" mode="aspectFill" src="https://daifeiclub.com/image/pics/chair.png"></image>
									<view class="n" v-if="k >= 4"></view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="list">
				<scroll-view class="list_chat" :style="listHeight" :scroll-y="true" :scroll-with-animation="false" :scroll-top="scrollTop">
					<view class="list_chat_bottom" id="message-scroll">
						<view class="item" v-for="(item, key) in list" :key="key">
							 <!-- 文本消息 -->
							<view @click="wordChange('news', item)" v-if="item.type === 'TIMTextElem'">
								<view class="item_model">
									<view class="head_portrait" @click.stop="userChange(item, 'news')">
										<image class="pic" mode="aspectFill" :src="item.avatar"></image>
									</view>
									<view class="head_content">
										<view class="label" @click.stop="userChange(item, 'news')">{{ item.nick | across }}：</view>
										<view class="text" @longpress.stop="wordLongpress(item.payload.text)">{{ item.payload.text | across }}</view>
									</view>
								</view>
							</view>
							<!-- 图片消息 -->
							<view @click="wordChange('news', item)" v-if="item.type === 'TIMImageElem'">
								<view class="item_model">
									<view class="head_portrait" @click.stop="userChange(item, 'news')">
										<image class="pic" mode="aspectFill" :src="item.avatar"></image>
									</view>
									<view class="head_content TIMImageElem">
										<view class="label" @click.stop="userChange(item, 'news')">{{ item.nick | across }}：</view>
										<view class="text">
											<image class="pic" mode="aspectFill" :src="item.payload.imageInfoArray[0].url" @click.stop="imagePreviewChange(item.payload)"></image>
										</view>
									</view>
								</view>
							</view>
							<!--自定义消息 -->
							<template v-if="item.type === 'TIMCustomElem'">
								<view class="join" v-if="item.payload.data === 'group_create'"><text class="name">{{ item.nick }}</text>创建了群组</view>
							</template>
							<!-- 通知 -->
							<template v-if="item.type === 'TIMGroupTipElem'">
								<view class="join" v-if="item.payload.operationType === 1"><text class="name">{{ item.payload | userIMFmt('memberList') }}</text>加入小队</view>
								<view class="join" v-if="item.payload.operationType === 3"><text class="name">{{ item.payload | userIMFmt('memberList') }}</text>退出小队</view>
								<view class="join" v-if="item.payload.operationType === 4"><text class="name">{{ item.payload | userIMFmt('memberList') }}</text>成为管理员</view>
								<view class="join" v-if="item.payload.operationType === 5"><text class="name">{{ item.payload | userIMFmt('memberList') }}</text>已从管理员团队移出</view>
								<view class="join" v-if="item.payload.operationType === 6 && item.payload.newGroupProfile.introduction"><text class="name">{{ item.nick || item.payload.operatorID }}</text>修改了话题</view>
								<view class="join" v-if="item.payload.operationType === 7"><text class="name">{{ item.payload | userIMFmt('muteTime') }}</text></view>
							</template>
						</view>
					</view>
				</scroll-view>
				<scroll-view class="team_gather" :scroll-y="true" :style="listHeight">
					<view class="team_gather__contenter">
						<view class="item" v-for="(item, key) in memberList" :key="key" @click="userChange(item, 'onLine')">
							<view class="userAvatarUrl">
								<image class="pic" mode="aspectFill" :src="item.userAvatarUrl"></image>
								<view class="ide" v-if="item.isAdmin === '1'">
									<view class="icomoon icon-leaderSymbol_black" style="font-size: 24rpx;">
										<i class="inline path1"></i>
										<i class="inline path2"></i>
										<i class="inline path3"></i>
									</view>
								</view>
							</view>
							<!-- <view class="speak" v-if="item.isCaptain === '55'">
								<image class="pic" mode="aspectFill" src="https://daifeiclub.com/image/pics/speak.png"></image>
							</view> -->
						</view>
					</view>
				</scroll-view>
			</view>
			<view class="fixed">
				<view class="btn" @click="forbiddenWords">
					<view class="ico">
						<image class="pic" mode="aspectFill" src="https://daifeiclub.com/image/pics/voice_disable.png" v-if="groupProfile.muteAllMembers"></image>
						<image class="pic" mode="aspectFill" src="https://daifeiclub.com/image/pics/voice.png" v-else></image>
					</view>
				</view>
				<view class="input" @click="wordChange">我想说...</view>
				<view class="btn" @click="giftOpen()">
					<view class="ico">
						<image class="pic" mode="aspectFill" src="https://daifeiclub.com/image/pics/gift.png"></image>
					</view>
				</view>
				<view class="btn" @click="menuOpen">
					<view class="ico">
						<image class="pic" mode="aspectFill" src="https://daifeiclub.com/image/pics/menu.png"></image>
					</view>
					<view class="yq" v-if="guideVisible">召集成员</view>
				</view>
			</view>
		</view>
		<!-- loading -->
		<loading :visible="loading" />
		<!-- 学院 -->
		<van-popup class="school_popup" position="bottom" :show="schoolVisible" @close="schoolClose" round>
			<view class="school_popup__contenter" v-if="form.school">
				<view class="th">
					<view class="l">
						<view class="name omit">{{ form.school.fullName | across }}</view>
					</view>
				</view>
				<view class="content">{{ form.school.simpleName || '暂无更多信息' }}</view>
			</view>
		</van-popup>
		<!-- 话题 -->
		<van-popup class="title_popup" position="bottom" :show="topicVisible" @close="topicClose" :custom-style="`bottom: ${wordHeight}px;`">
			<view class="title__popup__form">
				<view class="th">
					<view class="name">话题</view>
				</view>
				<view class="content">
					<input
						:show-confirm-bar="false"
						:adjust-position="false"
						:fixed="true"
						class="uni-textarea"
						:focus="wordTxtFocus"
						v-model="topicTxt"
						@blur="wordBlur"
						maxlength="14"
						@keyboardheightchange="keyboardheightchange"
						placeholder="输入话题..." />
				</view>
				<view class="btns">
					<view class="btn" @click="topicSave" :class="{active: topicTxt}">更改</view>
				</view>
			</view>
		</van-popup>
		<!-- 菜单 -->
		<van-popup class="meun_list__popup" position="bottom" :show="menuVisible" @close="menuClose">
			<view class="meun_list">
				<view class="item" @click="toTopping">
					<view class="ico">
						<i class="icomoon icon-toTop"></i>
					</view>
					<view class="txt">置顶</view>
				</view>
				<view class="item" @click="sendPictures" v-if="roomRoot === '1'">
					<view class="ico">
						<i class="icomoon icon-sendImage"></i>
					</view>
					<view class="txt">发送图片</view>
				</view>
				<view class="item">
					<view class="ico">
						<button class="share" open-type="share" data-type="forwardToFriends"></button>
						<i class="icomoon icon-roomShare"></i>
					</view>
					<view class="txt">转发给朋友</view>
				</view>
				<view class="item wechatMoments" @click="getPosterUserAvatars">
					<view class="ico">
						<i class="icomoon icon-friendCircleShare"></i>
					</view>
					<view class="txt">分享朋友圈</view>
				</view>
				<view class="item" @click="endCommunication">
					<view class="ico">
						<i class="icomoon icon-endChat"></i>
					</view>
					<view class="txt">结束交流</view>
				</view>
			</view>
		</van-popup>
		<!-- 小队 -->
		<van-popup class="team_popup" position="bottom" :show="teamVisible" @close="teamClose" round>
			<view class="team_popup__contenter">
				<view class="th">
					<view class="l">
						<view class="name omit">{{ form.team.teamName | across }}</view>
						<view class="attr">{{ form.team.memberNum || 0 }}名成员</view>
						<view class="attr">{{ form.team.followerNum || 0 }}人关注</view>
					</view>
					<button class="share" open-type="share" data-type="joinTheTeam">
						<i class="iconfont icon-fenxiang"></i>
					</button>
				</view>
				<view class="tr">{{ form.team.introduction }}</view>
				<view class="admin" v-if="form.captain">
					<view class="title">队长</view>
					<view class="admin_list">
						<template>
							<view class="item">
								<view class="photo">
									<view class="ide">
										<view class="icomoon icon-leaderSymbol_grey" style="font-size: 24rpx;">
											<i class="inline path1"></i>
											<i class="inline path2"></i>
											<i class="inline path3"></i>
										</view>
									</view>
									<image class="pic" mode="aspectFill" :src="form.captain.avatarUrl"></image>
								</view>
								<view class="nickname">
									<view class="name omit">{{ form.captain.nickname | across }}</view>
									<view class="ico">
										<image class="pic" mode="aspectFill" src="https://daifeiclub.com/image/pics/me_userInfo_logo.png"></image>
									</view>
								</view>
							</view>
						</template>
					</view>
				</view>
				<view class="flex btns">
					<view class="item" v-if="['0', '2'].includes(form.followOrJoin)" @click="focusTeam">关注</view>
					<view class="item active" v-if="['1', '3'].includes(form.followOrJoin)" @click="unfocusTeam">取消关注</view>
					<view class="item" v-if="['0', '3'].includes(form.followOrJoin)" @click="link('/pages/me/teamJoin')">加入</view>
					<view class="item disable" v-if="['1', '2'].includes(form.followOrJoin)">已加入</view>
				</view>
			</view>
		</van-popup>
		<!-- 用户 -->
		<van-popup class="user_popup" position="bottom" :show="userVisible" @close="userClose" round>
			<view class="user_popup__contenter" @click="link(`/pages/share/he?uid=${userObj.uid}`)">
				<view class="more" @click.stop="moreOpen" v-if="userObj.uid !== uid"><i class="iconfont icon-gengduo"></i></view>
				<view class="avatar">
					<image class="pic" mode="aspectFill" :src="userObj.avatarUrl"></image>
				</view>
				<view class="title">
					<view class="name omit">{{ userObj.nickname | across }}</view>
					<view class="ico" v-if="userObj.isVolunteer === '1'">
						<image class="pic" mode="aspectFill" src="https://daifeiclub.com/image/pics/me_userInfo_logo.png"></image>
					</view>
				</view>
				<view class="explain" v-if="userObj.signature">{{ userObj.signature | across }}</view>
				<view class="team_list" v-if="userObj.teams && userObj.teams.length">
					<view class="item" v-for="(item, key) in userObj.teams" :key="key">
						<view class="name omit">{{ item.teamName | across }}</view>
						<view class="value">{{ item.followerNum || 0 }}人关注</view>
					</view>
				</view>
				<view class="option">
					<view class="btn">查看更多</view>
					<template v-if="userObj.uid === uid">
						<view class="btn success" @click.stop="takeOrLeaveSeatChange('userCard', 1)" v-if="!userObj.roomSeatOrder">
							<view class="txt">上座</view>
						</view>
						<view class="btn mc" @click.stop="takeOrLeaveSeatChange(userObj.roomSeatOrder, 0)" v-else>
							<view class="txt">离座</view>
						</view>
					</template>
					<template v-else>
						<view class="btn mc" @click.stop="giftOpen(userObj.uid)">
							<i class="iconfont icon-liwu"></i>
							<view class="txt">赠送礼物</view>
						</view>
					</template>
				</view>
			</view>
		</van-popup>
		<van-overlay class="user_overlay" :z-index="9999" :show="userOverlayVisible" @click="userOverlayHide">
			<view class="user_overlay__contenter" :style="'top: ' + userOverlayContentertop + 'px;'">
				<view class="item" @click="link(`/pages/campus/complaint?roomId=${form.rid}&uid=${userObj.uid}&nickname=${userObj.nickname}`)">
					<view class="txt">投诉</view>
				</view>
				<view class="item" @click="prohibitionOfSpeechChange" v-if="roomRoot === '2'">
					<view class="txt">禁言</view>
				</view>
			</view>
		</van-overlay>
		<!-- 我想说 -->
		<van-popup class="word_popup" position="bottom" :show="wordVisible" :safe-area-inset-top="true" @close="wordClose" :custom-style="`bottom: ${wordHeight}px;`">
			<view class="word_popup__form">
				<view class="content">
					<input
						:show-confirm-bar="false"
						:adjust-position="false"
						:fixed="true"
						class="uni-textarea"
						:focus="wordTxtFocus"
						v-model="wordTxt"
						@input="wordInput"
						@blur="wordBlur"
						@keyboardheightchange="keyboardheightchange"
						:placeholder="wordPlaceholder" />
				</view>
				<view class="btn" :class="{active: wordTxt}" @click="wordSave">
					<view class="save">
						<image class="pic" mode="aspectFill" src="https://daifeiclub.com/image/pics/sendOut.png"></image>
					</view>
				</view>
			</view>
		</van-popup>
		<!-- 礼物 -->
		<van-popup class="gift_popup" position="bottom" :show="giftVisible" @close="giftClose">
			<view class="gift_popup__form">
				<view class="select">
					<view class="label">送给</view>
					<scroll-view class="select_userList" :scroll-x="true">
						<view class="item" v-for="(item, key) in receiverList" :key="key" @click="giftGiveChange(item)">
							<view class="active" v-if="receiverObj.userUid === item.userUid">
								<image class="pic" mode="aspectFill" src="https://daifeiclub.com/image/pics/user_active.png"></image>
							</view>
							<image class="pic" mode="aspectFill" :src="item.userAvatarUrl"></image>
							<view class="qizi" v-if="item.isCaptain === '1'"><i class="iconfont icon-qizi"></i></view>
						</view>
					</scroll-view>
				</view>
				<view class="content clearfix">
					<swiper class="swiper" :indicator-dots="true" indicator-color="#373737" indicator-active-color="#949494">
						<swiper-item v-for="(item, key) in giftList" :key="key">
							<template v-for="(i, k) in item">
								<view class="swiper-item more" :key="k" v-if="i.hasNewGrantGift">
									<view class="ico">
										<view class="add" @click="giftMoreOpen">
											<view class="spot" v-if="i.hasNewGrantGift === '1'"></view>
											<i class="iconfont icon-jiahao"></i>
										</view>
									</view>
									<view class="name">更多礼物</view>
								</view>
								<view class="swiper-item" :key="k" :class="{active: giftItemId === i.sysGrantGiftId}" @click="giftItem(i)" v-else>
									<view class="ico">
										<view class="num">{{ i.giftNum || 0 }}</view>
										<image class="pic" mode="aspectFill" :src="i.imageUrl"></image>
									</view>
									<view class="name">{{ i.giftName | across }}</view>
								</view>
							</template>
						</swiper-item>
					</swiper>
					<view class="option">
						<view class="label"></view>
						<view class="btn" @click="giftGiveSelect">确认</view>
					</view>
				</view>
			</view>
		</van-popup>
		<!-- 更多礼物 -->
		<van-popup class="giftMore_popup" position="bottom" :show="giftMoreVisible" @close="giftMoreClose">
			<view class="giftMore_popup__form">
				<view class="th" @click="giftMoreClose">
					<view class="ico">
						<i class="iconfont icon-zuojiantou"></i>
					</view>
					<view class="name">更多礼物</view>
				</view>
				<view class="content">
					<swiper class="swiper" :indicator-dots="true" indicator-color="#373737" indicator-active-color="#949494" v-if="giftMoreList && giftMoreList.length">
						<swiper-item v-for="(item, key) in giftMoreList" :key="key">
							<view class="swiper-item" v-for="(i, k) in item" :key="k">
								<view class="ico">
									<view class="num">{{ i.giftNum || 0 }}</view>
									<image class="pic" mode="aspectFill" :src="i.imageUrl"></image>
								</view>
								<view class="name">{{ i.giftName | across }}</view>
								<view class="type">{{ dict['giftType'][i.giftType] | across }}</view>
								<view class="btn active" v-if="i.isReceived === 0" @click="receiveGift(i, key, k)">领取</view>
								<view class="btn" v-else>已领取</view>
							</view>
						</swiper-item>
					</swiper>
					<view class="no_data" v-else>暂无更多礼物</view>
				</view>
			</view>
		</van-popup>
		<!-- 礼物送给谁 -->
		<van-popup class="giftGive_popup" position="bottom" :show="giftGiveVisible" @close="giftGiveClose" :custom-style="`bottom: ${wordHeight}px;`">
			<view class="giftGive_popup__form">
				<view class="select">
					<view class="label">送给</view>
					<scroll-view class="select_userList" :scroll-x="true">
						<view class="item">
							<view class="active">
								<image class="pic" mode="aspectFill" src="https://daifeiclub.com/image/pics/user_active.png"></image>
							</view>
							<image class="pic" mode="aspectFill" :src="receiverObj.userAvatarUrl"></image>
							<view class="qizi" v-if="receiverObj.isCaptain === '1'"><i class="iconfont icon-qizi"></i></view>
						</view>
					</scroll-view>
				</view>
				<view class="content clearfix">
					<textarea :adjust-position="false" :show-confirm-bar="false" class="uni-textarea" maxlength="70" v-model="giftMessage" @keyboardheightchange="keyboardheightchange" placeholder="想对TA说..." auto-height />
					<view class="option">
						<view class="label">对方拆开礼物后可见</view>
						<view class="btn" :class="{active: giftMessage}" @click="giftGiveSave">送出</view>
					</view>
				</view>
			</view>
		</van-popup>
		<!-- 	分享海报 -->
		<van-overlay class="playbill_overlay" :z-index="9999" :show="playbillVisible" @click="playbillClose">
			<view class="playbill_contenter">
				<view class="playbill_contenter__cell">
					<view class="press"> <!-- @longpress="playbillPress" -->
						<view class="txt">长按图片保存或分享</view>
						<image class="pic" :show-menu-by-longpress="true" mode="aspectFit" :src="playbillPic" :style="playbillStyle"></image>
					</view>
					<view class="go_back" @click="playbillClose">返回</view>
				</view>
			</view>
		</van-overlay>
		<!-- 实时音频流 -->
		<live-pusher
			id="livePusher"
			ref="livePusher"
			class="livePusher"
			:url="livePusherUrl"
			mode="SD"
			:muted="true"
			:enable-camera="false"
			:auto-focus="true"
			:beauty="1"
			whiteness="2"
			aspect="9:16"
			@statechange="statechange"
			@netstatus="netstatus"
			@error="error" />
	</view>
</template>

<script>
	import mixins from '@/utils/mixins'
	import sdkService from '@/api/sdk_service'

	export default {
		mixins: [mixins],
		data() {
			return {
				restrictedCopyTxt: '', // 限制文字
				schoolVisible: false, // 学校 是否显示
				livePusher: '',
				livePusherUrl: '',
				playbillVisible: false, // 分享海报 是否显示
				playbillPic: '', // 分享海报 图片地址
				uid: uni.getStorageSync('uid'),
				form: {
					team: {
						teamName: '',
						memberNum: '',
						followerNum: ''
					}
				},
				guideVisible: false, // 引导浮层 是否显示
				timer: null,  // 引导浮层 定时器
				timerTime: 60,  // 引导浮层 倒计时
				groupProfile: {}, // 群资料
				teamVisible: false, // 小队弹框 是否显示
				userVisible: false, // 用户 是否显示
				userObj: {}, // 用户 对象
				userOverlayVisible: false, // 用户更多 是否显示
				userOverlayContentertop: 0, // 用户更多 计算位置
				scrollTop: 0, // 滚动距离
				roomRoot: null, // 1带飞管理员，2房主，3交流成员/队员
				memberList: [], // 成员
				options: {
					scheduleTxt: '', // 查询小队活动提示
					group: {} // 群组
				},
				dict: {
					giftType: this.API.dict['giftType']
				},
				topicVisible: false, // 话题 是否显示
				topicTxt: '', // 话题 内容
				height: 0,
				menuVisible: false, // 菜单 是否显示
				wordVisible: false, // 我想说 是否显示
				wordHeight: 0, // 我想说 键盘高度
				wordTxtFocus: false, // 我想说 是否可提交
				wordTxt: '', // 我想说 msg
				wordStatus: 'ordinary', // 我想说 ordinary普通 longpress长按
				wordPlaceholder: '我想说...', // 我想说 提示placeholder
				wordAiteUser: null, // 我想说 艾特人员信息
				giftVisible: false, // 礼物 是否显示
				giftList: [], // 礼物 列表
				receiverList: [], // 礼物 收礼人
				receiverObj: [], // 礼物 选中当前收礼人对象
				giftItemId: null, // 礼物 选中当前礼物id
				giftUserId: null, // 礼物 选中收礼人id
				giftMoreList: [], // 更多礼物 列表
				giftMoreVisible: false, // 更多礼物 是否显示
				giftGiveVisible: false, // 礼物送给谁 是否显示
				giftMessage: '' // 礼物送给谁 礼物留言
			}
		},
		onLoad(e) {
			if (e) {
				this.options = Object.assign({}, this.options, e)
				if (getApp().globalData.isSDKReady) {
					this.getDetail()
					this.getUserRole()
					this.getDailyCommunicationGifts()
				}
			}
			uni.$on('isSDKReady', data => {
				this.isSDKReady = data.isSDKReady
				if (this.isSDKReady) {
					this.getDetail()
					this.getUserRole()
					this.getDailyCommunicationGifts()
				}
			})
			uni.$on('teamVoiceRoom', data => {
				this.getDetail()
			})
		},
		mounted() {
			uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.onMessageReceived, this)
			this.$nextTick(() => {
				const query = uni.createSelectorQuery().in(this)
				query.select('#model').boundingClientRect(data => {
					if (data) {
						this.height = data.height
					}
				}).exec()
			})
			this.setGuide()
		},
		onUnload() {
			if (this.options.level) {
				uni.navigateBack({
					delta: this.options.level
				})
			}
			// 移除监听事件
			uni.$off('teamVoiceRoom')
			this.clearGuide()
		},
		destroyed() {
			// 一定要解除相关的事件绑定
			uni.$TUIKit.off(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.onMessageReceived)
		},
		computed: {
			listHeight() {
				let height = this.CustomBar + this.height + 60
				return `height: calc(100vh - ${height}px);`;
			},
			playbillStyle() {
				let height = this.System.screenWidth * 1.4608540925266904
				return `height: ${height}px;`
			}
		},
		methods: {
			// 键盘高度发生变化的时候触发此事件
			keyboardheightchange (res) {
				this.wordHeight = res.detail.height
			},
			// 实时监听聊天消息
			onMessageReceived (e) {
				console.log('实时监听聊天消息', e.data)
				this.list = this.list.concat(e.data)
				console.log(e.data[0], e.data[0].type)
				if (e.data[0].type === 'TIMGroupTipElem' && [1, 3].includes(e.data[0].payload.operationType)) {
					this.getGroupMemberList()
				}
				if (e.data[0].type === 'TIMGroupSystemNoticeElem' && e.data[0].payload.operationType === 4) {
					uni.showModal({
						content: '你已被移出小队',
						showCancel: false,
						success: res => {
							uni.$emit('team')
							uni.navigateBack()
						}
					})
				}
			},
			// 当用户进入房间1分钟后才展示该引导浮层，并且小队房间展示“召集成员”浮层，交流房间才展示“邀请朋友”浮层
			setGuide () {
				this.timer = setInterval(() => {
					this.timerTime--
					if (this.timerTime <= 0) {
						this.guideVisible = true
						this.clearGuide()
					}
				}, 1000)
			},
			// 清除定时器
			clearGuide () {
				clearInterval(this.timer)
				this.timerTime = 60
				this.timer = null
			},
			// 获取每日交流礼物
			async getDailyCommunicationGifts () {
				await this.$axios.post(this.API.getDailyCommunicationGifts, {
					rid: this.options.rid
				})
			},
			// 获取群详细资料
			getGroupProfile () {
				sdkService.getGroupProfile({
					groupID: this.form.groupID
				}, res => {
					this.groupProfile = res.group
				})
			},
			// 查询用户在房间内的角色
			async getUserRole () {
				const result = await this.$axios.get(this.API.getUserRole, {
					params: {
						uid: uni.getStorageSync('uid'),
						rid: this.options.rid
					}
				})
				if (result) {
					// 1带飞管理员，2房主，3交流成员/队员
					this.roomRoot = result
				}
			},
			// 获取房间
			async getDetail(type) {
				this.loading = true
				const result = await this.$axios.get(this.API.roomGet, {
					params: {
						rid: this.options.rid
					}
				})
				this.loading = false
				if (result) {
					this.form = Object.assign({}, this.form, result)
					this.options.teamId && this.whetherFocusOrJoinTeam()
					if (type === 'team') {
						return
					}
					this.getList()
					this.getGroupProfile()
					this.getGroupMemberList()
					if (this.form.school && this.form.school.id && this.form.team && this.form.team.id) {
						this.restrictedCopyTxt = '校友和队友可参与'
					} else {
						if (this.form.school && this.form.school.id) {
							this.restrictedCopyTxt = '校友可参与'
						}
					}
				}
			},
			// 查询用户是否关注或加入小队
			// 0未加入未关注，1已加入已关注，2已加入未关注，3未加入已关注
			async whetherFocusOrJoinTeam () {
				const result = await this.$axios.get(this.API.whetherFocusOrJoinTeam, {
					params: {
						teamId: this.options.teamId
					}
				})
				if (result) {
					this.form = Object.assign({}, this.form, { followOrJoin: result })
				}
			},
			// 取消关注小队
			async unfocusTeam () {
				const result = await this.$axios.delete(this.API.unfocusTeam, {
					params: {
						teamId: this.form.teamId,
						follower: uni.getStorageSync('uid')
					}
				})
				if (result) {
					this.getDetail('team')
					this.teamClose()
				}
			},
			// 关注小队
			async focusTeam () {
				const result = await this.$axios.post(this.API.focusTeam, {
					teamId: this.form.teamId,
					follower: uni.getStorageSync('uid')
				})
				if (result) {
					this.getDetail('team')
					this.teamClose()
				}
			},
			// 上座离座
			async takeOrLeaveSeatChange (value, type) {
				let seatOrder = null
				// 用户卡上座
				if (value === 'userCard') {
					for (let i = 1; i <= this.form.users.length; i++) {
						if (!this.form.users[i].uid) {
							seatOrder = i
							break
						}
					}
				} else {
					seatOrder = value
				}
				const result = await this.$axios.put(this.API.takeOrLeaveSeat, {
					rid: this.options.rid,
					seatOrder: seatOrder,
					type: type // 0离座，1上座
				})
				if (result) {
					uni.$emit('team')
					this.form.users = result
					this.getGroupMemberList()
					// 用户卡上座
					if (value === 'userCard') {
						this.userObj.roomSeatOrder = seatOrder
					} else {
						this.userObj.roomSeatOrder = ''
					}
					this.userClose()
				}
			},
			// 话题 打开
			topicOpen () {
				this.topicTxt = this.form.topic
				this.topicVisible = true
				setTimeout(() => {
					this.wordTxtFocus = true
				}, 200)
			},
			// 话题 更改
			topicSave () {
				if (!this.topicTxt) {
					return
				}
				sdkService.updateGroupProfile({
					groupID: this.form.groupID,
					introduction: this.topicTxt
				}, async res => {
					if (res) {
						const result = await this.$axios.put(this.API.updateRoom, {
							rid: this.options.rid,
							topic: this.topicTxt,
							updateBy: uni.getStorageSync('uid')
						})
						if (result || result === 0) {
							this.form.topic = this.topicTxt
							uni.$emit('team')
							this.topicClose()
						}
					}
				})
			},
			// 话题 关闭
			topicClose () {
				this.wordBlur()
				this.topicVisible = false
			},
			// 小队弹框 打开
			teamOpen () {
				this.teamVisible = true
			},
			// 小队弹框 关闭
			teamClose () {
				this.teamVisible = false
			},
			// 用户 打开
			userChange (item, type) {
				switch (type){
					case 'seat':
						item.userID = item.uid
						break;
						
					case 'news':
						item.userID = item.from
						break;
						
					case 'onLine':
						item.userID = item.userUid
						break;
				}
				if (!item.userID) {
					return this.$base.Tips('没有uid')
				}
				this.getUserInfo(item)
			},
			// 查询个人主页信息
			async getUserInfo (item) {
				const result = await this.$axios.get(this.API.getUserInfo, {
					data: {
						rid: this.options.rid,
						uid: item.userID
					}
				})
				if (result) {
					this.userVisible = true
					this.userObj = result
				}
			},
			// 用户 关闭
			userClose () {
				this.userVisible = false
			},
			// 用户 更多 打开
			moreOpen (e) {
				this.userOverlayContentertop = e.detail.y + 22
				this.userOverlayVisible = true
			},
			// 用户 更多 取消
			userOverlayHide () {
				this.userOverlayVisible = false
			},
			// 获取消息列表
			getList() {
				sdkService.getMessageList({
					conversationID: `GROUP${this.form.groupID}`,
					count: 15
				}, res => {
					const { messageList } = res
					this.list = messageList
					console.log('messageList', messageList)
					sdkService.setMessageRead({
						conversationID: `GROUP${this.form.groupID}`,
					}, res => {
						console.log('setMessageRead', res)
					})
					this.scrollToButtom()
				})
			},
			// 获取群成员列表
			async getGroupMemberList () {
				this.memberList = []
				const result = await this.$axios.get(this.API.getRoomUsers, {
					params: {
						rid: this.options.rid
					}
				})
				if (result && result.length) {
					this.memberList = result || []
				}
			},
			// 群组禁言
			forbiddenWords () {
				sdkService.updateGroupProfile({
					groupID: this.form.groupID,
					muteAllMembers: !this.groupProfile.muteAllMembers
				}, res => {
					this.groupProfile = res.group
				})
			},
			// 长按复制消息
			wordLongpress (value) {
				uni.setClipboardData({
					data: value,
					success: () => {
						this.$base.Tips('已复制')
					}
				})
			},
			// 菜单 打开
			menuOpen() {
				this.menuVisible = true
				this.guideVisible = false
				this.clearGuide()
			},
			// 菜单 取消
			menuClose() {
				this.menuVisible = false
			},
			// 发送图片消息
			sendPictures () {
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 相册、相机
					success: res => {
						this.loading = true
						sdkService.sendMessage({
							to: this.form.groupID,
							conversationType: uni.$TUIKitTypes.CONV_GROUP,
							type: 'createImageMessage',
							file: res
						}, res => {
							this.loading = false
							if (res) {
								this.list.push(res.message)
								this.menuClose()
								this.scrollToButtom()
							}
						})
					}
				})
			},
			// 我想说 打开
			wordChange(type, item) {
				if (this.groupProfile.muteAllMembers) {
					return this.$base.Tips('群组已禁言')
				}
				if (type === 'news') {
					this.wordPlaceholder = `@${item.nick} `
					this.wordStatus = 'news'
					this.wordAiteUser = item
					this.wordTxt = ''
				} else {
					this.wordPlaceholder = '我想说...'
					this.wordStatus = 'ordinary'
					this.wordAiteUser = null
				}
				this.wordVisible = true
				setTimeout(() => {
					this.wordTxtFocus = true
				}, 200)
			},
			// 我想说 取消
			wordClose() {
				this.wordBlur()
				this.wordVisible = false
			},
			// 我想说 输入中
			wordInput(e) {
				this.wordTxt = e.detail.value
			},
			// 我想说 失去焦点
			wordBlur() {
				this.wordTxtFocus = false
			},
			// 我想说 发送群消息
			wordSave() {
				if (!this.wordTxt) {
					return
				}
				let params = {
					to: this.form.groupID,
					conversationType: uni.$TUIKitTypes.CONV_GROUP,
					msg: this.wordTxt
				}
				if (this.wordStatus === 'news') {
					params.msg = `@${this.wordAiteUser.nick} ${this.wordTxt}`
					params.atUserList = [this.wordAiteUser.from]
					params.type = 'createTextAtMessage'
				}
				this.loading = true
				sdkService.sendMessage(params, res => {
					this.loading = false
					if (res) {
						this.list.push(res.message)
						this.wordClose()
						this.scrollToButtom()
						this.wordTxt = ''
					}
				})
			},
			// 自己的消息上屏
			scrollToButtom () {
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this)
					query.select('#message-scroll').boundingClientRect(data => {
						this.scrollTop = data.height
					}).exec()
				})
			},
			// 礼物 打开
			giftOpen (uid) {
				this.giftVisible = true
				this.getReceiver(uid)
				this.getCanBeGivenGifts()
			},
			// 礼物 查询可赠予（已领取未赠送）的礼物列表
			async getCanBeGivenGifts () {
				const result = await this.$axios.get(this.API.getCanBeGivenGifts, {
					params: {
						userUid: uni.getStorageSync('uid'),
						page: 1
					}
				})
				this.giftList = []
				if (result) {
					const { hasNewGrantGift, canBeGivenGifts } = result
					canBeGivenGifts.unshift({
						hasNewGrantGift: hasNewGrantGift
					})
					this.setGiftGroup(canBeGivenGifts, this.giftList)
					this.giftItemId = this.giftList[0][1] ? this.giftList[0][1].sysGrantGiftId : null
				}
			},
			// 礼物 查询收礼人
			async getReceiver (uid) {
				const result = await this.$axios.get(this.API.getReceiver, {
					params: {
						teamId: this.options.teamId,
						giver: uni.getStorageSync('uid'),
						page: 1
					}
				})
				if (result && result.length) {
					this.receiverList = result
					this.receiverObj = this.receiverList[0]
				}
				if (uid) {
					this.userObj.userUid = this.userObj.uid
					this.userObj.userAvatarUrl = this.userObj.avatarUrl
					this.receiverObj = this.userObj
				}
			},
			// 礼物更多
			giftGiveSelect () {
				if (!this.receiverObj.id || !this.giftItemId) {
					return this.$base.Tips('请选择收礼人或礼物')
				}
				this.giftGiveVisible = true
			},
			// 礼物 取消
			giftClose () {
				this.giftVisible = false
			},
			// 礼物 选择组员
			giftGiveChange (item) {
				this.receiverObj = item
			},
			// 礼物 选中礼物
			giftItem (item) {
				this.giftItemId = item.sysGrantGiftId
			},
			// 礼物更多 打开
			giftMoreOpen () {
				this.giftMoreVisible = true
				this.getGiftMore()
			},
			// 礼物更多 查询未领取礼物列表
			async getGiftMore () {
				const result = await this.$axios.get(this.API.getMoreGifts, {
					params: {
						userUid: uni.getStorageSync('uid'),
						page: 1
					}
				})
				this.giftMoreList = []
				if (result && result.length) {
					this.setGiftGroup(result, this.giftMoreList)
				}
			},
			// 礼物更多 查询未领取礼物列表
			setGiftGroup (data, list) {
				let groupItem
				for (var i = 0; i < data.length; i++) {
					if ((i % 4) === 0) {
						groupItem != null && list.push(groupItem)
						groupItem = []
					}
					groupItem.push(data[i])
				}
				groupItem.length && list.push(groupItem)
			},
			// 礼物更多 领取
			async receiveGift (item, key, k) {
				const result = await this.$axios.put(this.API.acceptGift, {
					userUid: uni.getStorageSync('uid'),
					giftId: item.giftId,
					type: item.giftType
				})
				if (result) {
					this.giftMoreList[key][k].isReceived = 1
					this.giftMoreList[key][k].giftNum = 0
					this.getCanBeGivenGifts()
				}
			},
			// 礼物更多 取消
			giftMoreClose () {
				this.giftMoreVisible = false
			},
			// 礼物送给谁 取消
			giftGiveClose () {
				this.giftGiveVisible = false
			},
			// 礼物送给谁 送出
			async giftGiveSave () {
				if (!this.giftMessage) {
					return
				}
				this.loading = true
				const result = await this.$axios.post(this.API.giveGift, {
					giver: uni.getStorageSync('uid'),
					receiver: this.receiverObj.userUid,
					sysGrantGiftId: this.giftItemId,
					giftMessage: this.giftMessage,
					sourceRid: this.options.rid
				})
				this.loading = false
				if (result) {
					this.$base.Tips('礼物已送出')
					this.giftMessage = ''
					this.giftGiveClose()
					this.giftClose()
					this.userClose()
				}
			},
			// 跳转
			link(path) {
				this.menuClose()
				uni.navigateTo({
					url: path
				})
			},
			// 预览 打开
			imagePreviewChange(item) {
				uni.previewImage({
					indicator: 'none',
					urls: [item.imageInfoArray[0].url]
				})
			},
			// 获取生成海报时需要的用户头像
			async getPosterUserAvatars () {
				const result = await this.$axios.get(this.API.getPosterUserAvatars, {
					data: {
						rid: this.options.rid,
						type: 1 // 1小队海报 2礼物海报
					}
				})
				if (result) {
					this.sharewithFriends(result)
				}
			},
			// 分享到朋友圈
			async sharewithFriends (data) {
				this.loading = true
				const result = await this.$axios.post(this.API.getTeamPoster, {
					scene: `id=${this.form.teamId}&rid=${this.options.rid}`,
					path: 'pages/share/team',
					firstText: this.form.teamName,
					secondText: this.form.topic,
					avatarLst: data.avatarList || []
				})
				this.loading = false
				if (result) {
					this.playbillVisible = true
					this.playbillPic = result
					this.menuClose()
				}
			},
			// 长按保存图片
			playbillPress () {
				uni.downloadFile({
					url: this.playbillPic, //不能是本地，只能是网络路径
					success: ret => {
						if (ret.statusCode === 200) {
							uni.saveImageToPhotosAlbum({
								filePath: ret.tempFilePath,
								success: res => {
									this.$base.Tips('保存海报成功')
									this.playbillClose()
								}
							})
						}
					}
				})
			},
			// 分享海报 关闭
			playbillClose () {
				this.playbillVisible = false
				setTimeout(() => {
					this.playbillPic = ''
				}, 200)
			},
			// 学院 取消
			schoolClose () {
				this.schoolVisible = false
			},
			// 置顶
			async toTopping () {
				this.loading = true
				const result = await this.$axios.put(this.API.toppingRoom, {
					rid: this.options.rid
				})
				this.loading = false
				if (result) {
					this.$base.Tips('置顶成功')
					this.menuClose()
				}
			},
			// 结束交流
			async endCommunication () {
				uni.showModal({
					confirmText: '结束交流',
					confirmColor: '#AA2929',
					content: '是否结束当前交流？',
					success: res => {
						if (res.confirm) {
							sdkService.dismissGroup({
								groupID: this.form.groupID
							}, async res => {
								this.loading = true
								const result = await this.$axios.delete(this.API.closeCommunication, {
									params: {
										rid: this.form.rid
									}
								})
								this.loading = false
								if (result) {
									uni.navigateBack({
										delta: this.options.level || 1
									})
								}
							})
						}
					}
				})
			}
		},
		// 分享
		// -- 不关联：“邀你交流：” +「话题」，如“邀你交流：话题”
		// -- 关联校园：“邀你交流” + 「$校名」+「话题」，如“邀你交流「西天大学」话题”
		// -- 关联小队：“邀你交流” + 「$队名」+「话题」，如”邀你交流「原地爆炸小队」话题“
		// -- 关联校园和小队：“邀你交流”  + 「校名|队名」+ 「话题」，如“邀你交流「西天大学|原地爆炸小队」话题”
		onShareAppMessage(e) {
			let title = `邀你交流：${this.form.topic}`
			let path = `/pages/share/communication?id=${this.options.teamId}&rid=${this.options.rid}`
			if (this.form.school && this.form.school.id && this.form.team && this.form.team.id) {
				title = `邀你交流「${this.form.school.fullName}|${this.form.team.teamName}」${this.form.topic}`
			} else {
				if (this.form.school && this.form.school.id) {
					title = `邀你交流「${this.form.school.fullName}」${this.form.topic}`
				}
				if (this.form.team && this.form.team.id) {
					title = `邀你交流「${this.form.team.teamName}」${this.form.topic}`
				}
			}
			
			return {
				title: title, // 分享标题
				path: path, // 页面 path
				imageUrl: 'https://daifeiclub.com/image/pics/team_share.png'
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/static/css/voice_room.scss";
</style>
