// index.js
let myPro = require("../../utils/wxRequest.js");
let util = require("../../utils/util.js");
Page({
    data: {
		couponBg: "/statics/img/quan_bg_tu.png",
		checkedCard: true, // 默认选择余额付
		result: [],
		checkedWechat: false,
		showCashPop: false, // 会员卡钱不足时
		couponIdArr: [], // 优惠券选中 数组
		couponId:0,
		showCoupons: false,
		cardList: [], // 充值券
		userMoney: 0, // 用户余额
		totalPrice: 0, // 订单总金额
		fare_type: 0, // 配送方式 0外卖 1自提
		order_id: null, // 订单id(未支付订单)
		loading: false, // 全局loading
		is_member: getApp().globalData.is_member, // 会员 0否 1是
		addLock: false // 测试锁
    },
    onLoad: function (options) {
        // Do some initialize when page load.
		let that = this;
		// 配送方式
		if(options.fare_type){
			that.setData({
				fare_type: options.fare_type
			})
		};
		// 地址
		if(options.address_id){
			that.setData({
				address_id: options.address_id
			})
		};
		if(options.order_id){
			that.setData({
				order_id: options.order_id
			});
			that.getOrderDetail();
		};
		that.setData({
			couponBg: "data:image/png;base64," + wx.getFileSystemManager().readFileSync(that.data.couponBg, "base64")
		});
    },
    onShow: function () {
        // Do something when page show.
		let that = this;
		// 店铺
		if(wx.getStorageSync('store')){
			that.setData({
				store: JSON.parse(wx.getStorageSync('store'))
			});
		};
		// 获取用户余额
		that.getUserCash();
		// 获取充值卡
		that.getRechargeCard();
		// 获取券(只支持初次订单,不支持二次支付订单)
		if(!that.data.order_id && !that.data.addLock){
			that.getCreatelist();
		};
		// console.log('show=====');
    },
    onReady: function () {
        // Do something when page ready.
    },
    onHide: function () {
        // Do something when page hide.
    },
    onUnload: function () {
        // Do something when page close.
    },
    onPullDownRefresh: function () {
        // Do something when pull down.
		
    },
    onReachBottom: function () {
        // Do something when page reach bottom.
    },
    onPageScroll: function () {
        // Do something when page scroll
		
    },
    onResize: function () {
        // Do something when page resize
    },
	// 获取可用优惠券(同时总了总价等)
	getCreatelist(){
		let that = this;
		let params = {
			fare_type: that.data.fare_type
		};
		if(that.data.fare_type == 0){
			params.address_id = that.data.address_id
		};
		if(wx.getStorageSync('user_mark')){
			that.setData({
				user_mark: wx.getStorageSync('user_mark')
			});
			params.user_mark = that.data.user_mark;
		};
		if(that.data.couponId){
			params.user_coupon_id = that.data.couponId;
		};
		// return;
		myPro.wxRequest("user/v3/order/createlist","GET",params).then(res=>{
			let couponList = res.result.userCouponList;
			that.setData({
				totalPrice: res.result.orderInfo.pay_price,
				couponList: couponList,
				couponNums: couponList.length // 几张券
			});
		}).catch(err=>{
			console.log('报错信息',err);
			wx.showToast({
				title: err,
				icon: "none"
			})
		})
	},
	// 获取用户的余额
	getUserCash(){
		let that = this;
		myPro.wxRequest("user/v2/userinfo","GET",{}).then(res=>{
			that.setData({
				userMoney: parseFloat(res.result.money)
			});
		}).catch(err=>{
			console.log('报错信息',err);
			wx.showToast({
				title: err,
				icon: 'none'
			});
		});
	},
	// 选卡付
	changeCard(){
		let that = this;
		that.setData({
			checkedCard: !that.data.checkedCard
		});
		// 余额和微信方式只能选一种
		if(that.data.checkedCard){
			that.setData({
				checkedWechat: false
			})
		};
	},
	// 选微信付
	changeWechat(){
		let that = this;
		that.setData({
			checkedWechat: !that.data.checkedWechat
		});
		// 余额和微信方式只能选一种
		if(that.data.checkedWechat){
			that.setData({
				checkedCard: false
			})
		};
	},
	// 创建订单前的相关判断
	confirmCreateOrder(){
		let that = this;
		// wx.redirectTo({
		// 	url: '/pages/pay-success/index?order_id=176',
		// 	complete: function(){
		// 		// 清掉备注
		// 		// wx.removeStorageSync("user_mark");
		// 	}
		// });
		// return;
		// that.setData({
		// 	loading: true
		// });
		// 是否勾选支付方式
		if(!that.data.checkedCard && !that.data.checkedWechat ){
			wx.showToast({
				title: "请选择支付方式",
				icon: "none"
			});
			// that.setData({
			// 	loading: false
			// });
			return;
		};
		// 判断支付方式
		let pay_type = that.data.checkedWechat ? 1 : 2; //1微信 2充值卡
		that.setData({
			pay_type: pay_type
		});
		// 余额不足以支付时
		if( that.data.pay_type == 2 && that.data.userMoney < that.data.totalPrice){
			that.setData({
				showCashPop: true
			});
			// that.setData({
			// 	loading: false
			// });
			return;
		};
		// 余额付
		if(that.data.pay_type == 2){
			if(that.data.order_id){
				that.orderPay(2);
			}else{
				that.createOrder(2);
			}
		};
		// 微信付
		if(that.data.pay_type == 1){
			if(that.data.order_id){
				that.orderPay(1);
			}else{
				that.createOrder(1);
			}
		};
	},
	// 创建订单
	createOrder(pay_type){
		// pay_type 有三种类型 1微信 2余额 3混合
		let that = this;
		let data = {
			pay_type: pay_type,
			fare_type: that.data.fare_type
		};
		// 收货地址
		if(that.data.fare_type == 0 && that.data.address_id){
			data.address_id = that.data.address_id
		};
		// 券
		if(that.data.couponId){
			data.user_coupon_id = that.data.couponId
		};
		// 备注
		if(that.data.user_mark){
			data.user_mark = that.data.user_mark
		};
		// 创建订单
		myPro.wxRequest("user/v3/order/create","POST",data).then(res=>{
			let order = res.result.order;
			if(res.result.config){
				that.goWxPay(order,res.result.config)
			}else{
				// 不需要调微信支付,直接创建成功
				that.onCreateOrderAfter(order,1)
			}
		}).catch(err=>{
			console.log('报错信息',err);
			wx.showToast({
				title: err,
				icon: "none"
			});
		})
	},
	// 余额不足,加微信支付
	onAddWechat(){
		let that = this;
		// 混合付
		if(that.data.order_id){
			that.orderPay(3);
		}else{
			that.createOrder(3);
		};
		that.setData({
			showCashPop: false
		});
	},
	// 余额不足,充值
	onRecharge(){
		let that = this;
		that.setData({
			showCashPop: false
		});
	},
	// 调起微信
	goWxPay(order,config) {
        let that = this;
        const configArr = JSON.parse(config);
        wx.requestPayment({
            timeStamp: configArr.timeStamp,
            nonceStr: configArr.nonceStr,
            package: configArr.package,
            signType: configArr.signType,
            paySign: configArr.paySign,
            success(res) {
                // console.log(res);
                // 执行支付成功后续操作
                that.onCreateOrderAfter(order,1);
            },
            fail(res) {
                // console.error(res);
                if ( res.errMsg == 'requestPayment:fail cancel' ) {
					that.setData({
						addLock: true // 为了避免付款后,又进了onshow,影响了调优惠券的接口
					});
					wx.showToast({
						title: "您取消了支付，请到我的订单中继续付款",
						icon: "none"
					});
                } else {
					wx.showToast({
						title: "支付失败，请到我的订单中继续付款",
						icon: "none"
					});
                }
				// 订单创建成功,但取消了支付 -1
				that.onCreateOrderAfter(order,-1);
            }
        });
    },
	// 支付后的处理
	onCreateOrderAfter(order,type){
		let that = this;
		// 清掉下单时的备注
		wx.removeStorageSync("user_mark");
		// type 1成功 -1失败
		if(type == 1){
			that.setData({
				addLock: true // 为了避免付款后,又进了onshow,影响了调优惠券的接口
			});
			wx.redirectTo({
				url: '/pages/pay-success/index?order_id='+ order.id
			});
		}else{
			// 支付失败后 跳转到订单详情(此时订单已创建成功)
			setTimeout(function(){
				wx.redirectTo({
					url: '/pages/user/order/detail/index?order_id='+order.id
				});
			},1000)
		}
	},
	// 打开优惠券弹层
	onShowCoupons(){
		let that = this;
		that.setData({
			showCoupons: true
		});
	},
	// 获取当前点击的优惠券
	onClickCoupons(event){
		let that = this;
		let item = event.currentTarget.dataset.item;
		if(that.data.couponId == item.id){
			that.setData({
				couponIdArr: [],
				couponId:0,
				checkedCoupon: null
			});
			// 更新金额
			that.getCreatelist();
		}
		else{
			that.setData({
				couponIdArr: [''+item.id],
				couponId:item.id
			});
			if(that.data.couponId == item.id){
				that.setData({
					checkedCoupon: item,
					showCoupons: false,
				});
				// 更新金额
				that.getCreatelist();
			}else{
				that.setData({
					checkedCoupon: null,
					showCoupons: false
				});
			}
		}
		// console.log('选中的优惠券',that.data.checkedCoupon)
	},
	// 关闭优惠券弹层
	onCloseCoupons(){
		let that = this;
		that.setData({
			showCoupons: false
		});
	},
	// 获取订单详情
	getOrderDetail(){
		let that = this;
		let params = {
			order_id: that.data.order_id	
		};
		myPro.wxRequest("user/v2/order/detail","GET",params).then(res=>{
			that.setData({
				totalPrice: res.result.pay_price
			});
		}).catch(err=>{
			console.log('报错信息',err);
			wx.showToast({
				title: err,
				icon: "none"
			});
		})
	},
	// 未支付订单,进行支付
	orderPay(pay_type){
		let that = this;
		let params = {
			order_id: that.data.order_id,
			pay_type: pay_type
		};
		myPro.wxRequest("user/v2/order/topay","POST",params).then(res=>{
			let order = res.result.order;
			// res.result.type  1余额支付成功 2走微信
			if(res.result.config){
				that.goWxPay(order,res.result.config);
			}else{
				that.onCreateOrderAfter(order,1);
			}
		}).catch(err=>{
			console.log('报错信息',err);
			wx.showToast({
				title: err,
				icon: "none"
			})
		});
	},
	// 获取充值卡
	getRechargeCard(){
		let that = this;
		let params = {
			type: 1, // 1返回3条数据  2返回全部数据
			card_type: 1 // 1普通 2年卡(会员卡)
		};
		myPro.wxRequest("user/v2/rechargecardlist","GET",params).then(res=>{
			let list = res.result;
			for(let i in list){
				list[i].checked = false;
				// 卡+券的总金额 (都按代金券走,折扣券不考虑)
				if(list[i].coupon_rule){
					list[i].priceAddCoupons = ((list[i].coupon_rule.coupon.price * list[i].coupon_rule.num) + parseFloat(list[i].price)).toFixed(2)
				}else{
					list[i].priceAddCoupons = list[i].price
				}
			};
			that.setData({
				cardList: list
			});
		}).catch(err=>{
			console.log('报错信息',err);
			wx.showToast({
				title: err,
				icon: "none"
			})
		})
	},
	// 选择充值卡
	clickCard(event){
		let that = this;
		let id = event.currentTarget.dataset.id;
		let list = that.data.cardList;
		// 测试(模拟流程,能跑了再删)
		// that.setData({
		// 	is_member: 1
		// })
		// that.getUserCash();
		// return;
		for(let i in list){
			if(list[i].id == id){
				list[i].checked = !list[i].checked;
				// 选中状态,则去购卡
				if(list[i].checked){
					that.nextFun(list[i].id);
				}
			}else{
				list[i].checked = false
			}
		};
		that.setData({
			cardList: list
		});
	},
	// 充值
	nextFun(id){
		let that = this;
		let params = {
			recharge_card_id: id,
			store_id: that.data.store ? that.data.store.id : 1 // 门店id
		}
		myPro.wxRequest("user/recharge","POST",params).then(res=>{
			let config = res.result.config;
			that.wxPayCard(JSON.parse(config));
		}).catch(err=>{
			that.setData({
				loading: false
			});
			console.log('报错信息',err);
			wx.showToast({
				title: err,
				icon: "none"
			})
		})
	},
	// 卡充值微信付款
	wxPayCard: function(result) {
		let that = this;
		wx.requestPayment({
			timeStamp: result.timeStamp,
			nonceStr: result.nonceStr,
			package: result.package,
			signType: result.signType,
			paySign: result.paySign,
			success(res) {
				wx.showToast({
					title: "充值成功",
					icon: "none"
				});
				// 拉取用户余额
				that.getUserCash();
				// 获取券(非商品待支付订单)
				if(!that.data.order_id){
					that.getCreatelist();
				};
			},
			fail(res) {
				wx.showToast({
					title: "充值失败",
					icon: "none"
				});
				console.log("报错信息",res)
			}
		});
	},

});
