<template>
	<div class="container">
		<top-bar :theme="topBarTheme" 
		:title="topBarTitle"
		:backAction="'goHome'"
		@goHome="goHome">
		</top-bar>
		<van-popup v-model="exchangePopup" round closeable>
			<div class="panel">
				<p class="p-title">兑换颜豆</p>
				<p class="p-text">本次兑换将消耗<span style="color: #F74C31;">{{exchangeNum/10}}元</span>,兑换后不可反悔</p>
				<div class="p-exc">
					<div class="pe-pirce-box">
						<p class="pe-num">{{exchangeNum/10}}</p>
						<p class="pe-unit">元</p>
					</div>
					<img class="pe-exchange" src="~@/assets/wallet/exchange.png">
					<div class="pe-pirce-box">
						<img src="~@/assets/wallet/yd.png" class="pe-yd">
						<p class="pe-unit" style="font-weight: bolder;">{{exchangeNum}}颜豆</p>
					</div>
				</div>
				<div class="p-btn" @click="exchange">确认兑换</div>
				<div class="p-tip">
					点击“确认兑换”将进行面容识别,
				</div>
				<div class="p-tip">
					以确保余额安全。
				</div>
			</div>
		</van-popup>
		<div class="top-box">
			<img src="~@/assets/wallet/exchange_bg.png" class="top_bg">
			<div class="top-info">
				<div class="top-label">
					可兑换金额(元)
				</div>
				<div class="top-price-box">
					<img src="~@/assets/wallet/unit.png" class="tpb-unit">
					<span class="tpb-num">{{totalMoney}}</span>
					<span class="rule">1元=10颜豆</span>
				</div>
			</div>
		</div>
		<div class="form-box">
			<div class="form-title">兑换颜豆</div>
			<div class="form-input-box">
				<div class="fib-left">
					<img src="~@/assets/wallet/yd.png" class="fib-img">
					 <input v-model="exchangeNum" 
					 type="number" 
					 class="fib-input"
					 maxlength="5"
					 v-on:keyup="numInput($event)"
					 :style="{'color':`${inputError?'#FF6A6A':''}`}"
					 placeholder="请输入要兑换的颜豆数量" />
				</div>
			</div>
			<div class="tip-box">
				<div class="tip" :style="{'color':`${inputError?'#FF6A6A':'#999999'}`}">
					{{inputErrorText}}
				</div>
				<div class="all" @click="allEx">
					全部兑换
				</div>
			</div>
			<div class="btn-box" @click="showExchangePopup" :style="{'background':`${!inputError&&exchangeNum>0?'#FFC107':'#FFE699'}`}">
				立即兑换
			</div>
			<div class="prot-box">
				<span class="prot-text">点击“立即兑换”代表你同意<span style="color:#9580FF;text-decoration: underline;" @click="toLink('https://h5.sugarpark.cn/agreement/jx/yanbean-buy.html')">《颜豆购买协议》</span></span>
			</div>
		</div>

		<div class="null-box">
		
		</div>
	</div>
</template>

