<template>
	<view class="details_contanier">
		<view class="details_head" v-if='detailsMessage && detailsMessage.user && detailsMessage.user.meta' >
			<view class="head_photo">
				<image :src="detailsMessage.user.meta.avatar" />
			</view>
			<view class="head_message">
				<view class="name">
					{{detailsMessage.user.meta.nick_name}}
				</view>
				<view class="notice">
					在果酱小店发现好物，一起来砍价拿
				</view>
			</view>
			<view class="rule" @tap="showRule">
				活动规则
			</view>
		</view>
		<view class="details_body" v-if='detailsMessage'>
			<view class="goods_message" v-if='detailsMessage.reduce'>
				<view class="goods_left" v-if='detailsMessage.reduce.goods'>
					<image :src="detailsMessage.reduce.goods.img" mode="widthFix" />
				</view>
				<view class="goods_right" v-if='detailsMessage.reduce.goods'>
					<view class="goods_name">
						{{detailsMessage.reduce.goods.name}}
					</view>
					<view class="past_price" v-if='detailsMessage.reduce.goods'>
						原价￥{{detailsMessage.reduce.goods.max_price}}
					</view>
					<view class="new_price">
						砍后价￥{{detailsMessage.reduce.price}}
					</view>
				</view>
			</view>
			<view class="text_message" v-if="overTime == false && overActivity == false" :style="{marginLeft:left+'%'}">
				已砍{{detailsMessage.reduce_amount}}元
			</view>
			<view class="text-copy" v-if="overTime==true || overActivity==true" :style="{marginLeft:left+'%'}">
				已砍{{detailsMessage.reduce_amount}}元
			</view>
			<view class="bar">
				<progress :percent="detailsMessage.progress_par*100" :color="'#' + setColor" border-radius="3px" />
			</view>
			<view class="tips" v-if="overTime == false && overActivity == false">
				已砍{{detailsMessage.reduce_amount}}元,还可砍{{detailsMessage.reduce_surplus_amount}}元
			</view>
			<view class="tips" v-if="overTime == true && overActivity == false">
				很遗憾超时了，本次砍价失败
			</view>
			<view class="tips" v-if="overActivity == true">
				很遗憾活动已结束
			</view>
			<view class="tips" v-if="is_leader == 0 && overActivity == false &&overTime == false">
				帮我砍价，你拿红包，新人有礼
			</view>
			<!-- 后台没设置可提前购买-->
			<button class="btn" open-type='share' v-if="is_leader == 1 && buy == false && overTime == false && overActivity == false">
				<text>{{message}}</text>
			</button>
			<view class="btn" @tap="goStore" v-if="is_leader==1 &&overActivity==true">去商城看看</view>
			<view class="btn" @tap="goStore" v-if="is_leader==0 && overTime==true ">去商城看看</view>
			<!-- 后台设置了可提前购买-->
			<view class="can_buy" v-if="is_leader==1 && buy && overTime==false && overActivity==false">
				<!-- #ifdef MP-WEIXIN || APP-PLUS-->
				<view class="invite" v-if="over==false" @tap="helpShare">
					<text>{{message}}</text>
				</view>
				<!-- #endif -->
				<!-- #ifdef H5 -->
				<view class="invite" v-if="over==false" @tap="togglePopup('middle-img')">
					<text>{{message}}</text>
				</view>
				<!-- #endif -->
				<view class="now_buy" @tap="showSelect" v-if="over==false">马上购买</view>
				<!-- 活动未结束但是用户砍价已完成-->
				<view class="btn" @tap="showSelect" v-if="over==true && pay==false">{{detailsMessage.reduce_surplus_amount}}元购买商品</view>
				<view class="btn" @tap="goStore" v-if="over==true && pay==true">订单已支付，去商城看看</view>
			</view>
			<!-- 用户时间结束-->
			<view class="btn2" v-if="is_leader==1 && overTime==true && overActivity==false">
				<view class="child_btn1" @tap="bargainAgin">
					重新发起砍价
				</view>
				<view class="child_btn2" @tap.stop="goStore">
					去商城看看
				</view>
			</view>
			<view class="btn" @tap="bargain" v-if="is_leader==0 && step==1 && overTime==false && overActivity==false">
				<text>{{message}}</text>
			</view>

			<view class="btn2" v-if="is_leader==0 && step==2 && overActivity==false">
				<view class="child_btn1" @tap="joinBargain">
					{{message}}
				</view>
				<!-- #ifdef MP-WEIXIN || APP-PLUS -->
				<view class="child_btn2" @tap="helpShare" v-if="over==false">
					帮好友分享
				</view>
				<!-- #endif -->
				
				<!-- #ifdef H5 -->
				<view class="child_btn2" @tap="togglePopup('middle-img')" v-if="over==false">
					帮好友分享
				</view>
				<!-- #endif -->
				<view class="child_btn2" @tap="goStore" v-else>
					去商城看看
				</view>
			</view>
			<view class="count_down" v-if="overTime==false && overActivity==false">
				<!-- <seckill :end="detailsMessage.ends_at" :starts="detailsMessage.starts_at" :server="server" typename="砍价"></seckill> -->
				<countdown :value="detailsMessage.ends_at" detail-class="text-color"></countdown>
			</view>
			<view class="person_number" v-if="overActivity==false">
				<view class="left"></view>
				<view class="right"></view>
				<view class="title" v-if="overActivity==false">
					砍价英雄榜
				</view>
				<view class="person_tips" v-if="detailsMessage.users && detailsMessage.users.length==0 && overActivity==false">
					快去邀请英雄助力吧
				</view>
				<view class="person_list" v-if="detailsMessage.users && detailsMessage.users.length!==0 && overActivity==false">
					<view class="hero_box" v-for="(item,index) in detailsMessage.users" :key='index'>
						<view class="hero_message">
							<view class="head_img">
								<image :src="item.meta.avatar" />
							</view>
							<view class="message_box">
								<view class="message_name">
									{{item.meta.nick_name}}
								</view>
								<view class="message_share">
									分享给好友，免费拿好货
								</view>
							</view>
						</view>
						<view class="reduce_money">
							已成功砍掉{{item.reduce_amount}}元
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 活动规则弹层-->
		<view class="box_body" v-if="show" @tap.stop="closeRule" @touchmove.stop="true">
			<scroll-view scroll-y class="rule_box" @tap.stop="showRule">
				<u-parse :content="rule" />
			</scroll-view>
			<view class="iconfont icon-close" @tap="closeRule"></view>
		</view>
		<!-- 砍价成功弹层-->
		<view class="box_body" @touchmove.stop="true" v-if="showNotice && is_leader==0" @tap="closeNotice">
			<view class="notice_box" @tap.stop="showNoticeInfo">
				<view class="iconfont icon-xiaolian1"></view>
				<view class="thanks">
					<text>谢英雄拔刀相助,为我</text>
					<text>砍掉{{reduce_amount}}元</text>
				</view>
				<view class="true_btn" @tap.stop="closeNotice">
					确定
				</view>
				<view class="gostore" @tap.stop="goStore">
					去商城看看
				</view>
			</view>
			<view class="iconfont icon-close" @tap="closeNotice"></view>
		</view>
		<!-- 分享弹层-->
		<view class="box_body" @touchmove.stop="true" v-if="showShare">
			<view class="share_box">
				<view class="share_way">
					<!-- #ifdef MP-WEIXIN -->
					<button class="friends" open-type="share">
						<view class="iconfont icon--weixin">
					
						</view>
						<view class="text">
							微信好友
						</view>
					</button>
					<!-- #endif -->
					<!-- #ifdef APP-PLUS -->
					<button class="friends" @click="shareapp">
						<view class="iconfont icon--weixin">
					
						</view>
						<view class="text">
							微信好友
						</view>
					</button>
					<!-- #endif -->
					<view class="post" @tap="createShareImg">
						<view class="iconfont icon-tupian">

						</view>
						<view class="text">
							海报分享
						</view>
					</view>
				</view>
				<view class="exit" @tap="closeShare">取消</view>
			</view>
		</view>
		<view class="maks" :class="!show_select ? 'cur' : ''" @tap="closeSelect">

		</view>
		<view class="detail-popup" v-show="!show_select">
			<view class="select_goods_container">
				<!--关闭按钮-->
				<view class="select_goods_cloese" @tap="closeSelect"></view>
				<view class="select_goods_header">

					<view class="img_box">
						 <image v-if="select_product && select_product.img" :src="select_product.img" :alt="select_product.sku"></image>
						<image v-else :src="detailsMessage.reduce.goods.img" alt></image>
					</view>
					
					<view class="price_item">
						<span v-if="select_product">
						     <text>￥{{time_price}}</text>
						</span>
						 <span style="font-weight:bold;color:#ee2b1d;" v-else>
						     {{price_interval}}
						 </span>
						<!--<text  v-else>￥{{price}}</text>-->
						<!--<text  v-else>{{detailData.meta.groupon.groupon_price}}</text>-->
						<!-- <text v-if="detailData.data.shop_show_store == 1">库存{{store_count}}</text> -->
					</view>

				</view>

				<view class="select_spec">
					<view class="spec_line" v-for="(spec,index) in specs" :key="index">
						<view class="spec_title">{{spec.label}}</view>
						<view class="spec_value">
							<view class="spec_block" :class=" !!item.disabled ? 'disabled' : '' "  v-for="(item,index) in spec.values"
							 :key="index" :data-key="index" :data-index="item.index" :data-disabled="item.disabled ? 1 : 0" :data-id="item.id"
							 :data-active="item.active ? 1 : 0" @tap="selectSpec">
							 
								<view class="spec_text" v-if="(item.alias || item.value) && item.spec_img !== ''">
									{{item.alias || item.value}}

									<view v-if="!!item.active"  class="border-color">

									</view>
								</view>
								<view class="spec_text" v-if="!item.spec_img && !item.color">
									{{item.alias || item.value}}

									<view v-if="!!item.active"  class="border-color">

									</view>
								</view>
							</view>
							<!--<view class="spec_list" v-if="{{spec.id != 2}}">尺码表</view>-->
						</view>
					</view>

					<view class="spec_line">
						<view class="num_title">数量</view>
						<view class="num_value">
							<text :data-index="0">-</text>
							<view class="none_border">
								<input @input="modifyCount" :value="select_count" type="number" confirm-type="done" />
							</view>
							<text :data-index="1">+</text>

						</view>
						<!-- <view class="purchase" v-if="detailData.data.user_limit">
							本商品每人限购{{detailData.data.user_limit}}件
						</view> -->
					</view>

					<button class="button" v-if="!canBuy"  type="primary" @tap="confirmF">确定</button>
					<button class="button"  v-else type="primary" @tap="confirmF">确定</button>

					<!--<view  class="button {{ canBuy ? 'disabled' : '' }}" bindtap="confirm">-->

					<!--&lt;!&ndash;<submit-button v-ref:button bindsubmit="confirm" :status="disallow_cart ? 'disabled' : 'normal'">确定</submit-button>&ndash;&gt;-->
					<!--</view>-->
				</view>
			</view>

		</view>
		<view class="share-img-box" :class="share_img ? 'cur' : ''" v-if="showShareImg">
			<view class="imgs-box">
				<view class="img">
					<image :src="shareImg"></image>
				</view>
				<view class="text">
					保存图片后，可分享到朋友圈
				</view>
				<view class="save"  @tap="downImg">
					保存图片
				</view>
				<i class="iconfont icon-delete" @tap="changeImg"></i>
			</view>
		</view>
		<!--用户拒绝下载图片授权弹出-->
		<alert :is_refused="is_refused" @close="closeAlert"></alert>
		<!-- h5分享 -->
		<!-- #ifdef H5 -->
			<view class='shoppop'>
				<uni-popup :show="type === 'middle-img'" position="top" mode="fixed" @hidePopup="togglePopup('')">
								<view class="uni-center center-box">
									<image style="position: absolute; top: 0;right:0"  @tap="togglePopup('')" class="image" src="/static/ico-share-wechat.png" />
								</view>
				</uni-popup>
			</view>
		<!-- #endif -->
	</view>

