<template>
	<view>
		<view class="bargain_contanier">
			<view class="bargain_head">
				<image mode="widthFix" src="https://cdn.ibrand.cc/heads%20%281%29.png"></image>
			</view>
			<view class="rule" @tap="changeRule">
				活动规则
			</view>
			<view class="body_box">
				<view class="bargain_body" v-for="(items,idx) in list" :key="idx">
					<view v-for="(item,index) in items" :key="index">
						<view class="bargain_goods">
							<view class="goods_left">
								<image mode="widthFix" :src="item.goods.img"></image>
							</view>
							<view class="goods_right">
								<view class="goods_name">{{item.goods.name}}</view>
								<view class="number">剩余{{item.store_nums}}砍价名额</view>
								<view class="past_price">原价 ￥<span>{{item.goods.max_price}}</span></view>
								<view class="right_foot">
									<view class="new_price">
										砍后价￥{{item.price}}
									</view>
									<!-- #ifdef MP-WEIXIN -->
									<view class="btn" @tap.native.stop="clickBargain" :data-id="item.id">
										发起砍价
					
									</view>
									<button class="bind-btn" open-type="getUserInfo" @getuserinfo="bindUserInfo"  style="opacity: 0;" v-if="token && !user_info_fill">
									
									</button>
								
									<!-- #endif -->
									
									<!-- #ifdef APP-PLUS ||H5  -->
									<view class="btn" @tap="clickBargain" :data-id="item.id">
										发起砍价			
									</view>
									<!-- #endif -->
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="box_body" v-if="show" @tap.stop="changeRule" @touchmove.stop="true">
				<scroll-view scroll-y class="rule_box">
					<text>{{rule}}</text>
				</scroll-view>
				<view class="iconfont icon-close" @tap.stop="changeRule"></view>
			</view>
		</view>

	</view>

</template>

