<template>
	<view class="pages confirmOrder">
		<view class="order-list">
			<custom-nodata v-if="cartList.length === 0"></custom-nodata>
			<view class="order-list-item" v-for="(item,index) in cartList" :key="index">
				<view class="image-content">
					<image :src="$onlineImg + item.goodsImages | firstImg" mode="aspectFill"></image>
				</view>
				<view class="text-content">
					<view class="title">{{item.goodsName}} </view>
					<!-- <view class="oId">产品编号: {{ item.oId }}</view> -->
					<view class="price">
						<view class="price-total"><text>￥</text>{{item.totalPrice | keepTwoNum}}</view>
						<view class="price-unit">{{item.price}}元 / KG</view>						
					</view>
					<view class="totalcarbon">累计碳汇量{{item.carbonVal}}kg</view>
					<!-- <view class="total"><text>￥</text>{{item.totalPrice | keepTwoNum}}</view> -->
					<view class="nums">
						 <view class="countNum">
							 <view class="countNum-action reduce" @click="calcValue('reduce',item)">-</view>
							 <view class="countNum-input">
								 <input class="uni-input" v-model="item.carbonVal" type="number" @blur="onInput(item)"/>
							 </view>
							 <view class="countNum-action add" @click="calcValue('add',item)">+</view>
						 </view>
					</view>
					<!-- {{cartListTmp}} -->
				</view>
			</view>
		</view>
		<!-- <uni-list class="pay-way">
		    <uni-list-item title="支付方式" rightText="微信支付"></uni-list-item>
		</uni-list> -->
		<view class="pay-wrap" @click="submitOrder">
			<view class="pay-con">
				<text class="pay-con-til">立即支付</text>
				<view class="num">
					<text>￥</text>
					{{totalPrice | keepTwoNum}}
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { mapMutations } from 'vuex';
	// import uniList from "@/components/uni-list/uni-list.vue"
	// import uniListItem from "@/components/uni-list-item/uni-list-item.vue"
	import customNodata from '@/components/custom-nodata/custom-nodata.vue'
	import { debounce } from '@/utils/util.js'
	export default{
		components:{
			// uniList,
			// uniListItem,
			customNodata
		},
		onLoad(options) {
			let self = this;
			let arr = this.$store.state.cartListTmp
			// console.log('options',JSON.parse(JSON.stringify(options)));
			console.log('this.$store.state.cartListTmp',JSON.parse(JSON.stringify(this.$store.state.cartListTmp)));
			for(let i = 0; i < arr.length; i++){
				this.cartList.push({
					goodsName:arr[i].goodsName,
					goodsImages:arr[i].goodsImages,
					goodsId:arr[i].guid,
					price:arr[i].price,
					carbonVal:arr[i].carbonSkin,
					// total:arr[i].carbonSkin,
					totalPrice:arr[i].carbonSkin * arr[i].price,
					// totalcarbon:arr[i].carbonSkin
				})
			};
			uni.getStorage({
				key:'accessToken',
				success: function (res) {
					self.token = res.data.accessToken;
				   // console.log('token',res.data.accessToken);
				}
			});
		},
		onUnload() {
			//页面卸载购物清单
			this.clearCart()
		},
		data(){
			return{
				token:'',
				requested:true,//是否请求中
				min:1,
				cartList:[],
				orderid:'',
			}
		},
		methods:{
			...mapMutations(['clearCart']),
			onInput(item){
				console.log(item.carbonVal)
				if(!(/(^[1-9]\d*$)/.test(item.carbonVal))){
					item.carbonVal = 1
					if(item.carbonVal < this.min){
						item.carbonVal = 1
					}
				}
				item.totalPrice = item.price * item.carbonVal
			},
			//数量计算
			calcValue(type,item){
				if (type === "reduce") {
					item.total-- 
					if (item.carbonVal < this.min) {
						item.carbonVal = 1
					}
					item.totalPrice = item.price * item.carbonVal;
					// item.totalcarbon = item.carbonVal*10;
				} else if (type === "add") {
					// console.log('this.$store.state.cartListTmp',JSON.parse(JSON.stringify(this.$store.state.cartListTmp)));
					// console.log('this.$store.state.cartListTmp.canSold',this.$store.state.cartListTmp[0].canSold);
					item.carbonVal++
					item.totalPrice = item.price * item.carbonVal
					console.log('this.cartList',this.cartList);
					// item.totalcarbon = item.carbonVal*10;
				}
			},
			//提交校验
			submitOrder(){
				if(this.requested){
					this.requested = false;
					uni.showLoading({
						title: '订单生成中。'
					});
					if(this.cartList.length == 0){
						this.$api.msg("请先选择产品!")
						return;
					}else{ 
						let userInfo = uni.getStorageSync("userInfo");
						// console.log( uni.getStorageSync("linkType") );
						let params = {
							// customerId:userInfo.guid,
							goods:this.cartList,
							// linkType: uni.getStorageSync("linkType") || '',
							// activityId:uni.getStorageSync("togetherId") || ''
						}
						this.syncData(params);
					}					
				}else{
					this.$api.msg('请求中,请稍等!', 2500);
					return
				};
				
			},
			//订单提交，拿到订单id
			syncData(data){
				console.log('data',data);
				// return
				this.$api.http.post(this.config.apiBaseurl + "/carbon-h5/wap/order/createOrder",data,{
					header: {
					Accept:'application/json',
					Authorization: 'Bearer '+ this.token, //注意Bearer后面有一空格
				},
				}).then(res=>{
					console.log('res',res);
					this.requested = true;
					if(res.data.retHead.errCode == 0){
						this.pullWeichatPay(res.data.retBody)
					}else{							
						this.$api.msg(res.data.retHead.errMsg)	
					}
					uni.hideLoading()
				}).catch( err =>{
					this.requested = true;
					console.log('createOrder err',err)
				})
				
			},
			//拉起微信支付
			pullWeichatPay(item){
				this.orderid = item.guid;
				let self = this;
				console.log('pay item',item);
				let userInfo = uni.getStorageSync("userInfo");
				console.log('userInfo',userInfo);
				// return
				let params = {
					orderId:item.guid,
					// payType:item.payType,
					openid:userInfo.wxId,
					"tradeType":"test"
				};
				this.$api.http.post(this.config.apiBaseurl + "/carbon-h5/wechat/pay",params,{
					header: {
					Accept:'application/json',
					Authorization: 'Bearer '+ this.token, //注意Bearer后面有一空格
				},
				}).then(res=>{
					uni.requestPayment({
					    provider: 'wxpay',
					    timeStamp:res.data.retBody.timeStamp,
					    nonceStr: res.data.retBody.nonceStr,
					    package: res.data.retBody.packageValue,
					    signType: 'MD5',
					    paySign: res.data.retBody.paySign,
					    success: function (res) {
							// self.$api.href('/pages/usercenter/orderList/orderList')
							// self.$api.href('/pages/usercenter/certificateList/certificate/certificate?orderid=' + self.orderid);
							self.$api.href('/pages/buySuccess/buySuccess?orderid=' + self.orderid)
					        console.log('success:' + JSON.stringify(res));
					    },
					    fail: function (err) {
					        console.log('fail:' + JSON.stringify(err));
					    }
					});
				}).catch( err =>{
					console.log('pay err',err)
				})
			}
		},
		computed:{
			//订单总价计算
			totalPrice:function(){
				let totalPrice = 0 
				let len = this.cartList.length
				for(let i = 0; i < len;i++){
					totalPrice += this.cartList[i].totalPrice
				}
				return totalPrice
			}
		}
	}
</script>

<style>
	@import url("confirmOrder.css");
</style>