</template>

<script>
	// 引入安卓权限
	import permision from "@/common/js/permission.js"
	import alert from "@/components/alert/alert";
	import countdown from "@/components/Countdown/Countdown.vue";
	import uParse from '@/components/gaoyia-parse/parse.vue';
	export default {
		data() {
			return{
				userInfo: {},
				left: 0,
				select_count: 1,
				show: false, //控制活动规则的显示
				rule: '', //活动规则
				number: 17,
				skuTable: {},
				is_leader: 0, //1为自己，0为好友
				message: '',
				showShare: false, //显示分享
				showNotice: false, //控制砍价后弹框显示
				theReduce: 10, //
				step: 1, //控制好友按钮显示,1为还未助力；2为助力成功；3为助力失败
				showTell: false, //控制活动结束，好友新开零元拿显示的弹层
				buy: true, //系统是否设置了可提前购买
				over: false, //砍价是否完成
				overTime: false, //用户时间是否超时
				overActivity: false, //活动是否结束
				ends_at: '', //结束时间
				starts_at: '', //开始时间
				setColor: 'fb5054', //进度条的颜色
				page: 1, //页
				show_select: true, //选尺寸
				heroList: [], //砍价英雄榜的数据
				showShareImg: false, //展示分享图片
				pay: false, //是否已经支付
				canBuy: true,
				detailsMessage:'',
				reduce_id:'',
				id:'',
				goods_id:'',
				name:'',
				store_count:'',
				market_price:'',
				time_price:'',
				select_product:{},
				price_interval:'',
				specs:[],
				price:'',
				show_ten:'',
				reduce_amount:'',
				share_img:'',
				shareImg:'',
				is_refused:false,
				reduce_items_id:'',
				type: 0
			}
		},
		components: {
			countdown,
			uParse,
			alert
		},
		onLoad(e) {
			// #ifdef H5
			var token = this.$cookieStorage.get('user_token');
			if(!token){
				var env = {
							 isIPad: /ipad/i.test(window.navigator.userAgent),
							 isIphone: /iphone|ipad|ipod/i.test(window.navigator.userAgent),
							 isWechat: /MicroMessenger/i.test(window.navigator.userAgent)
				}
				if(env.isWechat){
					if(e.openid){
						this.$cookieStorage.set('openid',e.openid)
					}
					var openid =  this.$cookieStorage.get('openid') || e.openid;
					if(openid){
						this.postNewQuickLogin(openid);
					} else{
						let origin = window.location.origin;
						let url = origin+'/pages/bargain/detail/detail?reduce_items_id='+e.reduce_items_id;
						window.location.href = this.$config.GLOBAL.baseUrl+'oauth/wxOauth?redirect_url='+encodeURIComponent(url);
					}
				} else{
					let url = getUrl()+'?reduce_items_id='+e.reduce_items_id;
					wx.navigateTo({
						url:'/pages/user/loginType/loginType?url='+url
					})
				}
			}
			// #endif
			var reduce_items_id = decodeURIComponent(e.scene)
			if (reduce_items_id > 0) {

				this.setData({
					reduce_items_id: reduce_items_id
				})
				this.getMessage()
			}
			this.getServer()
			if (e.reduce_items_id) {
				this.reduce_items_id = e.reduce_items_id;
				this.getMessage()

			}
			if (this.overTime == true || this.overActivity == true) {
				this.setData({
					setColor: 'AAAAAA'
				})
			}
			var windowHeight = wx.getSystemInfoSync().windowHeight //获取设备的高度
			this.Height =  windowHeight;
			this.showWitch();

		},
		onShow() {
			this.getRule()
		},
		onShareAppMessage(res) {
			if (res.from === 'button') {
				// 来自页面内转发按钮
				this.closeShare();
			}
			return {
				title: '砍价帮帮忙',
				path: `/pages/bargain/detail/detail?reduce_items_id=${this.reduce_items_id}`
			}
		},
		onPullDownRefresh() {
			this.getMessage()

		},
		methods: {
			postNewQuickLogin(open_id){
				wx.showLoading({
					title: '正在登录',
					mask: true
				});
				this.$http.post({
					api:'api/oauth/newQuickLogin',
					data:{
						open_id:open_id
					}
			}).then(res=>{
					res = res.data;
					if(res.status){
						if(res.data.access_token){
							var access_token = res.data.token_type + ' ' + res.data.access_token;
							var expires_in = res.data.expires_in || 315360000; 
							this.$cookieStorage.set("user_token", access_token, expires_in);
							//如果用户没有绑定手机号
							if(res.data.has_bind_mobile == 0){
								wx.reLaunch({
									url:'/pages/user/bindingphone/bindingphone'
								})
							}
						} else{
							wx.showModal({
								content: res.message || '请求失败，请重试',
								showCancel: false
							});
							
						}
						
					} else{
						wx.showModal({
							content: res.message || '请求失败，请重试',
							showCancel: false
						});
					}
					wx.hideLoading()
				}).catch(rej=>{
					wx.showModal({
						content: rej.message || '请求失败，请重试',
						showCancel: false
					});
					wx.hideLoading()
					
				})
			},
			togglePopup(type) {
						this.type = type;
			},
			closeAlert() {
			  this.setData({
			    is_refused: false
			  });
			},
			shareapp(){
					var reduce_items_id = this.reduce_items_id;
					  uni.getProvider({
						  service:'share',
						  success:function(res){
							  uni.share({
							       provider: "weixin",
							       scene: "WXSceneSession",
							       type: 5,
							       title:'砍价帮帮忙',
							       imageUrl:'https://cdn.guojiang.club/guojiang_logo.png',  
							  			  miniProgram:{
							  				  id:'gh_72e65196278a',//小程序原始id
							  				  path:'pages/bargain/details/details?reduce_items_id='+ reduce_items_id,
							  				  type:0,
							  				  webUrl:'https://guojiang.club'
							  			  },
							       success: function (res) {
							           console.log("success:" + JSON.stringify(res));
							       },
							       fail: function (err) {
							           console.log("fail:" + JSON.stringify(err));
							       }
							   });
						  }
					  })
					  this.closeShare();
					  
					 
			},
			selectSpec(e) {
			  var spec = {
			    key: e.currentTarget.dataset.key,
			    index: e.currentTarget.dataset.index, 
			    disabled: Number(e.currentTarget.dataset.disabled),
			    active: Number(e.currentTarget.dataset.active),
			    id: Number(e.currentTarget.dataset.id)
			  };
			  if (spec.disabled) return;
			  var specs = this.specs;
			
			  if (!spec.active) {
			    for (let item of specs[spec.index].values) {
			      if (item.active) {
			        item.active = false;
			        break;
			      }
			    }
			  }
			
			  specs[spec.index].values[spec.key].active = !specs[spec.index].values[spec.key].active;
			  spec.active = !spec.active;
			  specs[spec.index].select = spec.active ? spec.id : '';
			  this.setData({
			    specs: specs
			  });
			  var canBuy = this.disallow_cart();
			  this.setData({
			    canBuy: canBuy
			  }); // this.queryCommodityStore(id, spec.index);
			
			  this.specStore(this.result, spec.index);
			},
			specStore(result, key) {
	
					
			     var query = {
					 id:this.goods_id
				 };
			   var data = result.data;
			   var specs = this.specs;
			
			   if (key === undefined) {
			     specs.forEach(spec => {
			       for (let v of spec.values) {
			         v.disabled = !data[v.id] || data[v.id].count == 0;
			       }
			     });
			     this.setData({
			       specs: specs,
			       skuTable: result.table
			     });
			     specs = this.specs;
			     var canBuy = this.disallow_cart();
			     this.setData({
			       canBuy: canBuy
			     });
			     specs.forEach(spec => {
			       let name = 'spec[' + spec.id + ']';
			
			       if (query[name]) {
			         let id = query[name];
			
			         for (let v of spec.values) {
			           if (v.id == id && !v.disabled && data[v.id] && data[v.id].count) {
			             v.active = true;
			             spec.select = v.id;
			             this.setData({
			               specs: specs
			             });
			             specs = this.specs;
			             var canBuy = this.disallow_cart();
			             this.setData({
			               canBuy: canBuy
			             });
			             this.specStore(result, v.index);
			             return;
			           }
			         }
			       }
			
			       if (!spec.select) {
			         for (let v of spec.values) {
			           if (!v.disabled && data[v.id] && data[v.id].count) {
			             v.active = true;
			             spec.select = v.id;
			             this.setData({
			               specs: specs
			             });
			             specs = this.specs;
			             var canBuy = this.disallow_cart();
			             this.setData({
			               canBuy: canBuy
			             }); // this.$emit('specStore', result, v.index);
			
			             this.specStore(result, v.index);
			             return;
			           }
			         }
			
			         return;
			       }
			
			       this.setData({
			         specs: specs
			       });
			     });
			     return;
			   }
			
			   var spec = specs[key];
			
			   if (spec.select) {
			     this.setData({
			       store_count: data[spec.select].count
			     });
			
			       for (let i = 0; i < specs.length; i++) {
			       if (i == key) continue;
			         
			         specs[i].values.forEach(v => {
			           
			          v.disabled = !data[spec.select].specs[v.id].count;
					
			       });
			
			       if (specs[i].select) {
			         this.setData({
			           store_count: data[spec.select].specs[specs[i].select].count
			         });	
			       }
			
			       this.setData({
			         specs: specs
			       });
			     }
			   } else {
			     this.setData({
			       store_count: this.detailsMessage.reduce.reduce_store_nums
			     });
			
			     for (let i = 0; i < specs.length; i++) {
			       if (i == key) continue;
			       specs[i].values.forEach(v => {
			         v.disabled = !data[v.id] || !data[v.id].count;
			       });
			
			       if (specs[i].select) {
			         this.setData({
			           store_count: data[specs[i].select].count
			         });
			       }
			
			       this.setData({
			         specs: specs
			       }); 
			     }
			   }
			
			   if (parseInt(this.select_count) > this.store_count) {
			     this.setData({
			       select_count: String(this.store_count)
			     });
			   } else if (parseInt(this.select_count) == 0) {
			     this.setData({
			       select_count: '1'
			     });
			   }
			
			   this.setData({
			     specs: specs
			   });
			   var canBuy = this.disallow_cart();
				  
				  
			//    this.setData({
			//      canBuy: canBuy
			//    });
				  // 
				  this.canBuy=canBuy;
			 },
			
			confirmF() {
				if (this.loading) return;
				if (this.disallow_cart()) return;
				this.loading =  true;

				var select_product = this.select_product;
				var select_count = Number(this.select_count)
				var data = this.specs.length ? {
					id: select_product.id,
					name: this.name,
					qty: select_count,
					store_count: this.store_count,
					price: this.time_price,
					market_price: this.market_price,
					attributes: {
						img: select_product.img || this.detailsMessage.reduce.goods.img,
						size: select_product.size,
						color: select_product.color,
						com_id: this.goods_id
					}
				} : {
					id:this.goods_id,
					name: this.detailsMessage.name,
					qty: select_count,
					store_count: this.store_count,
					price: this.time_price,
					market_price: this.detailsMessage.market_price,
					attributes: {
						img: this.detailsMessage.reduce.goods.img,
						com_id:this.goods_id
					}
				};
				if (select_product.sku) {
					data.attributes.sku = select_product.sku;
				}
				this.checkoutImmdeOrder(data)
			},
			disallow_cart() {
			  if (!this.specs.length) {
			    return !this.store_count;
			  }
			
			  var ids = [],
			      select_product = {},
			      specs = this.specs; // console.log(this.commodity.sell_price)
			
			  /* this.setData({
			    price: Number(this.commodity.sell_price).toFixed(2)
			  }); */
			
			  for (let spec of specs) {
			    if (!spec.select) {
			      this.setData({
			       /* price: Number(this.commodity.sell_price).toFixed(2), */
			        select_product: null
			      });
			      return true;
			    }
			
			    ids.push(spec.select);
			
			    for (let v of spec.values) {
			      if (v.id == spec.select) {
				
			        switch (spec.label_key) {
			          case 'color':
			            select_product.img = v.spec_img;
			            select_product.color = v.alias || v.value;
			            select_product.bac = v.color;
			            break;
			
			          default:
			            select_product.size = v.alias || v.value;
			        }
			
			        break;
			      }
				 
			    }
			  }
			
			  if (this.skuTable) {
			    ids = ids[0] > ids[1] ? [ids[1], ids[0]] : ids;
			    ids = ids.join('-');
			    select_product = Object.assign(select_product, this.skuTable[ids]);
			
			  }
			  var new_bargin_price = Number(select_product.price)-Number(this.detailsMessage.reduce_amount);
			  this.setData({
			    time_price: new_bargin_price.toFixed(2),
			    select_product: select_product
			  });
			  return false;
			},
			
			// 请求sku
			queryCommodityStore(id, key) {
				var that = this;
				this.$http.get({
					api: `api/store/detail/${id}/stock`
				}).then(res => {
					wx.hideLoading();
					res = res.data;
					if (!res.status || !res.data || !res.data.specs) return;

					if (res.data.specs && typeof key === 'undefined') {
						let specs = [];
						Object.keys(res.data.specs).forEach((key, index) => {
							let value = res.data.specs[key];
							value.select = '';
							value.values = value.list.map(v => {
								return Object.assign({
									index: index,
									active: false,
									disabled: false
								}, v);
							});
							delete value.list;
							specs.push(value);
						});
						that.setData({
						  specs: specs
						}); // console.log(specs)
						
						var canBuy = this.disallow_cart();
						this.setData({
						  canBuy: canBuy
						});
					}
					if (res.data.stores) {
						let data = {};
						Object.keys(res.data.stores).forEach(key => {
							let value = res.data.stores[key];
							value.ids.forEach(id => {
								data[id] = data[id] || {
									count: 0,
									specs: {}
								};
								data[id].count += Number(value.store);
								value.ids.forEach(i => {
									if (i == id) return;
									data[id].specs[i] = {
										count: Number(value.store)
									};
								});
							});
						}); // console.log(data);

						var result = {
							data,
							table: res.data.stores
						};
						// this.setData({
						//   result: result
						// });

						this.result = result;

						
						that.specStore(result, key); // this.$emit('specStore', result, key);
					}
				});
			},
			//关闭sku
			closeSelect() {
				// var animation = new Animation('show');
				// animation.up().then(() => {
				this.setData({
					show_select: true
				})
				// })
			},
			//获取详情页信息
			getMessage() {
				var token = this.$cookieStorage.get('user_token');
				this.$http.get({
					api: `api/reduce/showItem?reduce_items_id=${this.reduce_items_id}`,
					header: {
						Authorization: token
					},
				}).then(res => {
					if (res.statusCode == 200) {
						if (res.data.data.status_text !== "进行中" && res.data.data.status_text !== "已下单待支付" && res.data.data.reduce.status_text ==
							"进行中" && res.data.data.time_price !== "0.00") {
							this.overTime =  true;
							this.overActivity = false;
							this.setColor = 'AAAAAA';
						} else if (res.data.data.reduce.status_text !== "进行中") {
							this.overActivity = true;
							this.setColor = 'AAAAAA';
						} else if (res.data.data.status_text == "订单已支付") {
							this.pay = true;
							this.over = true;
						} else if (res.data.data.status_text == "进行中" && res.data.data.reduce.status_text == "进行中") {
							this.overTime = false;
							this.overActivity = false;
							this.setColor = 'fb5054';
						}
						if (res.data.data.reduce_surplus_amount == "0.00") {
							this.over = true;
						}
						this.setData({
							detailsMessage: res.data.data,
							is_leader: res.data.data.user_is_leader,
							// is_leader:0,
							reduce_id: res.data.data.reduce_id,
							id: res.data.data.id,
							goods_id: res.data.data.reduce.goods_id,
							name: res.data.data.reduce.goods.name,
							store_count: res.data.data.reduce.store_nums,
							market_price: res.data.data.reduce.goods.market_price,
							time_price: res.data.data.time_price
						})
						this.disallow_cart();
						this.queryCommodityStore(this.goods_id);
						this.showWitch();
						if (this.detailsMessage.progress_par > 0.17 && this.detailsMessage.progress_par < 0.83) {
							let percent = parseInt(this.detailsMessage.progress_par * 100) - 17
							this.setData({
								left: percent
							})
						} else if (this.detailsMessage.progress_par == 0.83 || this.detailsMessage.progress_par > 0.83) {
							this.setData({
								left: 67
							})
						} else {
							this.setData({
								left: 0
							})
						}
						// #ifdef H5
							if (this.$wechat && this.$wechat.isWechat()) {  
								var origin = window.location.origin;
								var pathname = window.location.pathname;
								var path = origin+pathname+'?reduce_items_id='+this.reduce_items_id
								 this.$wechat.share({
									  title:' 砍价帮帮忙',
									  img:'https://cdn.guojiang.club/h5_share_logo.png',
									  desc:'果酱小店'
								},path);  
							}  
						// #endif  
						
					} else {
						wx.showToast({
							title: res.data.data.message,
							icon: none,
							duration: 2000,

						})
					}
				})
				this.showWitch()
			},
			bargainAgin() {

				var token = this.$cookieStorage.get('user_token');
				var id = this.reduce_id;
				var data = {
					reduce_id: id,
					restart: 1
				}
				this.$http.post({
					api: `api/reduce`,
					header: {
						Authorization: token
					},
					data: data
				}).then(res => {
					if (res.statusCode == 200) {
						wx.showToast({
							title: '已重新发起砍价',
							duration: 2500
						})
						this.reduce_items_id = res.data.data.reduce_items_id;
						this.getMessage()
						this.showWitch()
					} else {}
				})
			},
			showWitch() {
				if (this.is_leader == 1) {
					this.setData({
						message: '邀请好友砍价'
					})
				} else if (this.is_leader == 0 && this.step == 1) {
					this.setData({
						message: '帮TA砍价'
					})
				} else if (this.is_leader == 0 && this.step == 2) {
					this.setData({
						message: '我也要去砍价'
					})
				}
			},
			downImg() {
				if (this.shareImg) {
				  wx.showLoading({
				    title: '正在下载',
				    mask: true
				  });
				  this.$http.dowloadFile({
				    api: this.shareImg
				  }).then(res => {
				    if (res.statusCode == 200) {
				      // #ifdef MP-WEIXIN
				      wx.getSetting({
				        success: ret => {
				          // 如果之前没有授权
				          if (!ret.authSetting['scope.writePhotosAlbum']) {
				            wx.authorize({
				              scope: 'scope.writePhotosAlbum',
				              success: rej => {
				                this.saveImg(res.tempFilePath);
				              },
				              // 用户拒绝授权
				              fail: ret => {
				                this.setData({
				                  is_refused: true
				                });
				                wx.hideLoading();
				              }
				            });
				          } else {
				            this.saveImg(res.tempFilePath);
				          }
				        }
				      });
				      // #endif
							// #ifdef APP-PLUS
							var that = this;
							uni.getSystemInfo({
								success(result) {
									if(result.platform == 'android'){
										that.requestAndroidPermission(res.tempFilePath);
									} else if(result.platform == 'ios'){
										that.requestIosPermission(res.tempFilePath)
									}
									
								}
							})
							// #endif
				    } else {
				      wx.hideLoading();
				      wx.showToast({
				        title: '下载图片失败',
				        icon: 'none'
				      });
				    }
				  }, err => {});
				}
			},
			//ios授权
			requestIosPermission(url){
				var result = permision.judgeIosPermission('photoLibrary');
				if(result){
					this.saveImg(url);
				}else{
					//打开授权，iOS上如果没有调用过的权限，不会出现在权限设置界面。
					permision.gotoAppPermissionSetting()
				}
			},
			// 安卓app授权
			async requestAndroidPermission(url) {
			    var result = await permision.requestAndroidPermission("android.permission.WRITE_EXTERNAL_STORAGE")
			    var strStatus
			    if (result == 1) {
			        strStatus = "已获得授权";
					this.saveImg(url);
			    } else if (result == 0) { 
			        strStatus = "未获得授权";
							permision.gotoAppPermissionSetting()
			    } else {
			        strStatus = "被永久拒绝权限"
							permision.gotoAppPermissionSetting()
			    }
			},
			// 保存图片
			saveImg(path) {
			  wx.saveImageToPhotosAlbum({
			    filePath: path,
			    success: res => {
			      wx.hideLoading();
				  wx.showToast({
				    title: '保存图片成功',
				    icon: 'success'
				  }); 
			    },
			    fail: rej => {
			      wx.hideLoading();
			      wx.showToast({
			        title: '保存图片失败',
			        icon: 'none'
			      });
			    }
			  });
			},
			
			//获取当前时间
			getServer() {
				var date = new Date();
				var seperator1 = "-";
				var seperator2 = ":";
				var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
				var strDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
				var server = date.getFullYear() + seperator1 + month + seperator1 + strDate +
					" " + date.getHours() + seperator2 + date.getMinutes() +
					seperator2 + date.getSeconds();
				this.server =  server;
			},
			closeTell() {
				this.setData({
					showTell: false
				})
			},
			showTellphone() {
				this.setData({
					showTell: true
				})
			},
			closeShare() {
				this.setData({
					showShare: false
				})
			},
			// 弹出分享
			changeShare() {
				this.setData({
					showShareImg: true
				})
			},
			// 生成海报
			createShareImg() {
				this.showShare = false;
				wx.showLoading({
					title: "生成中",
					mask: true
				})
				var token = this.$cookieStorage.get('user_token') || '';
				this.$http.get({
					api: `api/reduce/share?reduce_items_id=${this.reduce_items_id}`,
					header: {
						Authorization: token
					},
					//    data:{
					//        goods_id: this.data.showItemDate.multi_groupon_goods_id,
					//    }
				}).then(res => {
					if (res.statusCode == 200) {
						var res = res.data
						if (res.status) {
							this.shareImg = res.data.image;
							//this.getShearImg();
						} else {
							wx.showModal({
								content: res.message || '请求失败',
								showCancel: false
							})
						}
					} else {
						wx.showModal({
							content: '请求失败',
							showCancel: false
						});
					}
					wx.hideLoading();
					this.changeShare();
				})
			},
			closeAlert() {
				this.setData({
					is_refused: false
				})
			},
			helpShare() {
				this.setData({
					showShare: true
				})
			},
			showNoticeInfo() {
				this.setData({
					showNotice: true
				})
			},
			closeNotice() {
				this.setData({
					showNotice: false
				})
				this.getMessage()
			},
			//好友也要零元拿
			joinBargain() {
				if (this.overActivity == true) {
					this.setData({
						showTell: true
					})
				} else {
					wx.navigateTo({
						url: '/pages/bargain/index/index'
					})
				}
			},
			goStore() {
				wx.switchTab({
					url: '/pages/index/index/index'
				})
			},
			bargain() {
				var token = this.$cookieStorage.get('user_token');
				if (this.is_leader == 0) {
					this.$http.post({
						api: `api/reduce/help?reduce_items_id=${this.reduce_items_id}`,
						header: {
							Authorization: token
						}
					}).then(res => {
						if (res.statusCode == 200) {
							this.setData({
								step: 2
							})
							if (res.data.code == 400) {
								wx.showToast({
									title: res.data.message,
									icon: 'none',
									duration: 2000
								})
								setTimeout(function() {
									this.setData({
										step: 2
									})
									this.showWitch();
								}, 2000)
							} else {
								this.setData({
									showNotice: true,
									step: 2
								})
							}
							if (res.data.data.reduce_amount) {
								this.setData({
									reduce_amount: res.data.data.reduce_amount,
									step: 2
								})
							}
							this.showWitch();
						} else {
							wx.showToast({
								title: '您暂时不能帮好友砍价',
								icon: 'none',
								//duration: 3000
							})
							setTimeout(function() {
								this.setData({
									step: 2
								})
								wx.hideToast()
								//that.showWitch();  
							}, 3000)
						}
						this.getMessage()
					})
					this.getMessage()

				}
				this.getMessage()
				this.showWitch();
			},
			showRule() {
				this.setData({
					show: true
				})
			},
			closeRule() {
				this.setData({
					show: false
				})
			},
			// 获取用户信息
			getUserInfo() {
				var token = this.$cookieStorage.get('user_token')
				this.$http.get({
					api: 'api/me',
					header: {
						Authorization: token
					},
				}).then(res => {
					res = res.data;
					if (res.status) {
						this.setData({
							userInfo: res.data,
						}, () => {
							if (res.data.agent_code) {
								wx.updateShareMenu();
							}
						})
					}
				})
			},
			//选择sku
			showSelect(e) {
				this.setData({
					show_select: false
				})
			},
			// 立即购买
			checkoutImmdeOrder(data) {
				var token = this.$cookieStorage.get('user_token');
				this.$http.post({
					api: 'api/shopping/order/checkout?product_id=' + data.id + '&reduce_items_id='+this.reduce_items_id,
					header: {
						Authorization: token
					},
					data: data
				}).then(res => {
					if (res.statusCode == 200) {
						res = res.data;

						if (res.status) {
							this.$cookieStorage.set('local_order', res.data);
							wx.navigateTo({
								url: `/pages/store/order/order?reduce_items_id=${this.reduce_items_id}&bargain=true`
							});
						} else {
							if (res.data && res.data.server_busy) {
								this.show_ten =  true;
							} else if (res.message == 'User unbind mobile') {
								wx.showModal({
									content: '请先绑定手机号',
									showCancel: false,
									success: res => {
										if (res.confirm || !res.cancel && !res.confirm) {
											wx.navigateTo({
												url: '/pages/user/phone/phone?url=' + getUrl()
											});
										}
									}
								});
							} else {
								wx.showModal({
									content: res.message || '请求失败',
									showCancel: false
								});
							}

							this.loading =  false;
						}
					}
				});
			},
			showToast() {
				wx.showToast({
					title: '请选择商品的规格',
					icon: 'none',
					duration: 2000
				})
			},
			changeImg() {
				this.setData({
					showShareImg: false
				})
			},
			//活动规则
			getRule() {
				this.$http.get({
					api: 'api/reduce/help/text'
				}).then(res => {
					if (res.statusCode == 200) {
						this.setData({
							rule: res.data.data.reduce_help_text
						})
					}
				})
			},
			setData: function(obj) {
				let that = this;
				let keys = [];
				let val, data;
				Object.keys(obj).forEach(function(key) {
					keys = key.split('.');
					val = obj[key];
					data = that.$data;
					keys.forEach(function(key2, index) {
						if (index + 1 == keys.length) {
							that.$set(data, key2, val);
						} else {
							if (!data[key2]) {
								that.$set(data, key2, {});
							}
						}

						data = data[key2];
					});
				});
			}






		}
	}
</script>

<style rel="stylesheet/less" lang="less">
	@import "detail";
</style>
