<template>
	<view v-if="isShowView">
		<view class="photo" v-if="cardInfo.imageMap">
			<image :src="cardInfo.imageMap" mode="aspectFill" class="poster"></image>
		</view>
		<view class="infos">
			<view class="info dflex">
				<view class="flex">
					<view class="company">{{ cardInfo.companyName }}</view>
					<view class="name">{{ cardInfo.realName }}</view>
					<view class="job">{{ cardInfo.job }}</view>
				</view>
				<view class="logo"><image :src="cardInfo.avatar" mode="aspectFit"></image></view>
			</view>
			<view class="btns dflex" v-if="cardId">
				<button open-type="share" hover-class="none" class="share-ta">分享名片</button>
				<view class="save" @tap="addContact">保存到通讯录</view>
			</view>
			<view class="contacts" v-if="cardId || isShowContacts">
				<scroll-view scroll-x="true" class="contact">
					<view class="li" @click="goPhone()">
						<view class="lit dflex">
							<image src="../static/images/phone.png"></image>
							拨打电话
						</view>
						<view class="num">{{ cardInfo.phone }}</view>
					</view>
					<view class="li" @click="copy(cardInfo.wechat, 1)">
						<view class="lit dflex">
							<image src="../static/images/wechat.png"></image>
							复制微信
						</view>
						<view class="num">{{ cardInfo.wechat }}</view>
					</view>
					<view class="li" @click="copy(cardInfo.email, 2)">
						<view class="lit dflex">
							<image src="../static/images/message.png"></image>
							复制邮箱
						</view>
						<view class="num">{{ cardInfo.email }}</view>
					</view>
				</scroll-view>
			</view>
			<view :class="'zhan dflex' + (isShowContacts ? ' zhan-romate':'')" v-if="!cardId" @click="showContacts()">
				{{isShowContacts ? '收起' : '显示全部信息'}}
				<image src="../static/images/bico1.png" class="bico"></image>
			</view>
			<block v-if="!cardId">
				<button open-type="share" hover-class="none" class="share">发名片</button>
				<view class="opt dflex">
					<view class="li" @click="jumpUrl('/card/create/create?isEdit=true&id=' + cardInfo.id)">
						<image src="../static/images/edit.png"></image>
						<view>编辑名片</view>
					</view>
					<!-- <view class="li">
						<image src="../static/images/fx_ico.png"></image>
						<view>分享图像名片</view>
					</view> -->
					<view class="li" @click="jumpUrl('/card/poster/poster?id=' + cardInfo.id)">
						<image src="../static/images/code.png"></image>
						<view>名片码</view>
					</view>
				</view>
			</block>
			<view class="datas dflex">
				<view class="users dflex flex">
					<!-- 	<image src="../../static/images/userimg.png" mode="aspectFill"></image>
					<image src="../../static/images/userimg.png" mode="aspectFill"></image>
					<image src="../../static/images/userimg.png" mode="aspectFill"></image> -->
					<view>{{ cardInfo.person }}人看过</view>
				</view>
				<view class="zan dflex" @click="userBehavior(3)">
					<image src="../static/images/zan_ico.png"></image>
					{{ cardInfo.thumbs }}
				</view>
				<!-- <view class="renqi dflex">
					<image src="../static/images/rqico.png"></image>
					{{ cardCount.viewsNo }}
				</view> -->
			</view>
		</view>
		<view class="box brief" v-if="cardInfo.brief">
			<view class="tit dflex">
				<view class="flex dflex">
					<image src="../static/images/jj_ico.png"></image>
					<view>个人简介</view>
				</view>
				<image v-if="!cardId" src="../static/images/bj_ico.png" class="edit" @tap="jumpUrl('/card/editDesc/editDesc?id=' + cardInfo.id)"></image>
			</view>
			<view class="bri"><rich-text :nodes="cardInfo.brief"></rich-text></view>
		</view>
		<view class="box" v-if="!cardId">
			<view class="tit dflex">
				<image src="../static/images/sj_ico.png"></image>
				<view>名片数据<text>（/人次）</text></view>
			</view>
			<view class="card-datas dflex">
				<view class="li">
					<text>{{ cardInfo.todayBrowse }}</text>
					今日访问
				</view>
				<view class="li">
					<text>{{ cardInfo.browse }}</text>
					访问总量
				</view>
				<view class="li">
					<text>{{ cardInfo.share }}</text>
					名片分享
				</view>
			</view>
		</view>
		<view class="box videos" v-if="!cardId">
			<view class="tit ddflex">
				<view class="flex ddflex">
					<image src="../static/images/sp_ico.png"></image>
					<view>我的视频</view>
				</view>
				<!-- <image v-if="cardInfo.videoId" @click="uploadVodChangeHandle()" src="../static/images/bj_ico.png" class="edit"></image> -->
				<image v-if="cardInfo.videoId" @click="uploadVideo()" src="../static/images/bj_ico.png" class="edit"></image>
			</view>
			<view class="video">
				<!-- <video v-if="cardInfo.videoId" controls="true" class="video-sp" :src="videoInfo.playUrl"></video> -->
				<video v-if="cardInfo.videoId" controls="true" class="video-sp" :src="cardInfo.videoId"></video>
				<view v-else class="not" @click="uploadVideo()" v-else>
					<image src="../static/images/add_ico1.png"></image>
					<view>点击添加个人介绍视频</view>
				</view>
			</view>
		</view>
		<block v-else>
		<view class="box videos" v-if="cardInfo.videoId">
			<view class="tit ddflex">
				<view class="flex ddflex">
					<image src="../static/images/sp_ico.png"></image>
					<view>我的视频</view>
				</view>
			</view>
			<view class="video">
				<video controls="true" class="video-sp" :src="cardInfo.videoId"></video>
				<!-- <video controls="true" class="video-sp" :src="videoInfo.playUrl"></video> -->
			</view>
		</view>
		</block>
		<view class="box pic" v-if="cardInfo.pictures">
			<view class="tit dflex">
				<view class="flex dflex">
					<image src="../static/images/tp_ico.png"></image>
					<view>风采展示</view>
				</view>
				<image v-if="cardInfo.pictures && !cardId" @click="uploadImgs()" src="../static/images/bj_ico.png" class="edit"></image>
			</view>
			<view class="picture">
				<view class="pics" v-if="cardInfo.pictures">
					<image
						v-for="(item, index) in getImgList(cardInfo.pictures)"
						:key="index"
						:src="item"
						mode="widthFix"
						@tap="previewImg(getImgList(cardInfo.pictures), index)"
					></image>
				</view>
				<view class="not" v-else @click="uploadImgs()">
					<image src="../static/images/add_ico1.png"></image>
					<view>点击添加图片</view>
				</view>
			</view>
		</view>
		<!-- <view class="also" v-if="cardId">我也要创建电子名片</view> -->
		<!-- #ifdef H5 -->
		<wx-share ref="wxshare" />
		<!-- #endif -->
	</view>