<script>
	import topBar from "@/views/wallet/components/topBar.vue";
	import {getBiztoken,getFaceResult} from '@/util/faceAuth.js'
	import {isMobile,isIphoneX,isSafari,toDecimal2,dataURLtoFile} from '@/util/index.js';
	export default {
	    name: "exchange",
		components:{topBar},
	    data() {
			return{
				topBarTitle:'兑换颜豆',
				topBarTheme:'white',
				exchangePopup:false,
				topBarActionText:'遇到问题',
				exchangeNum:null,//颜豆数量
				inputErrorText:'',
				inputError:false,
				totalMoney:0,
			}
		},
		created() {
			
			if(location.href.indexOf('result_id')!==-1&&localStorage.exResultOrderId!==localStorage.createIncomeOrderId){//获取活体检测结果
				this.getResult();
			}
			
		},
		mounted() {
			this.totalMoney=parseInt(this.$store.state.withdrawMyInfo.canAmountFen);
			this.$nextTick(() => {
			      // 监听滚动条
			      window.addEventListener("scroll", this.handleScroll);
			});
			if(this.totalMoney===0){
				this.inputErrorText=`暂无可兑换颜豆`;
				this.inputError=true;
				return
			}
			this.inputErrorText=`当前最多可兑换颜豆${this.totalMoney*10}个`;
			
		},
		computed:{
			withdrawMyInfo(){
				return this.$store.state.withdrawMyInfo;
			}
		},
		methods:{
			goHome(){
				this.$router.replace({name:'walletHome'});
			},
			toLink(url){
				window.open(url,'_blank');
			},
			numInput(e){
				if(Number(e.target.value)%10>0){
					this.inputError=true;
					this.inputErrorText=`只能输入10的整数倍`;
					return;
				}
				let value=Number(e.target.value/10);
				if(this.totalMoney===0){
					this.inputErrorText=`暂无可兑换颜豆`;
					this.inputError=true;
					return
				}
				if(value===0){
					this.inputError=false;
					this.inputErrorText=`当前最多可兑换颜豆${this.totalMoney*10}个`;
					return;
				}
				
				if(value>this.totalMoney){
					this.inputError=true;
					this.inputErrorText='当前超出可兑换数量'
					return;
				}
				this.inputError=false;
				this.inputErrorText=`当前最多可兑换颜豆${this.totalMoney*10}个`;
			},
			allEx(){
				if(parseInt(this.totalMoney*10)===0){return;}
				this.exchangeNum=parseInt(this.totalMoney*10);
			},
			showExchangePopup(){
				if(this.exchangeNum===null||this.exchangeNum===''||this.inputError){
					return;
				}
				this.exchangePopup=true;
			},
			handleScroll(){
				
			  let scrollTop =window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
			  if(scrollTop>30){
				  this.topBarTheme='black';
			  }else{
				  this.topBarTheme='white';
			  }
			},
			getResult(){
				let locationHref=location.href;
				let str=locationHref.substr(locationHref.indexOf("?")+1);
				let arr=str.split("&");
				let bizToken="",resultId="";
				for(let i=0;i<arr.length;i++){
					let name=arr[i].substring(0,arr[i].indexOf("="));
					let value=arr[i].substr(arr[i].indexOf("=")+1);
					if(name==='biztoken'){
						bizToken=value;
					}
					if(name==='result_id'){
						resultId=value;
					}
				}
				if(bizToken!==''&&resultId!==''){
					this.$toast.loading({
						message: '加载中...',
						forbidClick: true,
						duration:0
					});
					getFaceResult(bizToken,resultId).then(result=>{
						if(result.passed===true){//识别通过
						this.$api.faceAuth.checkRealManFace({}).then(checkResult=>{//检查是否存有人脸照
							if(checkResult.data.hasFace){//有人脸
								this.$api.faceAuth.upload({//上传base64到oss
									originalFilename:result.request_id+'.jpg',
									faceImagStr:result.base64_liveness_face_image
								}).then(media=>{
									if(media.code===0){
										this.$toast.loading({
											message: '人脸比对中...',
											forbidClick: true,
											duration:0
										});
										this.$api.faceAuth.compareFace({
											imgUrl:media.data,
											scene:'IncomeExchangeCoin',
											completeUser:this.$store.state.withdrawUserInfo,
										}).then(compare=>{//进行人脸比对
											if(compare.data.succ){//人脸比对成功
												this.$toast.loading({
													message: '兑换中...',
													forbidClick: true,
													duration:0
												});
												this.$api.bag.submitIncomeOrder({//提交兑换颜豆订单
													completeUser:this.$store.state.withdrawUserInfo,
													faceToken:compare.data.succToken,
													orderId:localStorage.createIncomeOrderId,
													}).then(res=>{
													this.$toast.clear();
													if(res.data.succ){
														this.$router.replace({name:'exchangeSuccess',params:{id:localStorage.createIncomeOrderId}});
													}
													else{
														if(res.data.needDone){
															 this.$dialog.alert({
															      message: res.data.needDone,
															});
														}
														else{
															this.$dialog.alert({
															      message: res.data.msg,
															});
														}
													}
												}).catch(err=>{
													this.$toast.clear();
													this.$dialog.alert({
														  message: err.msg
													});
												})
											}else{//比对失败
												this.$toast.clear();
												this.$dialog.alert({
												      message: compare.msg
												});
											}
										}).catch(err=>{
											this.$toast.clear();
											this.$dialog.alert({
												  message: err.msg
											});
										})
									}
									else{
										this.$toast.clear();
										this.$dialog.alert({
										      message: media.msg
										});
									}
									
								}).catch(err=>{
									this.$toast.clear();
									this.$dialog.alert({
									      message: err.msg
									});
								})
							}
							else{//无人脸直接兑换
								this.$toast.loading({
									message: '兑换中...',
									forbidClick: true,
									duration:0
								});
								this.$api.bag.submitIncomeOrder({//提交兑换颜豆订单
									completeUser:this.$store.state.withdrawUserInfo,
									faceToken:'faceToken',
									orderId:localStorage.createIncomeOrderId,
									}).then(res=>{
									this.$toast.clear();
									if(res.data.succ){
										
										this.$router.replace({name:'exchangeSuccess'});
									}
									else{
										if(res.data.needDone){
											 this.$dialog.alert({
											      message: res.data.needDone,
											});
										}
										else{
											this.$dialog.alert({
											      message: res.data.msg,
											});
										}
									}
								}).catch(err=>{
									this.$toast.clear();
									this.$dialog.alert({
										  message: err.msg
									});
								})
							}
						}).catch(err=>{//人脸检查失败
							this.$toast.clear();
							this.$dialog.alert({
							      message: err.msg
							});
						})
							
							
						}else{//识别失败
							this.$toast.clear();
							this.$dialog.alert({
							      message: result,
							});
						}
					});
				}
			},
			exchange(){
				
				this.$toast.loading({
					message: '加载中...',
					forbidClick: true,
					duration:0
				});
				this.$api.bag.createIncomeOrder({coin:this.exchangeNum,completeUser:this.$store.state.withdrawUserInfo}).then(res=>{
					if(res.status==='Succ'){
						localStorage.setItem('createIncomeOrderId',res.data.orderId);//兑换颜豆订单保存本地
						localStorage.setItem('exchangeNum',this.exchangeNum);//保存兑换颜豆数量
						if(res.data.succ===true){
							getBiztoken(`${window.location.origin}/exchange`).then(result=>{
								window.location.href=result;
							}).catch(err=>{
								this.$toast.clear();
								this.$toast.fail(err.msg);
							});
						}
						else{
							this.$toast.clear();
							this.$dialog.alert({
							      message: res.data.msg,
							});
						}
					}
					else{
						this.$toast.clear();
						this.$dialog.alert({
						      message: res.msg,
						});
					}
				}).catch(err=>{
					this.$toast.clear();
					this.$toast.fail(err.msg);
				});
			}
			
		}
	}
</script>

<style lang="scss" scoped>
	@import './index.scss';
</style>