<template>
	<view v-if="isShowView">
		<view class="top" :style="'height:' + systems.barHeight + 'rpx;'">
			<navigator open-type="navigateBack" hover-class="none" class="back" :style="'height:' + systems.navigationHeight + 'rpx;top:' + systems.ktxStatusHeight + 'rpx;'">
				<image src="../static/images/back_black.png"></image>
			</navigator>
		</view>
		<view class="c-top">
			<view class="top-img">
				<image :src="config.COMMENT_TOP_IMG?config.COMMENT_TOP_IMG:'../static/images/topimg.png'" class="pic"></image>
				<!-- <image src="../static/images/topbg.png" class="topbg"></image> -->
			</view>
			<view class="t-user ddflex">
				<image :src="userDetail.avatar ? userDetail.avatar : '/static/images/def_head.png'" class="t-userimg"></image>
				<navigator v-if="userId == userInfo.id" url="/mine/userinfo/userinfo" hover-class="none" class="edit ddflex">
					<image src="../static/images/edit.png"></image>
					编辑资料
				</navigator>
				<view v-else class="guanzhu ddflex" @click="behaviorOpt()">
					{{isFocus ? '取消关注':'+关注'}}
				</view>
			</view>
			<view class="t-name ddflex">
				<view>{{ userDetail.nickName }}</view>
				<image v-if="isOpenWeRunData" style="width:22rpx;height:26rpx;margin-left: 10rpx;" src="../../static/images/yd.png"></image>
				<!-- <text>详细资料</text>
				<image src="../static/images/rico.png" class="rico"></image> -->
			</view>
			<view class="bri ddflex">
				<view>简介：</view>
				<rich-text :nodes="userDetail.brief ? userDetail.brief : '暂无~'" class="fflex"></rich-text>
			</view>
			<view class="tuan ddflex" v-if="userDetail.levelGrade == 2 || userDetail.levelGrade == 4">
				<image v-if="userDetail.levelGrade == 2" src="../static/images/tuan.png"></image>
				<image v-if="userDetail.levelGrade == 4" src="../../static/images/tuan.png"></image>
				{{ userDetail.levelName }}
			</view>
			<view class="datas ddflex">
				<view class="fflex" @click="jumpFans()">
					<text>{{ userDetail.count.fansNo }}</text>
					<view>关注</view>
				</view>
				<view @click="jumpCollection()" class="fflex">
					<text>{{ userDetail.count.collectionNo }}</text>
					<view>收藏</view>
				</view>
				<view class="fflex">
					<text>{{ userDetail.count.praiseNo }}</text>
					<view>获赞</view>
				</view>
			</view>
		</view>
		
		
		
		<!-- 加入团队 -->
		<view class="m-team" v-if="myTeamList.length>0">
			<view class="m-tits ddflex" @click="jumpUrl('/office/myTeam/index')">
				<view class="fflex">加入的团队</view>
			</view>
			<view class="map-team">
				<scroll-view scroll-x="true" class="map-teams">
					<view class="li" v-for="(item,index) in myTeamList" :key="index" @click="jumpUrl('/office/team/index?id='+item.id)">
						<view class="ddflex">
							<image :src="item.url?item.url:picUrlss+'office_images/team_default.png'" mode="aspectFill"></image>
							<view class="fflex">
								<view class="tover">{{item.title?item.title:'cessss'}}</view>
								<text>{{item.memberNum}}成员</text>
							</view>
							<view class="li-btn" @click.stop="joinTeam(item,index)">{{item.isJoin == 1 ? '已加入':'加入'}}</view>
						</view>
					</view>
				</scroll-view>
			</view> 
		</view>
		
		<!-- 参与活动 -->
		<view class="ac-team" v-if="userMatchList.length>0">
			<view class="ac-tits ddflex">
				<view class="fflex">参与活动</view>
				<!-- <view>
					<text style="color: #999;">更多</text>
					<image src="/static/images/moreico.png" class="rico"></image>
				</view> -->
			</view>
			<view class="map-ac">
				<scroll-view scroll-x="true" class="map-acs" >
					<view class="li" v-for="(item,index) in userMatchList" :key="index" @click="jumpUrl('/match/activityDetail/activityDetail?id='+item.id)">
						<view style="position: relative;border-radius: 20rpx;overflow: hidden;">
							<image :src="item.pic ? item.pic : '/static/images/def_zw1.png'" mode="aspectFill"></image>
							<view class="ac-type" v-if="item.categoryName">{{ item.categoryName }}</view>
						</view>
						<view class="ac-title tover">{{ item.title }}</view>
						<view class="ac-date">赛事日期：{{ item.time }}</view>
					</view>
				</scroll-view>
			</view> 
		</view>
		
		<!-- 自己 -->
		<!-- <view class="tab ddflex" v-if="userId == userInfo.id">
			<view :class="'li ' + (type == 1 ? 'active' : '')" @click="swiType(1)">动态</view>
			<view :class="'li ' + (type == 2 ? 'active' : '')" @click="swiType(2)">提问</view>
			<view :class="'li ' + (type == 3 ? 'active' : '')" @click="swiType(3)">日记</view>
		</view> -->
		<view class="list" v-if="pageList && pageList.length > 0">
			<view style="font-size: 28rpx;font-weight: bold;padding: 30rpx 30rpx 0;color: #333;">全部动态({{total}})</view>
			<view class="li" v-for="(item, index) in pageList" :key="index">
				<view class="user ddflex">
					<image :src="item.userDTO.avatar" mode="aspectFill" class="userimg" @click="toUserHomePage(item.userDTO.id)"></image>
					<view class="fflex">
						<view class="namea ddflex">
							<view class="name fflex ddflex" @click="toUserHomePage(item.userDTO.id)">
								{{ item.userDTO.nickName }}
								<image v-if="item.userDTO.levelGrade > 0" src="../../static/images/vip_tag.png" class="vip-tag"></image>
							</view>
							<view class="time">{{ item.time }}</view>
						</view>
						<view class="area" @click="toUserHomePage(item.userDTO.id)" v-if="item.userDTO.cityName">{{ item.userDTO.provinceName }} {{ item.userDTO.cityName }}</view>
					</view>
				</view>
				<!-- 分享的动态 -->
				<block v-if="item.source">
					<view class="link ddflex" @click="jumpUrlDetail(item)">
						<block v-if="item.url&&item.url.length>0"><image mode="aspectFill" v-if="idx == 0" v-for="(it, idx) in item.url" :src="it" :key="idx"></image></block>
						<view class="fflex tover"><rich-text :nodes="item.content"></rich-text></view>
					</view>
				</block>
				<!-- 非分享的动态 -->
				<block v-else>
					<view v-if="item.type == 2" class="des tovers" @click="jumpUrlDetail(item)">
						<view class="wen">提问</view>
						{{ removeHtml(item.content) }}
					</view>
					<view class="des" v-else @click="jumpUrlDetail(item)"><rich-text :nodes="item.content"></rich-text></view>
					
					
					<!-- //如果有投票，就不显示图片 -->
					<block v-if="!item.qyPoll">
					<view class="video" v-if="item.isHaveVideo && config.open_community_video == 1">
						<video :src="item.url" :show-center-play-btn="false" :controls="item.isControls" :autoplay="item.isControls" :id="'myVideo'+index" @pause="videoPause(index)" @ended="videoEnded(index)"></video>
						<view class="video-play ddflex" @click="videoPlay(index)" v-if="item.isShowPlayBtn"><image src="../../static/images/play.png"></image></view>
					</view>
					<view class="imgbox ddflex" @click="jumpUrlDetail(item)" v-if="!item.isHaveVideo"><!-- @click="previewImgss(item.url, idx)" -->
						<block v-if="item.url&&item.url.length>0">
							<image mode="aspectFill" v-for="(it, idx) in item.url" :src="it" :key="idx"></image>
						</block>
					</view>
					</block>
					<!-- 话题 -->
					<view class="ddflex" v-if="item.qyDialogu&&item.qyDialogu.isExamine==1">
						<view class="topic ddflex" @click="jumpUrl('/topics/detail/detail?topicId=' + item.qyDialogu.id)">
							<image src="../../static/images/topic.png"></image>
							{{ item.qyDialogu.title }}
						</view>
					</view>
					<view class="loca ddflex" @click="jumpUrlPoi(item,'/office/poi/index')" v-if="item.poiName"><image :src="picUrlss+'office_images/loca.png'"></image><text v-if="item.poiDistance > 0">{{item.poiDistance ? item.poiDistance < 1000 ? item.poiDistance+'m' : (item.poiDistance/1000).toFixed(1)+'km' : ''}}</text>{{item.poiName}}</view>
					<!-- 投票 -->
					<view :class="'vote-box' + (item.qyPoll.isEnd ? ' ends' : '')" v-if="item.qyPoll">
						<view class="vote-tit">{{ item.qyPoll.title }}</view>
						<block v-if="item.qyPoll.isVote == 1">
							<view class="vote-list end" @click="jumpUrlDetail(item)">
								<view :class="'lis ddflex  ' + (itpy.isVote == 1 ? 'active' : '')" v-for="(itpy, idex) in JSON.parse(item.qyPoll.optionJson)" :key="idex">
									<view class="percent" :style="'width:' + parseFloat(itpy.proportion) + '%;'"></view>
									<view class="fflex">{{ itpy.name }}</view>
									<view>{{ parseFloat(itpy.proportion) + '%' }}</view>
								</view>
							</view>
						</block>
						<block v-else>
							<view class="vote-list">
								<view class="lis" v-for="(itpy, idex) in JSON.parse(item.qyPoll.optionJson)" :key="idex" @click="submitPoll(item, index, idex)">
									{{ itpy.name }}
								</view>
							</view>
						</block>
						<view class="vote-can" v-if="item.qyPoll.isEnd"><text>{{item.qyPoll.voteCount}}人参与</text>投票已结束</view>
					</view>
					<block v-if="item.type==10||item.type==11">
						<view v-if="item.type==10" class="ddflex step-box" style="justify-content: space-between;" @click="jumpUrl('/exercise/record/record?userId=' + item.userId)">
							<view>
								<view class="step-date">{{item.wxRun.step}}</view>
								<view class="step-label">步数</view>
							</view>
							<view>
								<view class="step-date">{{item.wxRun.index}}</view>
								<view class="step-label" style="text-align: right;">名次</view>
							</view>
						</view>
						<view v-if="item.type==11" class="ddflex step-box" style="justify-content: space-between;" @click="jumpUrl('/match/activityDetail/activityDetail?id=' + item.matchContent.id)">
							<image class="step-pic" :src="item.matchContent.pic" mode="aspectFill"></image>
							<view class="fflex">
								<view class="step-title tovers">{{item.matchContent.title}}</view>
								<view class="ddflex" style="justify-content: space-between;margin-top: 10rpx;">
									<view class="step-price">{{item.matchContent.endTime}}</view>
									<view  class="step-btn">查看</view>
								</view>
							</view>
						</view>
					</block>
					<view v-if="item.userGroupId" class="ddflex step-box" style="padding: 25rpx 21rpx;" @click="jumpUrl('/office/team/index?id=' + item.userGroupId)">
						<image style="width: 24rpx;height: 24rpx;margin-right: 13rpx;" src="../../static/images/link.png"></image>
						<view style="font-weight: 500;color: #999999;">Team：</view>
						<view>{{item.userGroupTitle}}</view>
					</view>
					<block v-else>
						<view class="product" v-if="item.products && item.products.length > 0">
							<view scroll-x="true" :class="'pro-view' + (item.products.length == 1 ? ' pro-view1' : '')">
								<view class="li" v-for="(it, idx) in item.products" :key="idx" @click="toProductDetail(it)">
									<view class="ddflex">
										<image :src="it.pic" mode="aspectFill" class="pro-pic"></image>
										<view class="fflex">
											<view class="title tovers">{{ it.title }}</view>
											<view class="opts ddflex">
												<view class="money">￥{{ it.salePrice }}</view>
												<view class="pro-btn">购买</view>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</block>
				</block>
				<view class="opt ddflex" v-if="!item.source && type != 3">
					<view class="fflex" @click="jumpUrlDetail(item)">{{ item.count.browseCount }}次浏览</view>
					<view class="ddflex" @click="submitFabulous(2, item.id, index)">
						<image :src="'../../static/images/' + (item.isPraise == 1 ? 'like_h' : 'like') + '.png'"></image>
						{{ item.count.fabulousCount < 99 ? item.count.fabulousCount : '99+' }}
					</view>
					<view class="ddflex" @click="jumpUrlDetail(item)">
						<image src="../../static/images/comment.png"></image>
						{{ item.count.commentCount < 99 ? item.count.commentCount : '99+' }}
					</view>
					<button open-type="share" class="opt-share ddflex">
						<image src="../../static/images/share.png"></image>
						分享
					</button>
				</view>
			</view>
		</view>
		<view class="nodata" v-else>
			<image :src="picUrlss + 'empty_jl.png'"></image>
			<text>{{ type == 1 ? '暂无动态' : type == 2 ? '暂无提问' : type == 3 ? '暂无日记' : '' }}</text>
		</view>
	</view>
