// packageA/pages/details_serviceCard/details_serviceCard.js
var t_pay = require("../../../utils/pay2.js");
const app = getApp();
const os = app.globalData.setting;
let self = null;
var util = require('../../../utils/util.js');
const ut = require("../../../utils/util.js");

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		is_summit_ing: 0,
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {

		//定义第一次进入
		this.data.fir_in=1;

		self = this;
		this.data.options = options;
		
		wx.setNavigationBarTitle({
			title: '订单详情',
		});
		
		app.isLogin().then(function(data) {
			self.setData({
				userInfo: data,
			});
			self.getConfig();
		});
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {

		this.setData({ is_summit_ing: 0 });

		var th=this;
        //判断是不是第一次进入
		if(this.data.fir_in){
			this.data.fir_in=0;
		}else{
			util.fy_back('',0)
			t_pay.set_fir();

			var back_url='/pages/user/order_list/order_list?index=2&tabindex=1';
			var err_url='/pages/user/order_list/order_list?index=2&tabindex=1';

			//判断是不是有调用支付过
			if(th.data.payed) {
				th.data.payed=0;
				//-- 判断一下活动的类型 --
				var prom_type = th.data.details.list[0].prom_type > 0 ? th.data.details.list[0].prom_type : 0;
				var order_id = th.data.details.order_id;
				var order_sn = th.data.details.order_sn;

				var ck_url = '';   //请求地址
				var req_data = {}; //请求参数
				if (parseInt(prom_type) == 6) {
                    //跳转到组图的页面
					back_url= "/packageA/pages/serviceCard_pd/team_success/team_success?ordersn=" + order_sn
					ck_url = "/api/weshop/rechargeServicelist/page";
					req_data = {store_id: os.stoid, order_id: order_id};
				} else {
					ck_url = "/api/weshop/recharge/user/page";
					req_data = {store_id: os.stoid, order_id: order_id, user_id: getApp().globalData.user_id};
				}

				//-- 通联的第三方支付的返回优化 --
				ut.is_pay_ok(th.data.details,back_url, err_url, function () {
					if (!th.data.details) return false;
					getApp().request.promiseGet(ck_url,
						{data: req_data}).then(res => {
						if (ut.ajax_ok(res)) {
							var item = res.data.data.pageData[0];
							if (parseInt(prom_type) == 6) {
								if (item.pt_status == 1 || item.pt_status == 2) {
									//支付支付，返回首页
									ut.m_toast('支付成功');
									setTimeout(() => {
										getApp().re_to(back_url);
									}, 1000)

								} else {
									//支付支付，返回首页
									ut.m_toast('支付失败');
									setTimeout(() => {
										getApp().re_to(err_url);
									}, 1000)
								}

							} else {
								if (item.pay_status == 1) {
									//支付支付，返回首页
									ut.m_toast('支付成功');
									setTimeout(() => {
										getApp().re_to(back_url);
									}, 1000)

								} else {
									//支付支付，返回首页
									ut.m_toast('支付失败');
									setTimeout(() => {
										getApp().re_to(err_url);
									}, 1000)
								}
							}


						}
					})
				});
			}

		}


        getApp().check_can_share();
		if (app.globalData.userInfo) {
			if (!this.data.isLogin) {
				this.setData({
					userInfo: app.globalData.userInfo,
					imghost: app.globalData.setting.imghost,
					isLogin: true,
				});

				let url = '/api/weshop/recharge/user/page'
				let data = {
					store_id: app.globalData.setting.stoid,
					user_id: this.data.userInfo.user_id,
					order_id: this.data.options.order_id,
				};

				// 请求数据
				app.promiseGet(url, {
					data: data,
				}).then(res => {
					if (res.data.code == 0) {
						// console.log('请求成功', res);
						var dd=res.data.data.pageData[0];
						dd.prom_type=dd.list[0].prom_type;
						dd.pt_status=dd.list[0].pt_status;
						dd.pt_tail_money=dd.list[0].pt_tail_money;

						this.setData({
							details: dd,
						});
					} else {
						throw (res);
					};
				}).catch(err => {
					wx.showToast({
						title: err.data.data,
						icon: 'error',
					});
				});

			};
		};
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {
        getApp().globalData.no_clear=1
	},


	// 内容复制到剪贴板
	copy() {
		// console.log('点击了复制按钮');
		wx.setClipboardData({
			data: this.data.details.order_sn,
			success(res) {
				wx.getClipboardData({
					success(res) {
						console.log(res.data);
					}
				})
			}
		})
	},


	// 图片异常时加载默认图片
	bind_bnerr(e) {
		var errImg = e.currentTarget.dataset.errorimg;
		var errObj = {};
		errObj[errImg] = 'public/images/default_goods_image_240.gif';
		this.setData(errObj); // this.setData({ details.list[0].img_url});    
	},


	// 查看商品详情
	async viewDetails(e) {
		let goods_id = e.currentTarget.dataset.gid;
		let url = '/packageH/pages/goodsInfo/goodsInfo?goods_id=' + goods_id;

		var rurl = '/api/weshop/activitylist/listGoodActInfo2New';
		var req_d = {
			"store_id": os.stoid,
			"goods_id": goods_id,
			"user_id": getApp().globalData.user_id,
			"goods_type": 1,
		}
		var res= await getApp().request.promiseGet(rurl, {data: req_d});


		if (res.data.code == 0 && res.data.data && res.data.data.length > 0) {
			var arr = res.data.data;
			let times = new Date().getTime();
			//-- 预热也要计算 --
			var arr2 = arr.filter(function (e) {
				return e.s_time < ut.gettimestamp() || (e.warm_uptime && e.warm_uptime < ut.gettimestamp())
			})
			if(arr2.length==1) {
				switch(arr2[0].prom_type){
					case 1:
						url+="&prom_type=1&prom_id="+arr2[0].act_id;
						break;
					case 2:
						url="/packageG/pages/group_buy/goodsInfo/goodsInfo?goods_id="+goods_id+"&prom_id="+arr2[0].act_id;
						break;
					case 6:
						url = `/packageA/pages/serviceCard_pd/goodsInfo/goodsInfo?goods_id=${goods_id}&prom_type=${arr2[0].prom_type}&prom_id=${arr2[0].act_id}`;
						break;
					case 8:
						url = `/packageC/pages/presell/cardInfo/goodsInfo?goods_id=${goods_id}&prom_id=${arr2[0].act_id}`;
						break;
				}
			}

		}


		app.goto(url);
	},

	// 获取系统参数
	getConfig() {
		app.getConfig2(function(e) {
			// console.log('101',e);
			let json_d = JSON.parse(e.switch_list);
			self.setData({
				sys_switch: json_d,
				// weapp_customertype: json_d.weapp_customertype,
			});
		}, 1);
	},


	// 联系微信客服
	contact_wx() {
        getApp().globalData.no_clear=1;
		var url = this.data.sys_switch.weapp_customertype_url;
		var id = this.data.sys_switch.weapp_customertype_appid;
		wx.openCustomerServiceChat({
			extInfo: {
				url: url
			},
			corpId: id,
			success(res) {}
		})
	},


	// 联系电话客服
	contactService() {
        getApp().con_Service();
	},


	// 评价商品
	access() {
		let listLength = this.data.details.list.length;
		let order_id = this.data.details.order_id;
		let url = '';

		// 卡项订单跳转到评论页要多加个参数card=1
		// 卡项订单goods_id要带card_id
		if (listLength == 1) {
			let price = this.data.details.list[0].price;
			let card_id = this.data.details.list[0].card_id;
			url =
				`/packageB/pages/user/add_comment/add_comment?card=1&goods_id=${card_id}&order_id=${order_id}&price=${price}`
		};
		if (listLength > 1) {
			url = `/packageB/pages/user/comment/comment?card=1&status=0&order_id=${order_id}`;
		};
		f
		// console.log('url', url);
		app.goto(url);
	},


	// 查看评论
	viewComment() {
		let order_id = this.data.details.order_id;
		let card_id = this.data.details.list[0].card_id;
		let listLength = this.data.details.list.length;
		let url = '';

		// 卡项订单单个商品
		if (listLength == 1) {
			url = `/packageB/pages/user/view_comment/view_comment?card=1&goods_id=${card_id}&order_id=${order_id}`;
		};
		// 卡项订单多个商品
		if (listLength > 1) {
			// status控制评论列表页的activeStatus
			url = `/packageB/pages/user/comment/comment?card=1&status=1&order_id=${order_id}`;
		};

		app.goto(url);
	},


	// 再来一单
	buy2: async function(t) {
		let details = this.data.details;
		var th = this;
		var ind = 1; // 1：加入购物车
		// var ind = t.currentTarget.dataset.openSpecModal_ind;
		// var action= t.currentTarget.dataset.action;
		var action = 'add'; //
		// if(!ind)  ind = t.currentTarget.dataset.openspecmodal_ind;
		var user_id = getApp().globalData.user_id;
		th.setData({
			open_ind_store: ind
		});

		// if(!th.data.sto_sele_name){
		//       getApp().my_warnning('请选择门店', 1, th, 450);
		//       return false;
		//   }


		if (action == "buy") {
			//--------------此时操作的数据------------
			// var newd = {
			//   id: th.data.data.id,
			//   goods_num: th.data.goodsInputNum,
			//   pick_id: th.data.sto_sele_id,		
			//   keyid: th.data.sto_sele_keyid,		
			// };	  
			// newd['pick_name'] = th.data.sto_sele_name;		
			// newd['guide_id'] = getApp().globalData.guide_id;
			// newd['guide_type']=0;
			// th.buyNow(newd);
		} else {

			var len = details.list.length;
			// 底导航购物车红点显示的数量
			var c_num = 0;
			// 多商品
			for (let i = 0; i < len; i++) {
					
					var newd = {
						// service_id: th.data.data.id,
						// service_sn:th.data.data.service_sn,
						// service_name:th.data.data.goods_name,
						// goods_num: th.data.goodsInputNum,
						// pick_id: th.data.sto_sele_id,
						// user_id:oo.user_id,
						// store_id:os.stoid,
						// money:th.data.data.shop_price,

						service_id: details.list[i].card_id,
						service_sn: details.list[i].service_sn,
						service_name: details.list[i].service_name,
						goods_num: details.list[i].qty,
						pick_id: details.list[i].pickup_id,
						user_id: user_id,
						store_id: app.globalData.setting.stoid,
						money: details.list[i].price,
					};
					if (getApp().globalData.guide_id) {
						newd['guide_id'] = getApp().globalData.guide_id;
						newd['guide_type'] = 0;
					};
					// 秒杀：单独购买的情况下，加入购物车显示的是零售价，否则显示秒杀活动价
					if(details.list[i].prom_type == 1) {
						newd['prom_type'] = details.list[i].prom_type;
						newd['prom_id'] = details.list[i].prom_id;
					};

					var prom_id = details.list[i].prom_id > 0 ? details.list[i].prom_id : 0;
					var card_id = details.list[i].card_id;
					var prom_type = details.list[i].prom_type > 0 ? details.list[i].prom_type : 0;
					var is_pd_normal = details.list[i].is_pd_normal;
					if(is_pd_normal){
						newd['is_pd_normal'] = 1;
					}
					// 库存
					var redisNums = 0;
					// 限购数
					var limitNum = 0;
					// 已购买数量
					var boughtNum = 0;

					// 秒杀活动中购买
					if ((prom_type == 1 && !is_pd_normal) || prom_type==2) {

							// 获取已购数量
							await getApp().request.promiseGet("/api/weshop/rechargeServicelist/getUserBuyGoodsNum?store_id="+os.stoid+"&user_id="+getApp().globalData.user_id+"&card_id="+card_id+"&prom_type="+prom_type+"&prom_id="+prom_id, {
							}).then(res => {
								boughtNum = !res.data.data.promcardbuynum ? 0 : res.data.data.promcardbuynum;
							});
							
							// 获取库存
							await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" + os.stoid + "/"+prom_type+"/" + prom_id, {}).then(res => {
								if (res.data.code == 0) {
									redisNums = !res.data.data ? 0 : res.data.data;
								}
							})

							// 获取限购数
							var is_end = 1;

							switch (prom_type){
								case 1:
									await getApp().request.promiseGet("/api/ms/flash_sale/getNew/" + os.stoid + "/" + user_id + "/" + prom_id, {}).then(res => {
										if (res.data.code == 0) {
											is_end = res.data.data.is_end;
											limitNum = res.data.data.buy_limit;
										}
									});
									break;
								case 2:
									await getApp().request.promiseGet("/api/weshop/goods/groupBuy/getActInfo/" + os.stoid + "/" + details.list[i].card_id + "/" + prom_id, {}).then(res => {
										if (res.data.code == 0) {
											is_end = res.data.data.is_end;
											limitNum = res.data.data.buy_limit;
										}
									});
									break;
							}


							// 判断活动是否结束
							if (is_end == 1) {
								wx.showModal({
									title: details.list[i].service_name + '\n\t活动已经结束',
								});
								return false;
							}


							var snum = limitNum - boughtNum;
								if (snum <= 0) {
									wx.showModal({
										title: '超出活动限购数量',
									});
									return false;
								}

					}

					if(prom_type==6){
						wx.showModal({
							title: details.list[i].service_name +"拼团商品不加入购物车\n"
						});
						return false;
					}

					if(prom_type==8){
						wx.showModal({
							title: details.list[i].service_name +"预售商品不加入购物车\n"
						});
						return false;
					}

					//----先看会员在购物车中是否加入了该商品-----
					app.request.get("/api/weshop/cartService/page", { 
						data: {
							store_id: app.globalData.setting.stoid,
							user_id: user_id,
							service_id: details.list[i].card_id,
							pick_id: details.list[i].pickup_id,
						},
						success: function(re) {
							//-------如果购物车中有相关的数据---------
							if (re.data.data.total > 0) {
								var item = re.data.data.pageData[0];
								var totalNum = details.list[i].qty + item.goods_num;

								if (prom_type == 1 && !is_pd_normal) {
									// 秒杀购物车购买 修正数量 剩余购买数量
									var snum = limitNum - boughtNum;

									if (totalNum >= redisNums){
										if (redisNums > snum) {
											totalNum = snum;
										} else {
											totalNum = redisNums;
										}
									} else {
										if (totalNum > snum)
												totalNum = snum;
										}
								}

								var updata = {
									id: item.id,
									goods_num: totalNum,
									money: details.list[i].price,
									store_id: app.globalData.setting.stoid,
								};

								if (getApp().globalData.guide_id) {
									updata['guide_id'] = getApp().globalData.guide_id;
									updata['guide_type'] = 1;
								}

								getApp().request.put("/api/weshop/cartService/update", {
									data: updata,
									success: function(t) {
										// getApp().my_warnning('加入购物车成功', 1, th, 450);
										c_num += th.data.cartGoodsNum + th.data.goodsInputNum;
										th.setData({
											cartGoodsNum: c_num
										});
										
										// th.closeSpecModal();
									}
								});


							} else {

								getApp().request.post("/api/weshop/cartService/save", {
									data: newd,
									success: function(t) {
										// getApp().my_warnning('加入购物车成功', 1, th, 450);
										c_num += th.data.cartGoodsNum + th.data.goodsInputNum;
										th.setData({
											cartGoodsNum: c_num
										});
										
										// th.closeSpecModal();
									}
								});
							}
						}
					});

		}
			app.goto('/pages/cart/cart/cart');

		}
	},


	// 取消订单
	// api/weshop/recharge/update?store_id=&order_id=&order_status=3
	cancle() {
		wx.showModal({
			title: '提示',
			content: '确定取消订单吗？',
			success(res) {
				if (res.confirm) {
					console.log('用户点击确定');
					let order_id = self.data.details.order_id;
					let order_sn = self.data.details.order_sn;
					app.request.put('/api/weshop/recharge/update', {
						data: {
							store_id: os.stoid,
							order_id: order_id,
							order_sn: order_sn,
							order_status: 3,
						},
						success: function(res) {

							//取消成功刷新订单
							let url = '/api/weshop/recharge/user/page'
							let data = {
								store_id: app.globalData.setting.stoid,
								user_id: self.data.userInfo.user_id,
								order_id: self.data.options.order_id,
							};

							// 请求数据
							app.promiseGet(url, {
								data: data,
							}).then(res => {
								if (res.data.code == 0) {
									console.log('请求成功', res);
									wx.showToast({
										title: '取消成功',
									});
									self.setData({
										details: res.data.data.pageData[0],
									});
								} else {
									throw (res);
								};
							}).catch(err => {
								wx.showToast({
									title: err.data.data,
									icon: 'error',
								});
							});

						},
					})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	},


	// 立即支付
	async pay() {

		if(this.data.is_summit_ing) return false;
		this.setData({
			is_summit_ing:1
		})

		var th=this;
		let order_sn = this.data.details.order_sn;
		let order_id = this.data.details.order_id;
		let store_id = app.globalData.setting.stoid;
		let user_id = getApp().globalData.user_id;

		let flag = true;
		// 如果是普通购买或单独购买，不用判断
		// 如果是秒杀购买：1、判断活动是否变化；2、是否超出限购
		let list =  this.data.details.list;
		var pt_act=null;  //-- 拼团活动的优化 --
		var presell=null;  //-- 预售活动 --

		//秒杀活动和拼团活动要重新计算一下
		for (const it of list) {

			var card=null;
			await getApp().request.promiseGet("/api/weshop/serviceCard/get/" + store_id + "/" + it.card_id, {}).then(res => {
				if(res.data.code==0 && res.data.data){
					card = res.data.data;
				}
			})

			if(card && card.storageId){
				let the_c_key=it.pickup_keyid;
				if (card.storageId.indexOf(the_c_key)==-1) {
					getApp().confirmBox(it.service_name + "的门店不可售");
					th.setData({ is_summit_ing: 0 });
					flag = false;
					return false;
				}
			}


			if ([1,2].includes(it.prom_type)) {
				let act_details = null;
				let redis_num = 0;
				let promcardbuynum = 0;
				let qty = it.qty;


				if(it.prom_type==1)
				   await getApp().request.promiseGet('/api/ms/flash_sale/getNew/' + store_id + '/' + user_id + '/' + it.prom_id, {}).then(res => {
					console.log('11111111====>>>');
					if (res.data.code == 0) {
						console.log('当前的秒杀活动信息：', res.data.data);
						act_details = res.data.data;
						if (act_details.is_end == 1) {
							wx.showModal({
								title: '提示',
								content: '活动已结束,无法支付,请取消订单！',
								showCancel: false,
							});
							flag = false;
							return false;
						};

						var t_now = ut.gettimestamp();
						if (act_details.is_end == 1 || act_details.start_time > t_now || act_details.end_time < t_now) {
							wx.showModal({
								title: '提示',
								content: '活动发生了变化,无法支付,请取消订单,重新购买！',
								showCancel: false,
							});
							flag = false;
							return false;
						}

						//指定门店的控制
						if (act_details.pick_up_lists) {
							var idx0=act_details.pick_up_lists.findIndex(function (e){
								return e.pickup_id==it.pickup_id;
							})
							if(idx0<0){
								getApp().confirmBox(it.service_name + "秒杀活动的门店不可售");
								th.setData({ is_summit_ing: 0 });
								flag = false;
								return false;
							}
						}

					};
				});
				if(it.prom_type==2)
					await getApp().request.promiseGet("/api/weshop/goods/groupBuy/getActInfo/" + os.stoid + "/" + it.card_id + "/" + it.prom_id, {}).then(res => {
						if (res.data.code == 0) {
							console.log('当前的t团购活动信息：', res.data.data);
							act_details = res.data.data;
							if (act_details.is_end == 1) {
								wx.showModal({
									title: '提示',
									content: '活动已结束,无法支付,请取消订单！',
									showCancel: false,
								});
								flag = false;
								return false;
							};
							var t_now = ut.gettimestamp();
							if (act_details.is_end == 1 || act_details.start_time > t_now || act_details.end_time < t_now) {
								wx.showModal({
									title: '提示',
									content: '活动发生了变化,无法支付,请取消订单,重新购买！',
									showCancel: false,
								});
								flag = false;
								return false;
							}

							//指定门店的控制
							if (act_details.pick_up_lists) {
								var idx0=act_details.pick_up_lists.findIndex(function (e){
									return e.pickup_id==it.pickup_id;
								})
								if(idx0<0){
									getApp().confirmBox(it.service_name + "秒杀活动的门店不可售");
									th.setData({ paying: 0 });
									flag = false;
									return false;
								}
							}

						};
					});

				if(act_details && act_details.buy_limit>0 && flag){
					await getApp().request.promiseGet("/api/weshop/rechargeServicelist/getUserBuyGoodsNum", {
						data: {
							store_id: store_id,
							user_id: user_id,
							card_id: it.card_id,
							prom_type: it.prom_type,
							prom_id: it.prom_id,
							ispay:1
						}
					}).then(res => {

						if (res.data.code == 0) {
							promcardbuynum = res.data.data.promcardbuynum;
							let canBuyNum = act_details.buy_limit - promcardbuynum; // 自己还可购买的数量c

							if (canBuyNum < qty) {
								wx.showModal({
									title: '提示',
									content: '您已超出活动限购数量,无法支付,请取消订单！',
									showCancel: false,
								});
								flag = false;
							}
						}
					})
				}

			};

			if (it.prom_type == 6) {
				let act_details = null;
				let redis_num = 0;
				let promcardbuynum = 0;
				let qty = it.qty;

				await getApp().request.promiseGet("/api/weshop/teamlist/get/" + store_id + "/" + it.prom_id, {}).then(res => {

					if (res.data.code == 0) {

						act_details = res.data.data;

						if (act_details.is_end == 1) {
							wx.showModal({
								title: '提示',
								content: '活动已结束,无法支付,请取消订单！',
								showCancel: false,
							});
							flag = false;
							return false;
						}

						if (act_details.id != it.prom_id) {
							wx.showModal({
								title: '提示',
								content: '活动发生了变化,无法支付,请取消订单,重新购买！',
								showCancel: false,
							});
							flag = false;
							return false;
						}

						var t_now = ut.gettimestamp();
						if (act_details.is_end == 1 || act_details.start_time > t_now || act_details.end_time < t_now) {
							wx.showModal({
								title: '提示',
								content: '活动发生了变化,无法支付,请取消订单,重新购买！',
								showCancel: false,
							});
							flag = false;
							return false;
						}

						//指定门店的控制
						if (act_details.pick_up_lists) {
							var idx0=act_details.pick_up_lists.findIndex(function (e){
								return e.pickup_id==it.pickup_id;
							})
							if(idx0<0){
								getApp().confirmBox(it.service_name + "拼团活动的门店不可售");
								th.setData({ paying: 0 });
								flag = false;
								return false;
							}
						}


					};
				});

				if(act_details.buy_limit>0 && flag){
					await getApp().request.promiseGet("/api/weshop/rechargeServicelist/getUserBuyGoodsNum", {
						data: {
							store_id: store_id,
							user_id: user_id,
							card_id: it.card_id,
							prom_type: it.prom_type,
							prom_id: it.prom_id,
							ispay:1
						}
					}).then(res => {
						if (res.data.code == 0) {
							console.log('已经购买的数量：', res.data.data);
							promcardbuynum = res.data.data.promcardbuynum;
						}
					})
					let limited = act_details.buy_limit; // 限购数量a
					let canBuyNum = limited - promcardbuynum; // 自己还可购买的数量c

					if (canBuyNum < qty ) {
						wx.showModal({
							title: '提示',
							content: '您已超出活动限购数量,无法支付,请取消订单！',
							showCancel: false,
						});
						flag = false;
					}
				}
				pt_act=act_details;
			}
			//-- 预售 --
			if (it.prom_type == 8) {

				let act_details = null;
				let promcardbuynum = 0;
				let qty = it.qty;
				let presell_id=0;

				var url = "/api/weshop/marketing/marketingPresellList/list"
				var rd = {
					store_id: os.stoid,
					presell_id: it.prom_id,
					goods_id: it.card_id
				}
				console.log('获取预售从表')
				//------获取预售从表----------
				await getApp().request.promiseGet(url, {
					data: rd
				}).then(res => {
					if (res.data.code == 0 && res.data.data && res.data.data.length > 0) {
						act_details = res.data.data[0];
						presell_id = act_details.presell_id;
					}
				})

				//------获取预售主表----------
				await getApp().request.promiseGet(`/api/weshop/marketing/marketingPresellForm/get/${os.stoid}/${presell_id}`, {}).then(res => {
					if (res.data.code == 0 && res.data.data) {
						var act_data = res.data.data;
						if (act_data.is_end) {
							wx.showToast({ title: "活动已经结束", icon: 'none', duration: 3000 });
							flag = 0;
							return false;
						}
						if (act_data.isuse == 0) {
							wx.showToast({ title: "活动未启用", icon: 'none', duration: 3000 });
							flag = 0;
							return false;
						}

						var err_txt = "活动定金时间已经结束";
						var end_time = act_data.end_time;
						if (act_data.presell_type == 1) {
							err_txt = "活动时间已经结束";
						}
						if (end_time < ut.gettimestamp()) {
							wx.showToast({ title: err_txt, icon: 'none', duration: 3000 });
							flag = 0;
							return false;
						}

						if (act_data.presell_type == 0) {
							end_time = act_data.pay_enddate;
							err_txt = "活动尾款时间已经结束";
						}
						if (end_time < ut.gettimestamp()) {
							wx.showToast({ title: err_txt, icon: 'none', duration: 3000 });
							flag = 0;
							return false;
						}
						presell=act_data;
					}
				})

				if(!flag) {
					th.setData({ is_summit_ing: 0 });
					return false;
				}

				//-- 判断一下限购的计算 --
				if(act_details.vip_butyqty>0){
					await getApp().request.promiseGet("/api/weshop/recharge/rechargePresell/countBuyGoodsSum", {
						data: {
							store_id: store_id,
							user_id: user_id,
							goods_id: it.card_id,
							prom_id: it.prom_id
						}
					}).then(res => {
						if (res.data.code == 0) {
							console.log('已经购买的数量：', res.data.data);
							promcardbuynum = res.data.data.sumgoodsnum;
						}
					})
					let limited = act_details.buy_limit; // 限购数量a
					let canBuyNum = limited - promcardbuynum; // 自己还可购买的数量c

					if (canBuyNum < qty ) {
						wx.showModal({
							title: '提示',
							content: '您已超出活动限购数量,无法支付,请取消订单！',
							showCancel: false,
						});
						flag = false;
					}
				}
			}
		}

		if (flag) {

			th.data.payed=1;
			t_pay.set_pay_url("/api/weshop/order/pay/createRechargeOrder");
			t_pay.pay({
				parentSn: order_sn,
				store_id: store_id
			}, function () {
				app.showWarning('支付成功');

				if(pt_act && pt_act.kttype==1){
					//--如果商家团的时候---
					getApp().request.promisePost("/api/weshop/order/pay/vipAutoTuan", {
						data: {orderSn:order_sn,storeId:os.stoid }
					})
				}

				setTimeout(function () {
					if(pt_act){
						wx.redirectTo({
							url: "/packageA/pages/serviceCard_pd/team_success/team_success?ordersn=" + order_sn
						});
					}else if(presell && presell.presell_type==0){

						wx.redirectTo({
							url: 	"/packageC/pages/presell/cart/cart?is_fwk=1&order_sn=" + order_sn
						});
					}
					else{
						wx.reLaunch({
							url: "/packageG/pages/payment/pay_success/pay_success?card=1&order_id=" + order_id,
						})
					}

				}, 1000)

			}, function (e) {
				th.setData({ is_summit_ing: 0 });
				wx.showToast({
					title: e,
					icon: 'none',
					duration: 2000
				});
			})
		}else{
			th.setData({ is_summit_ing: 0 });
		}

	},

	//-- 支付尾款 --
	pay2(){
	    var url="/packageA/pages/serviceCard_pd/cart_wk/cart_wk?order_id="+this.data.details.order_id;
	    getApp().goto(url);
	},
	
	//------调起支付框--------
	weixinPay: function(n, success, fail) {
		if (!n) return false;
		let order_id = this.data.details.order_id;

		getApp().globalData.no_clear=1;

		wx.requestPayment({
			timeStamp: String(n.timeStamp),
			nonceStr: n.nonceStr,
			package: n.packageValue,
			signType: n.signType,
			paySign: n.paySign,
			success: function(n) {
				console.log(n), getApp().showSuccess("支付成功！");
				"function" == typeof success && success();
				wx.redirectTo({
					url: "/packageG/pages/payment/pay_success/pay_success?card=1&order_id=" + order_id,
				});
			},
			fail: function(n) {
				console.log(n), "requestPayment:fail" == n.errMsg ? getApp().showWarning("支付失败") :
					"requestPayment:fail cancel" == n.errMsg ? getApp().showWarning("您已取消支付") : getApp().showWarning("支付失败：" + n
						.errMsg.substr("requestPayment:fail ".length)),
					"function" == typeof fail && fail();
			}
		});
	},

    click_contact:function () {
        getApp().globalData.no_clear=1;
    }




})
