<template>
	<view class="container">
		<view id="topnav" class="topnav flex-start" :style="{'height':`${topbarOffsetHeight-statusBarHeight}px`,'padding-top':`${statusBarHeight}px`,'background-color':`rgba(21, 17, 38,${topNavAlpha})`}" v-if="!cover.isFullScreen">
			<view class="nav-item flex-center" @click="back">
				<image :src="`${assetsUrl}back.png`" mode="widthFix" class="nav-img"></image>
			</view>
			<view class="nav-text font32 fw600">
				{{pageName}}
			</view>
			<view class="nav-item"></view>
		</view>
		<uni-popup ref="modalPopup" type="center">
			<Popup :content1="popup.content1" :content2="popup.content2" :tip1="popup.tip1" :tip2="popup.tip2" :btntext="popup.btntext" @closePopup="closePopup" @toService="toService" :btnEvent="'toService'"></Popup>
		</uni-popup>
		<uni-popup ref="popup" type="bottom" @maskClick="popupMaskClick" :safe-area="false">
			<view class="popup" @touchmove.prevent>
				<view class="p-title-box flex-between">
					<view class="p-title font36 fw600">
						上传相册
					</view>
					<image :src="`${assetsUrl}info-figure-close.png`" mode="aspectFill" class="p-close" @click="closePopup"></image>
				</view>
				<view class="p-title-tip font28 fw400">
					上传清晰本人照片更容易交到好友哦
				</view>
				<view class="p-img-box flex-between">
					<view class="p-img">
						<image :src="`${assetsUrl}info-figure-img1.png`" mode="aspectFill" class="img"></image>
						<view class="p-text font22 fw400">
							五官清晰
						</view>
					</view>
					<view class="p-img">
						<image :src="`${assetsUrl}info-figure-img2.png`" mode="aspectFill" class="img"></image>
						<view class="p-text font22 fw400">
							半身照
						</view>
					</view>
					<view class="p-img">
						<image :src="`${assetsUrl}info-figure-img3.png`" mode="aspectFill" class="img"></image>
						<view class="p-text font22 fw400">
							风景和人
						</view>
					</view>
				</view>
				<view style="height: 60rpx;">
					
				</view>
			</view>
			
		</uni-popup>
		<uni-popup ref="authPopup" type="bottom" @maskClick="authPopupMaskClick">
			<view class="auth-popup" @touchmove.prevent>
				<view class="ap-title">
					请上传本人正面清晰照片
				</view>
				<view class="ap-imgs flex-start">
					<view class="ap-img-box">
						<image :src="`${assetsUrl}auth-ap1.png`" mode="aspectFill" class="ap-img"></image>
						<view class="ap-alpha flex-center">
							<image :src="`${assetsUrl}auth-right.png`" mode="aspectFill" class="ap-right"></image>
							<view class="ap-text font30 fw400">
								清晰正脸
							</view>
						</view>
					</view>
					<view class="ap-img-box">
						<image :src="`${assetsUrl}auth-ap2.png`" mode="aspectFill" class="ap-img"></image>
						<view class="ap-alpha flex-center">
							<image :src="`${assetsUrl}auth-right.png`" mode="aspectFill" class="ap-right"></image>
							<view class="ap-text font30 fw400">
								全身/半身
							</view>
						</view>
					</view>
					<view class="ap-img-box">
						<image :src="`${assetsUrl}auth-ap3.png`" mode="aspectFill" class="ap-img"></image>
						<view class="ap-alpha flex-center">
							<image :src="`${assetsUrl}auth-right.png`" mode="aspectFill" class="ap-right"></image>
							<view class="ap-text font30 fw400">
								记得微笑
							</view>
						</view>
					</view>
					<view class="ap-img-box">
						<image :src="`${assetsUrl}auth-ap4.png`" mode="aspectFill" class="ap-img"></image>
						<view class="ap-alpha flex-center">
							<image :src="`${assetsUrl}auth-right.png`" mode="aspectFill" class="ap-right"></image>
							<view class="ap-text font30 fw400">
								光线合适
							</view>
						</view>
					</view>
				</view>
				<view style="height: 60rpx;">
					
				</view>
			</view>
			
		</uni-popup>
		<scroll-view
		scroll-y="true" 
		:style="{'height': `${scrollHeight}px`,'padding-top':`${topNavHeight}px`}"
		v-if="scrollHeight>0"
		lower-threshold="200"
		refresher-enabled="true"
		:refresher-triggered="scrollTriggered"
		:refresher-threshold="45" 
		refresher-default-style="white"
		refresher-background="#151126" 
		@refresherrefresh="scrollRefresh" 
		@refresherpulling="scrollPulling"
		@refresherrestore="scrollRestore" 
		@refresherabort="scrollAbort"
		@scrolltolower="scrollToBottom"
		class="scroll-view"
		>
			<drag-image :list="albumData" :number="1000" :custom="true" @addImage="toAddImg" @sortImage="sortImg" @delImage="deleteImg" :chooseImage="isChooseImage" @chooseEvent="chooseImageHandle"></drag-image>
		</scroll-view>
		<view class="btn-tip font24 fw400" v-if="!isChooseImage">
			长按可拖动调整图片顺序
		</view>
		<view class="btn font32 fw600" @click="sure">
			{{btnText}}
		</view>
	</view>