</template>
<script>
//获取应用实例
const app = getApp();
const req = require('../../utils/request.js');
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
export default {
	data() {
		return {
			picUrlss: req.public.picUrls,
			systems: {},
			userInfo: '',
			isLoad: true,
			form: {
				page: 1,
				limit: 10
			},
			type: 1, //1 聊一聊，2提问  3日记
			pageList: [],
			isShowView: false,
			userId: '',
			userDetail: '',
			videoCurrent: null,
			videoContext: '',
			config: {},
			currentPoi: {},
			total:0,
			isFocus: false,//是否已关注
			myTeamList:[],
			exreciseData:{},
			isOpenWeRunData:false,
			userMatchList:[]
		};
	},
	onLoad(opt) {
		this.userId = opt.userId;
		this.userInfo = req.getStorage('userInfo');
		this.getOfficeList();
		this.getUserTeam()
		this.getUserMatchList()
	},

	onShow() {
		this.getUserDetail();
		this.getFocusState();
		this.config = JSON.parse(req.getStorage('configRes'))
	},

	onReachBottom() {
		this.form.page++;
		this.getOfficeList();
	},

	methods: {
		jumpUrl(url) {
			uni.navigateTo({
				url: url
			});
		},
		jumpUrlPoi(item,url){
			this.currentPoi = item;
			uni.navigateTo({
				url: url
			})
		},
		removeHtml(content) {
			return util.removeHtml(content);
		},
		jumpCollection() {
			if (this.userId == this.userInfo.id) {
				this.jumpUrl('/topics/release/release?type=2');
			}
		},
		jumpFans() {
			if (this.userId == this.userInfo.id) {
				this.jumpUrl('/topics/fans/fans?type=2');
			}
		},
		//预览图片
		previewImgss(picUrls, index) {
			//预览合同图片
			var src = picUrls[index];
			let imgs = picUrls;
			uni.previewImage({
				current: src, // 当前显示图片的http链接
				urls: imgs
			});
		},

		jumpUrlDetail(item) {
			//日记，不做跳转
			if(this.type==3){
				return;
			}
			if (item.source) {
				this.jumpUrl('/office/detail/detail?contentId=' + item.source);
			} else {
				this.jumpUrl('/office/detail/detail?contentId=' + item.id);
			}
		},
		toProductDetail(it) {
			if (!req.isLogins(true)) {
				return;
			}
			if(it.actId){
				app.globalData.openPage('group/detail/detail?id=' + it.id + '&groupId=' + it.actId);
			}else{
				app.globalData.openPage('product/detail/detail?id=' + it.id);
			}
		},
		toUserHomePage(userId) {
			this.jumpUrl('/topics/home/home?userId=' + userId);
		},

		//切换类型
		swiType(type) {
			this.isLoad = true;
			this.form.page = 1;
			this.type = type;
			this.getOfficeList();
		},

		getUserDetail() {
			req.getRequest('/api/v3/moments/getUser', { userId: this.userId }, data => {
				this.userDetail = data;
				this.isShowView = true;
			});
		},
		
		sum(arr) {
		    var s = 0;
		    for (var i=arr.length-1; i>=0; i--) {
				if(arr[i].count){
					s += Number(arr[i].count);
				}
		    }
		    return s;
		},
		
		getOfficeList() {
			let that = this;
			var pramData = this.form;
			// pramData.type = this.type;
			pramData.orderType = 2;
			pramData.userId = this.userId;
			if (!this.isLoad) return false;
			this.isLoad = false;
			req.getRequest('/api/v3/moments/page', pramData, data => {
				if(data.list&&data.list.length > 0){
					this.total = data.total
					data.list.map(it=>{
						if(it.qyPoll && it.qyPoll.isEnd){
							it.qyPoll.voteCount = that.sum(JSON.parse(it.qyPoll.optionJson))
						}
						if(it.url){
							let h = it.url.substring(it.url.lastIndexOf('.') + 1)
							if(h.indexOf('mp4')<0&&h.indexOf('MP4')<0){
								it.url = it.url.split(',');
							}else{
								it.isHaveVideo = true
								it.isControls = false
								it.isShowPlayBtn = true
							}
						}
						it.content = '<div style="overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-line-clamp: 5;-webkit-box-orient: vertical;word-break: break-all;">' + it.content + '</div>'
						return it;
					})
				}
				if (data.list && data.list.length >= this.form.limit) {
					this.isLoad = true;
				}
				if (this.form.page > 1) {
					data.list = this.pageList.concat(data.list);
				}
				this.pageList = data.list;
				this.isShowView = true;
			});
		},
		//提交点赞、取消点赞；收藏、取消收藏
		submitFabulous(type, id, index) {
			if (!req.isLogins(true)) {
				return;
			}
			var dataP = {};
			dataP.type = type; //1，观看 ，2点赞，3评论，4分享，5收藏
			dataP.momentsId = id;
			req.postRequestLoding('/api/v3/fabulous/save', dataP, data => {
				if (type == 2) {
					//动态点赞
					if (this.pageList[index].isPraise == 1) {
						//已赞
						this.pageList[index].isPraise = 0;
						this.pageList[index].count.fabulousCount--;
						req.saveBehaviorNew(id, this.pageList[index].pollId?10:11,11)
					} else {
						this.pageList[index].isPraise = 1;
						this.pageList[index].count.fabulousCount++;
						req.saveBehaviorNew(id, this.pageList[index].pollId?10:11,3)
					}
				}
			});
		},

		//提交投票
		submitPoll(item, pIndex, pollIndex) {
			if(item.qyPoll.isEnd) return false;
			var dataP = {};
			// dataP.id = item.id;
			dataP.pollId = item.qyPoll.id;
			var pollObjList = JSON.parse(item.qyPoll.optionJson);
			dataP.pollOptionCode = pollObjList[pollIndex].code;
			req.postRequest('/api/v3/poll/saveDetails', dataP, data => {
				req.msg('投票成功');
				//图片完之后要将该投票的对象返回，便于做渲染%
				this.pageList[pIndex].qyPoll = data;
				req.saveBehaviorNew(item.id,10,5)
			});
		},
		videoPlay(index){
			var that = this;
			var curIdx = index;
			this.pageList[index].isControls = true
			this.pageList[index].isShowPlayBtn = false
			// 有播放时先将prev暂停，再播放当前点击的current
			if (that.videoCurrent != null) {
				var videoContextPrev = uni.createVideoContext('myVideo' + that.videoCurrent)
				if (that.videoCurrent != curIdx) {
					this.pageList[that.videoCurrent].isControls = false
					this.pageList[that.videoCurrent].isShowPlayBtn = true
					
					videoContextPrev.stop()
				}
				that.videoCurrent = curIdx
				var videoContextCurrent = uni.createVideoContext('myVideo' + curIdx)
				videoContextCurrent.play()
			} else {  
				// 没有播放时播放视频
				that.videoCurrent = curIdx
				var videoContext = uni.createVideoContext('myVideo' + curIdx) // 对应的视频id
				videoContext.play()
			}
		},
		videoPause(index){
			this.pageList[index].isControls = false
			this.pageList[index].isShowPlayBtn = true
		},
		videoEnded(index){
			this.pageList[index].isControls = false
			this.pageList[index].isShowPlayBtn = true
		},
		behaviorOpt(){
			if(this.isFocus){
				this.delFocus()
			}else{
				this.focusOn()
			}
		},
		focusOn(){
			let params = {
				behavior: 1,
				bindId: this.userId,
				type: 11
			}
			req.postRequest(api.behavior_save,params,data=>{
				req.msg('已关注');
				setTimeout(()=>{
					this.getFocusState();
				},1000)
				this.getUserDetail();
			})
		},
		delFocus(){
			let params = {
				behavior: 1,
				bindId: this.userId,
				type: 11
			}
			req.postRequest(api.behavior_save,params,data=>{
				req.msg('已取消关注');
				setTimeout(()=>{
					this.getFocusState();
				},1000)
				this.getUserDetail();
			})
		},
		getFocusState(){
			let params = {
				behavior: 1,
				bindId: this.userId,
				type: 11,
				uid:req.getStorage('userInfo').id
			}
			req.getRequest(api.behavior_get,params,data=>{
				this.isFocus = data;
			})
		},
		// 用户加入的团队
		getUserTeam(){
			let form = {
				teamType:3,
				userId:this.userId
			};
			req.getRequest(api.user_team_list,form,data=>{
				this.myTeamList = data.list
			})
		},
		// 获取运动统计数据
		getExreciseData(){
			req.getRequest('/api/v3/wxRun/todayInfo', {userId:this.userId}, data => {
				this.exreciseData = data
			})
		},
		// 获取用户已参加活动
		getUserMatchList(){
			req.getRequest('/api/match/user', {uid:this.userId,type:'ycs'}, data => {
				this.userMatchList = data
			})
		},
		// 数字格式化
		unitConverter(num){
			return util.unitConverter(num)
		},
		joinTeam(item,index){
			if(item.isJoin == 1) {
				uni.navigateTo({
					url: '/office/team/index?id='+item.id
				})
				return false;
			}
			if(item.relationMatch){
				uni.navigateTo({
					url: '/match/activityDetail/activityDetail?id='+item.relationMatch.id
				})
				return false;
			}
			req.postRequest(api.user_team_follow,{userGroupId: item.id},data=>{
				req.msg('加入团队成功');
				item.isJoin=1
			})
		}
	},
	created() {
		const systemInfo = uni.getSystemInfoSync();
		// px转换到rpx的比例
		let pxToRpxScale = 750 / systemInfo.windowWidth;
		let systems = {
			ktxStatusHeight: systemInfo.statusBarHeight * pxToRpxScale, // 状态栏的高度
			navigationHeight: 44 * pxToRpxScale // 导航栏的高度
		};
		systems.barHeight = systems.ktxStatusHeight + systems.navigationHeight;
		this.systems = systems;
	}
};
</script>

<style>
@import './home.css';
</style>