</template>
<script>
const app = getApp();
const req = require('../../utils/request.js');
const api = require('../../utils/api.js');
export default {
	data() {
		return {
			isShowView:false,
			cardId: '',
			cardInfo: '',
			cardCount: '',
			isShowContacts: true,
			zhiPicUrls: [],
			scene: '',
			isFirst: true
		};
	},
	onLoad(opt) {
		if(opt.scene) this.scene = options.scene
		if(opt.appId) req.setStorage('appId',opt.appId);
		this.cardId = opt.cardId;
	},

	async onShow() {
		if (this.scene) {
		  await this.loadCodeParams();
		}
		await this.getCardInfo();
	},
	onShareAppMessage() {
		this.saveShareBehavior();
		return this.onShareMessage();
		
	},
	onShareTimeline() {
		this.saveShareBehavior();
		return {
			title: this.cardInfo.realName + ' - 电子名片',
			imageUrl: this.cardInfo.imageMap?this.cardInfo.imageMap:this.cardInfo.avatar,
			path: '/share/card/index?cardId=' + this.cardInfo.id+'&appId='+req.getStorage('appId')
		};
	},
	onReady() {
		// #ifdef H5
		var that = this;
		//初始化分享内容
		setTimeout(function() {
			var shareContent = that.onShareMessage();
			if (shareContent) {
				shareContent.path = window.location.origin + shareContent.path;
			}
			console.log('分享内容》》》》》', shareContent);
			that.$refs.wxshare.init(shareContent);
		}, 4 * 1000);
		// #endif
	},

	methods: {
		onShareMessage(){
			let path = '';
			let isSolution = '';
			// #ifndef H5
			isSolution = req.env[req.env.NODE_ENV].isSolution;
			// #endif
			// #ifdef H5
			isSolution = false;
			// #endif
			let userInfo = req.getStorage('userInfo');
			if(isSolution){
				path = '/share/home/index?appId='+req.getStorage('appId')+'&userId='+userInfo.id;
			}else{
				path = '/share/card/index?cardId=' + this.cardInfo.id + '&appId=' + req.getStorage('appId');
			}
			
			return {
				title: this.cardInfo.realName + ' - 电子名片',
				imageUrl: this.cardInfo.imageMap?this.cardInfo.imageMap:this.cardInfo.avatar,
				path: path
			};
		},
		
		
		saveShareBehavior(){
			let params = {
				behavior: 6,
				type: 23,
				bindId: this.cardInfo.id
			}
			req.saveBehavior(params,res=>{})
		},
		addContact: function() {
		    var that = this;
		    wx.showActionSheet({
		        itemList: ['添加联系人'],
		        success: function(res) {
		            // 添加到手机通讯录
		            uni.addPhoneContact({
		                firstName: that.cardInfo.realName,//联系人姓名
		                mobilePhoneNumber: that.cardInfo.phone, //联系人手机号
		                organization: that.cardInfo.companyName,//公司
		                weChatNumber: that.cardInfo.wechat,//微信
		                email: that.cardInfo.email, //电子邮件
		            })
		        }
		    })
		},
		loadCodeParams() {
			let _ts = this;
			return new Promise((resolve, reject) => {
				if (!_ts.scene) {
					resolve();
					return false;
				}
				req.getRequest(
					'/api/code/params',
					{
						scene: _ts.scene
					},
					data => {
						this.options.userId = data.userId
						this.cardId = data.scene
						resolve();
					}
				);
			});
		},
		getImgList(url) {
			var list = [];
			if (url) {
				list = url.split(',');
			}
			return list;
		},

		jumpUrl(url) {
			uni.navigateTo({
				url: url
			});
		},

		getCardInfo() {
			var url = '';
			var dataP = {};
			if (this.cardId) {
				url = api.card_info;
				dataP.id = this.cardId;
			} else {
				url = api.card_userInfo;
				dataP = {};
			}
			return new Promise((resolve, reject) => {
				req.getRequest(url, dataP, data => {
					// if(data.position){
					// 	data.position = JSON.parse(data.position)
					// }
					this.cardInfo = data;
					uni.setNavigationBarTitle({
						title: data.realName + '的名片'
					})
					if(this.cardId&&this.cardInfo.userId==req.getStorage('userInfo').id){
						this.cardId = null
						this.getCardInfo()
					}else{
						if(this.cardInfo.userId==req.getStorage('userInfo').id){
							
						}else{
							// 用户浏览
							if(this.isFirst){
								this.userBehavior(4)
							}
						}
						this.isFirst = false
					}
					// this.getCardCount();
					this.isShowView=true;
					resolve();
				});
			})
		},
		
		// 用户行为
		userBehavior(type){
			var dataP = {};
			dataP.type = 23 //、产品 2、活动 3、未知 4、内容 5、课程 6、老师 7、素材 8、题目 9、资料领取 10、招聘职位 12、用户须知 13、素材 15、医院科室 16、海报 20、医生 21 新闻 23名片
			dataP.behavior = type; //1、关注 2、收藏 3、点赞 4、浏览 5、确认 6、分享
			dataP.bindId = this.cardInfo.id;
			req.postRequestLoding('/api/v3/behavior/save', dataP, data => {
				if(type==3){
					if(!this.cardInfo.isThumbs) this.cardInfo.thumbs++;
					else this.cardInfo.thumbs--
					this.cardInfo.isThumbs = !this.cardInfo.isThumbs
				}
				if(type==1){
					this.cardInfo.follow = !this.cardInfo.follow
				}
			});
		},

		getCardCount() {
			req.getRequest(api.api_company_visits_count, { companyId: this.cardInfo.id }, data => {
				this.cardCount = data;
			});
		},

		showContacts() {
			this.isShowContacts = !this.isShowContacts;
		},

		goPhone() {
			uni.makePhoneCall({ phoneNumber: this.cardInfo.phone }); // 传参带入号码即可
		},

		copy(valueText, type) {
			uni.setClipboardData({
				data: valueText,
				success: function(res) {
					if (type == 1) {
						req.msg('微信号复制成功');
					} else if (type == 2) {
						req.msg('邮箱复制成功');
					}
				}
			});
		},

		uploadVideo() {
			let that = this;
			uni.chooseVideo({
				sourceType: ['camera', 'album'],
				success(res) {
					req.uploadFile(api.upload, res.tempFilePath, res => {
						that.updateCard(2, res.src);
					});
				}
			});
		},
		uploadImg(){
			let that = this;
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: function({ tempFilePaths }) {
					var promise = Promise.all(
						tempFilePaths.map(tempFilePath => {
							return new Promise(function(resolve, reject) {
								req.uploadFile(api.upload, tempFilePath, res => {
									that.imageMap = res.src;
									//上传完成，则更新保存
									that.updateCard(3, that.imageMap);
								});
							});
						})
					);
					promise
						.then(function(results) {
							console.log(results);
						})
						.catch(function(err) {
							console.log(err);
						});
				}
			});
		},

		uploadImgs() {
			let that = this;
			uni.chooseImage({
				count: 9,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: function({ tempFilePaths }) {
					var promise = Promise.all(
						tempFilePaths.map(tempFilePath => {
							return new Promise(function(resolve, reject) {
								req.uploadFile(api.upload, tempFilePath, res => {
									let picUrls = that.zhiPicUrls;
									that.zhiPicUrls = picUrls.concat(res.src);
									if (tempFilePaths.length == that.zhiPicUrls.length) {
										//上传完成，则更新保存
										that.updateCard(1, that.zhiPicUrls.join(','));
									}
								});
							});
						})
					);
					promise
						.then(function(results) {
							console.log(results);
						})
						.catch(function(err) {
							console.log(err);
						});
				}
			});
		},

		//预览图片
		previewImg(picUrls, index) {
			//预览合同图片
			var src = picUrls[index];
			let imgs = picUrls;
			uni.previewImage({
				current: src, // 当前显示图片的http链接
				urls: imgs
			});
		},

		cleanimages(index) {
			// 删除图片
			let arr = this.zhiPicUrls;
			arr.splice(index, 1);
			this.zhiPicUrls = arr;
		},

		/**
		 * @param {Object} type 1图片 2、视频
		 * @param {Object} url 资源地址
		 */
		updateCard(type, url) {
			var dataP = {};
			dataP.id = this.cardInfo.id;
			if (type == 1) {
				dataP.pictures = url;
			} else if (type == 2) {
				dataP.videoId = url;
			} else if (type == 3) {
				dataP.imageMap = url;
			}
			req.postRequest(api.card_saveOrUpdate, dataP, json => {
				if (type == 1) {
					this.cardInfo.pictures = url;
					this.zhiPicUrls = [];
				} else if (type == 2) {
					this.cardInfo.videoId = url;
				} else if (type == 3) {
					this.cardInfo.imageMap = url;
				}
			});
		},

		wxShare() {
			uni.share({
				provider: 'weixin',
				scene: 'WXSceneSession',
				type: 0,
				href: 'http://www.baidu.com',
				title: this.cardInfo.realName,
				summary: this.cardInfo.msg,
				imageUrl: this.cardInfo.avatar,
				success: function(res) {
					console.log('success:' + JSON.stringify(res));
				},
				fail: function(err) {
					console.log('fail:' + JSON.stringify(err));
				}
			});
		}
	}
};
</script>

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