</template>

<script>
	import TabBar from '@/components/TabBar/TabBar.vue';
	import Popup from '@/components/Popup/Popup.vue';
	import wxMap from '@/static/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min.js';
	import DragImage from '@/components/DragImage/DragImage.vue';
	import {getPolicy,computeSignature,getKey} from '@/util/oss.js';
	import {encode} from '@/util/base64.js'
	/**
	 * 腾讯位置服务，手机账号：18996226740
	 */
	const wxMapSdk=new wxMap({key:'E5SBZ-T2YC3-CBL3F-YGFQQ-26PP2-ERFII'})
	export default {
		components:{TabBar,Popup,DragImage},
		data() {
			return {
				btnText:'去认证',
				pageName:'编辑相册',
				isChooseImage:false,//是否为选择图片模式
				assetsUrl:this.$util.assetsUrl,
				scrollHeight:0,
				topNavHeight:0,
				scrollRefreshing:false,
				scrollTriggered:true,
				showNoData:false,
				albumData:[],
				authChooseImages:[],
				moveItemAlbum:{},
				moveItemIndex:null,
				currentIndex:0,
				isSort:false,
				popup:{
					content1:'',
					content2:'',
					tip1:'',
					tip2:'',
					btntext:''
				},
			};
		},
		computed: {
			statusBarHeight() {
				return this.$store.state.statusBarHeight;
			},
			topbarOffsetHeight() {
				return this.$store.state.topbarOffsetHeight;
			},
			imageCdn(){
				return this.$store.state.imageCdn;
			},
			videoCdn(){
				return this.$store.state.videoCdn;
			}
		},
		onLoad(options) {
			if(options.type==='auth'){
				this.isChooseImage=true;
				this.btnText='前往认证';
				this.pageName='选择照片';
			}else{
				this.isChooseImage=false;
			}
			this.computedScollviewHeight()
			this.getAlbumData();
		},
		mounted() {
			
			
		},
		onPageScroll(e) {
			
		},
		methods:{
			back(){
				uni.navigateBack({
					delta:1
				})
			},
			chooseImageHandle(data){
				this.authChooseImages=data;
			},
			toAddImg(){
				this.btnText='从相册上传';
				if(this.isChooseImage){
					this.$refs.authPopup.open();
				}
				else{
					this.$refs.popup.open();
				}
				
			},
			popupMaskClick(){
				this.btnText=this.isChooseImage?'前往认证':'去认证';
			},
			authPopupMaskClick(){
				this.btnText=this.isChooseImage?'前往认证':'去认证';
			},
			closePopup(){
				this.$refs.popup.close();
				this.$refs.modalPopup.close();
				this.$refs.authPopup.close();
				this.btnText=this.isChooseImage?'前往认证':'去认证';
			},
			sortImg(ids){
				let user=JSON.parse(uni.getStorageSync('user'));
				this.$api.public.albumSort({
					completeUser:user,
					mediaIdsInSeq:ids
				}).then(res=>{})
			},
			toService(){
				this.$refs.popup.close();
				uni.openCustomerServiceChat({
				     extInfo:{
				         url:'https://work.weixin.qq.com/kfid/kfca1b21d2f7e8a18e9',//客服链接
				     },
				     corpId:'wwa8f2a0d8a6dc0950',//企业ID
				     fail(res){
						 console.log(res)
				         wx.showToast({
				           title: '客服联系失败',
				           icon:'none'
				         })
				     }
				 })
			},
			/**
			 * 计算scroll高度
			 */
			computedScollviewHeight() {
				let query = uni.createSelectorQuery().in(this);
				let heightLeaf =0;
				query.select('#topnav').boundingClientRect(data => {
					this.topNavHeight=data.height;
					heightLeaf += data.height;
				}).exec(() => {
					let sysInfo = uni.getSystemInfoSync();
					this.scrollHeight = sysInfo.windowHeight - heightLeaf;
				});
			
			},
			/**
			 * 推荐下拉刷新、加载更多
			 */
			scrollRefresh(){
				if (this.scrollRefreshing) 
				{
					return;
				}
				this.scrollRefreshing = true;
				setTimeout(() => {
					this.scrollTriggered = false;
					this.scrollRefreshing = false;
				}, 1000)
				this.getAlbumData();
			},
			scrollPulling(e) {},
			scrollRestore() {this.scrollTriggered = true;},
			scrollAbort() {},
			scrollToBottom(){

			},
			getAlbumData(){
				let user=JSON.parse(uni.getStorageSync('user'));
				this.$api.public.album({uurd:user.id}).then(res=>{
					for(let i=0;i<res.data.dms.length;i++){
						res.data.dms[i].isMove=false;
					}
					let arr=[];
					if(this.isChooseImage){
						for(let i=0;i<res.data.dms.length;i++){
							if(res.data.dms[i].cate==='Img'){
								arr.push(res.data.dms[i])
							}
						}
						this.albumData=arr;
					
					}
					else{
						this.albumData=res.data.dms;
					}
					
				})
			},
			deleteImg(index){
				this.$api.public.albumDelete({mediaId:this.albumData[index].mediaId}).then(res=>{})
			},
			sure(){
				if(this.btnText==='从相册上传'){
					
					this.addImg();
				}
				else{
					this.popup={
						content1:'进行认证流程需给客服回复关键词',
						content2:'「真人认证」',
						tip1:'',
						tip2:'',
						btntext:'联系客服去认证'
					}
					this.$refs.modalPopup.open();
				}
			},
			
			async addImg(){
				const that=this;
				this.closePopup();
				
				uni.chooseMedia({
				  count: 9,
				  mediaType: this.isChooseImage?['image']:['image','video'],
				  sourceType: ['album', 'camera'],
				  maxDuration: 30,
				  camera: 'back',
				  success(res) {
					uni.showLoading({
						mask:true,
						title:"正在上传···"
					})
						let arr=[],obj={},imageCdn='',videoCdn='';
						
						
						for(let i=0;i<res.tempFiles.length;i++){
							obj={
								cate:res.tempFiles[i].fileType==='image'?'Img':'Vdo',
								cdt:'General',
								env:'Album',
								url:null
							}
							const policyText=getPolicy();
							const policy=encode(JSON.stringify(policyText));
							const key=getKey(i,res.tempFiles[i].tempFilePath.split('.')[1]);
							that.$api.public.aliossToken({}).then(resuslt=>{
								let formData={
									key:key,
									policy:policy,
									OSSAccessKeyId:resuslt.data.accessKeyId,
									signature:computeSignature(resuslt.data.accessKeySecret,policy),
									'x-oss-security-token':resuslt.data.securityToken,
									success_action_status:'200'
								}
								uni.uploadFile({
									url: 'https://zhenyanapp-gen.oss-cn-qingdao.aliyuncs.com',
									filePath: res.tempFiles[i].tempFilePath,
									name: 'file',
									header:{
										"Content-Type": "multipart/form-data"
									},
									formData: formData,
									success: (data) => {
									    if (data.statusCode === 200) {
										  if(obj.cate==='Img'){
											  let link=`${that.imageCdn}/${key}`;
											  obj.url=link;
										  }
										  else if(obj.cate==='Vdo'){
											  let link=`${that.videoCdn}/${key}`;
											  obj.url=link;
										  }
										  arr.push(obj);
										  if(arr.length===res.tempFiles.length){
											    that.$api.public.albumAdd({addMediaParamList:arr}).then(mapResult=>{
													if(mapResult.status==='Succ'){
														that.getAlbumData();
														uni.hideLoading();
													}
											    })
										  }
									    }
									},
									fail: err => {
									    console.log(err);
									  }
								})
							})
							
						}
				  }
				})
			},
		}
			
	}