<script>
	import uParse from '@/components/gaoyia-parse/parse.vue';
	import {
		pageLogin,
		getUrl,
		config,
		is
	} from '@/common/js/utils.js';
	export default {
		components: {
			uParse
		},
		data() {
			return {
				show: false,
				rule: '京东方公安三季度非附近的双方各见风使舵公开',
				list: [],
				prices: [],
				page: 1,
				more: true,
				user_info_fill:0,//用户是否完善信息
				token:''
			}
		},
		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;
							var url = origin+'/pages/bargain/index/index';
							window.location.href = this.$config.GLOBAL.baseUrl+'oauth/wxOauth?redirect_url='+encodeURIComponent(url);
						}
					} else{
						let url = getUrl();
						wx.navigateTo({
							url:'/pages/user/loginType/loginType?url='+url
						})
					}
			}
			// #endif
			var windowHeight = wx.getSystemInfoSync().windowHeight //获取设备的高度
			var token = this.$cookieStorage.get('user_token');
			this.token = token;
			this.Height =  windowHeight;
			this.getReduceList(1);
			this.getHelpText();
			if(token){
				this.getUserInfo()
			}
			

		},
		//下拉刷新
		    onReachBottom(){
		        if(this.more){
		            let page = this.page + 1;
		            this.getReduceList(page);
		        } else {
		            wx.showToast({
		                image: '../../../static/error.png',
		                title: '再拉也没有啦'
		            });
		        }
		    },
		methods: {
			//h5微信登陆
			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()
					
				})
				
			},
			//绑定用户信息
			bindUserInfo(e) {
				console.log(e)
				if (e.detail.encryptedData) {
					this.updateUserInfo(e.detail);
				}
			},
			updateUserInfo(data) {
				wx.showLoading({
					title: '更新中',
					mask: true
				});
				this.$http.get({
					api: 'api/user/bindUserMiniInfo',
					data: data,
					header: {
						Authorization: this.$cookieStorage.get('user_token')
					}
				}).then(res => {
						res = res.data;
						if (res.status) {
							wx.showModal({
								content:"用户信息更新完成,请砍价",
								showCancel:false
							})
						} else {
							wx.showModal({
								content: res.message || '请求失败',
								showCancel: false
							});
						}
						wx.hideLoading();
				});
			},
			
			//获取用户信息
			getUserInfo() {
				this.$http.get({
					api: 'api/me',
					header: {
						Authorization: this.$cookieStorage.get('user_token')
					}
				}).then(res => {
					res  = res.data;
					if (res.status) {
						this.user_info_fill = res.data.user_info_fill
					}
				});
			},
			
			// 点击发起砍价按钮
			clickBargain(e) {
				let token = this.$cookieStorage.get('user_token');
				if (token) {
					// 发起砍价请求
					let id = e.currentTarget.dataset.id;
					this.id = id;
					this.postReduce(id);
				} else {
					// #ifdef MP-WEIXIN || APP-PLUS
					var url = getUrl();
					// #endif
					// #ifdef H5
					var url = getUrl();
					// #endif
					wx.showModal({
						content: '请先登录',
						success: res => {
							if (res.confirm) {
								// #ifdef APP-PLUS || MP-WEIXIN
								wx.navigateTo({
								  url: '/pages/user/register/register?url=' + url
								});
								// #endif
								
								// #ifdef H5
								wx.navigateTo({
								  url: '/pages/user/register/register?url=' + encodeURIComponent(url)
								});
								// #endif
							}
						}
					});
				}

			}, 
			// 发起砍价的请求
			postReduce(reduce_id) {
				wx.showLoading({
					title: "请求中",
					mask: true
				});
				let token = this.$cookieStorage.get('user_token');
				this.$http.post({
					api: 'api/reduce',
					header: {
						Authorization: token
					},
					data: {
						reduce_id: reduce_id
					}
				}).then(res => {
					res = res.data;
					if (res.status) {
						this.reduce_items_id =  res.data.reduce_items_id
						// 判断是否可以跳砍价页面，如果不能就需要跳到订单详情页去
						this.getReduceShowItem();
					} else {
						wx.showModal({
							content: res.message || '请求失败',
							showCancel: false
						})

					}
					wx.hideLoading()

				}).catch(rej => {
					wx.showModal({
						content: rej.message || '请求失败',
						showCancel: false
					})
					wx.hideLoading()
				})



			},


			// 获取砍价的规则
			getHelpText() {
				this.$http.get({
					api: 'api/reduce/help/text'
				}).then(res => {

					res = res.data;
					if (res.status) {
						this.setData({
							rule: res.data.reduce_help_text
						})
					} else {
						wx.showModal({
							content: res.message || '请求失败',
							showCancel: false
						})

					}
				}).catch(rej => {
					wx.showModal({
						content: rej.message || '请求失败',
						showCancel: false
					})
				})
			},
			// 请求是否是可以跳到砍价详情页
			getReduceShowItem() {
				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 => {
					res = res.data;
					if (res.status) {
						if (res.data.order != null) {
							if (res.data.order.status == 1) {
								{
									wx.navigateTo({
										url: `/pages/order/detail/detail?no=${res.data.order.order_no}`
									})
								}
							} else {
								wx.navigateTo({
									url: `/pages/bargain/detail/detail?reduce_items_id=${this.reduce_items_id}&id=${this.id}`
								})
							}
						} else {
							wx.navigateTo({
								url: `/pages/bargain/detail/detail?reduce_items_id=${this.reduce_items_id}&id=${this.id}`
							})
						}
					} else {
						wx.showModal({
							content: res.message || '请求失败',
							showCancel: false
						})

					}
				})
			},

			// 弹起活动规则
			changeRule() {
				this.setData({
					show:!this.show
				})
			},
			// 获取页面列表数据
			getReduceList(page) {
				wx.showLoading({
					title: "加载中",
					mask: true
				});
				this.$http.get({
					api: 'api/reduce/list',
					data: {
						page:page
					}
				}).then(res => {

					res = res.data;
					if (res.status) {
						let pages = res.meta.pagination;
						let current_page = pages.current_page;
						let total_pages = pages.total_pages;
						this.setData({
							[`list.${page-1}`]: res.data,
							more: current_page < total_pages,
							page: current_page
						})
					} else {
						wx.showModal({
							content: res.message || '请求失败',
							showCancel: false
						})
					}

					this.setData({
						show: false
					})
					wx.hideLoading()
				}).catch(rej => {
					wx.hideLoading()
					wx.showModal({
						content: rej.message || '请求失败',
						showCancel: false
					})
				})

			},
			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 "index";
</style>