</script>

<style lang="scss" scoped>
.container{
	width: 100vw;
	height: 100vh;
	background-color: $bgcolor1;
	position: relative;
	.topnav {
		padding: 0 10rpx;
		position: fixed;
		top: 0;
		left: 0;
		width: 100vw;
		z-index: 100;
		backdrop-filter: blur(10px);
		.nav-item {
			width: 40rpx;
			height: 40rpx;
			margin-left: 16rpx;
			.nav-img{
				width: 40rpx;
				height: 40rpx;
			}
			
		}
		.nav-text{
			flex: 1;
			color: $fontcolor5;
			height: 40rpx;
			text-align: center;
		}
	}
	.popup{
		width: 100vw;
		box-sizing: border-box;
		padding: 56rpx 60rpx;
		background-color: $bgcolor3;
		.p-title-box{
			.p-title{
				color: $fontcolor5;
			}
			.p-close{
				width: 40rpx;
				height: 40rpx;
			}
		}
		.p-title-tip{
			color: $fontcolor3;
			margin-top: 16rpx;
		}
		.p-img-box{
			margin-top: 80rpx;
			padding-bottom: 100rpx;
			.p-img{
				.img{
					width: 200rpx;
					height: 200rpx;
				}
				.p-text{
					color: $fontcolor2;
					text-align: center;
				}
			}
		}
	}
	.auth-popup{
		background-color: bgcolor1;
		border-radius: 40rpx 40rpx 0rpx 0rpx;
		.ap-title{
			color: #ffffff;
			text-align: center;
		}
		.ap-imgs{
			flex-wrap: wrap;
			margin: 80rpx 64rpx 50rpx 64rpx;
			.ap-img-box{
				width: 306rpx;
				height: 306rpx;
				border-radius: 8rpx;
				overflow: hidden;
				margin-right: 10rpx;
				margin-bottom: 10rpx;
				position: relative;
				&:nth-of-type(2n){
					margin-right: 0rpx;
				}
				.ap-img{
					width: 306rpx;
					height: 306rpx;
				}
				.ap-alpha{
					position: absolute;
					width: 306rpx;
					height: 80rpx;
					bottom: 0;
					left: 0;
					background: rgba(0,0,0,0.3);
					.ap-right{
						width: 48rpx;
						height: 48rpx;
					}
					.ap-text{
						color: #ffffff;
					}
				}
			}
		}
	}
	.scroll-view{
		position: relative;
		padding: 0rpx 30rpx;
		box-sizing: border-box;
		.move-area{
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			flex-wrap: wrap;
			align-items: flex-start !important;
			.img-box{
				width: 216rpx;
				height: 216rpx;
				border-radius: 8rpx;
				position: relative;
				z-index: 1;
				margin-right: 19rpx;
				margin-top: 20rpx;
				&:nth-of-type(3n){
					margin-right: 0rpx;
				}
				.img-add{
					width: 216rpx;
					height: 216rpx;
					border-radius: 8rpx;
				}
				.img-delete{
					position: absolute;
					right: 16rpx;
					top: 16rpx;
					width: 40rpx;
					height: 40rpx;
				}
			}
			
		}
	}
	.btn-tip{
		position: fixed;
		z-index: 1;
		left: 0;
		right: 0;
		bottom: 160rpx;
		margin: auto;
		width: 630rpx;
		height: 50rpx;
		color: #9A9ABF;
		text-align: center;
		line-height: 50rpx;
	}
	.btn{
		position: fixed;
		z-index: 999;
		left: 0;
		right: 0;
		bottom: 44rpx;
		margin: auto;
		width: 630rpx;
		height: 104rpx;
		border-radius: 52rpx;
		background-color: $primary;
		color: $fontcolor5;
		text-align: center;
		line-height: 104rpx;
	}
}
</style>
