// index.js
let myPro = require("../../utils/wxRequest.js");
let util = require("../../utils/util.js");
Page({
    data: {
		setBgHeight: getApp().globalData.setBgHeight,
		imgUrl: getApp().globalData.imgUrl,
		fare_type: 1, // 0外卖 1自提   默认自取
		is_member: 0, // 是否为会员
		showGoodsSpec: false,
		cartGoods: [], // 购物车商品
		addGoodList: [], // 活动加购商品
		resultArr: [], // 选中商品
		checkedAll: true,
		resultAll: [], // 测试
		totalNums: 0, // 加购商品总数
		totalPrice: 0, // 加购商品总价(原价)
		totalMemberPrice: 0, // 加购商品总价(会员价)
		showAdGoodsSpec: false,
		isHaveGoods: true // 是否有商品
    },
    onLoad: function (options) {
        // Do some initialize when page load.
    },
    onShow: function () {
        // Do something when page show.
		let that = this;
		that.setData({
			is_member: getApp().globalData.is_member
		});
		// 获取配送方式
		if(wx.getStorageSync('fare_type')){
			that.setData({
				fare_type: wx.getStorageSync('fare_type')
			})
		};
		that.getCartsList();
    },
    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
    },
	// 获取购物车商品
	getCartsList(){
		let that = this;
		let params = {};
		myPro.wxRequest("user/v3/carts/list","GET",params).then(res=>{
			// 普通商品
			let list = res.result.list;
			if(list.length != 0){
				that.setData({
					isHaveGoods: true
				})
			}else{
				that.setData({
					isHaveGoods: false
				})
			}
			// 活动加购商品
			let addGoodList = res.result.add_good_list;
			that.setData({
				cartGoods: list,
				addGoodList: addGoodList,
				totalNums: res.result.total_num,
				totalPrice: res.result.money // 接口返回的,不需再关注是否为会员价
			});
			// 商品选中状态
			let resultArr = [];
			for(let i in list){
				if(list[i].selected){
					resultArr.push(''+list[i].id);
				}
			};
			that.setData({
				resultArr: resultArr
			});
		}).catch(err=>{
			console.log('报错信息',err);
			wx.showToast({
				title: err,
				icon: "none"
			});
		})
	},
	// 展示详情
	onGoodsSpec(event){
		let that = this;
		let item = event.currentTarget.dataset.item;
		that.setData({
			currentGoods: item, // 商品加购的规格(不带多规格)
			showGoodsSpec: true
		});
	},
	// 关闭详情
	closeGoodsSpec(){
		let that = this;
		that.setData({
			showGoodsSpec: false,
		});
	},
	// 更改购物车商品
	onChangeCartNum(event){
		let that = this;
		let nums = event.detail;
		let item = event.currentTarget.dataset.item;
		let params = {
			id: item.id,
			nums: nums
		};
		// console.log('event',event)
		// return;
		myPro.wxRequest("user/v3/carts/editnum","POST",params).then(res=>{
			that.getCartsList();
		}).catch(err=>{
			console.log('报错信息',err);
			wx.showToast({
				title: err,
				icon: "none"
			});
		})
	},
	// 删除商品
	bindDel(event){
		let that = this;
		console.log('event',event);
		let item = event.currentTarget.dataset.item;
		let params = {
			id: item.id
		};
		myPro.wxRequest("user/v3/carts/remove","POST",params).then(res=>{
			// 主动调购物车,更新信息
			that.getCartsList();
		}).catch(err=>{
			console.log('报错信息',err);
			wx.showToast({
				title: err,
				icon: "none"
			})
		})
	},
	// 选择
	onChangeResult(event){
		let that = this;
		console.log(event.detail);
		that.setData({
			resultArr: event.detail
		});
	},
	// 切换状态
	toggleGoods(event){
		console.log('切换状态',event);
		let that = this;
		let id = event.currentTarget.dataset.id;
		let resultArr = that.data.resultArr;
		let params = {
			id: id
		};
		if(resultArr.includes(''+id)){
			params.selected = 1;
			// 选中
			myPro.wxRequest("user/v3/carts/selected","POST",params).then(res=>{
				that.getCartsList();
			}).catch(err=>{
				console.log('报错信息',err);
				wx.showToast({
					title: err,
					icon: "none"
				})
			})
		}else{
			// 取消选中
			params.selected = 0;
			// 选中
			myPro.wxRequest("user/v3/carts/selected","POST",params).then(res=>{
				that.getCartsList();
			}).catch(err=>{
				console.log('报错信息',err);
				wx.showToast({
					title: err,
					icon: "none"
				})
			})
		}
	},
	// 去结算
	toPay(){
		let that = this;
		// 判断商品是否勾选(如果都未勾选提示一下)
		// console.log('resultArr',that.data.resultArr);
		let resultArr = that.data.resultArr;
		if(resultArr.length == 0){
			wx.showToast({
				title: "请勾选商品",
				icon: "none"
			})
			return;
		};
		// 验证是否能下单(有可能不在营业时间)
		wx.request({
			url: getApp().globalData.api + "user/v3/order/createlist",
			data: {
				"token": getApp().globalData.token
			},
			success: function(res) {
				if(res.data.code == 200){
					// 如果是外卖，看是否有收货地址
					if(that.data.fare_type == 0 ){
						if(!wx.getStorageSync('checkedAddress')){
							wx.navigateTo({
								url: "/pages/user/address/list/index"
							});
						}else{
							wx.navigateTo({
								url: "/pages/create-order/index"
							});
						}
					}else{
						// 路由跳转：需要保留购物车页面(因为从购物车往后的步骤都可能回退),但注意更新购物车
						wx.navigateTo({
							url: "/pages/create-order/index"
						});
					}
				}else{
					wx.showToast({
						title: res.data.msg,
						icon: "none"
					});
				}
			}
		});
	},
	// 活动加购商品
	onAdGoodsSpec(event){
		let that = this;
		let cartGoods = that.data.cartGoods;
		let item = event.currentTarget.dataset.item;
		let currentAdGoodsSpec = null;
		if(item.add_good_rule_good_spec && item.add_good_rule_good_spec.length != 0){
			for(let i in item.add_good_rule_good_spec){
				if(i == 0){
					item.add_good_rule_good_spec[i].is_checked = true; // 默认选中第一个
					currentAdGoodsSpec = item.add_good_rule_good_spec[i];
				}else{
					item.add_good_rule_good_spec[i].is_checked = false;
				}
			};
			// 跟购物车对比,拿数量
			for(let k in cartGoods){
				if(currentAdGoodsSpec.good_id == cartGoods[k].good_id && currentAdGoodsSpec.good_spec_id == cartGoods[k].good_specs_id && currentAdGoodsSpec.add_good_rule_id == cartGoods[k].add_good_rule_id){
					currentAdGoodsSpec.nums = cartGoods[k].nums;
					break;
				}
			}
		};
		that.setData({
			showAdGoodsSpec: true,
			currentAdGoods: item,
			currentAdGoodsSpec: currentAdGoodsSpec
		});
		// console.log('活动加购商品',that.data.currentAdGoods);
	},
	// 切换规格
	onChangeSpecGoods(event){
		let that = this;
		console.log(event);
		let specs = event.currentTarget.dataset.specs;
		let currentAdGoods = that.data.currentAdGoods;
		let cartGoods = that.data.cartGoods;
		if(currentAdGoods.add_good_rule_good_spec && currentAdGoods.add_good_rule_good_spec.length != 0){
			for(let i in currentAdGoods.add_good_rule_good_spec){
				let item = currentAdGoods.add_good_rule_good_spec[i];
				if(item.good_spec_id == specs.good_spec_id){
					item.is_checked = true;
				}else{
					item.is_checked = false;
				}
			};
			// 跟购物车对比,拿数量
			for(let k in cartGoods){
				if(specs.good_id == cartGoods[k].good_id && specs.good_spec_id == cartGoods[k].good_specs_id && specs.add_good_rule_id == cartGoods[k].add_good_rule_id){
					specs.nums = cartGoods[k].nums;
					break;
				}
			};
		};
		that.setData({
			currentAdGoods: currentAdGoods,
			currentAdGoodsSpec: specs
		});
	},
	// 关闭活动加购商品
	closeAdGoodsSpec(){
		let that = this;
		that.setData({
			showAdGoodsSpec: false
		})
	},
	// 点击活动加购商品(多规格)
	onChangeAdGoodsSpecNum(event){
		let that = this;
		let nums = event.detail;
		// console.log('event',event);
		let item = event.currentTarget.dataset.item;
		let itemObj = {
			good_id: item.good_id,
			add_good_rule_id: item.add_good_rule_id,
			good_specs_id: item.good_spec_id
		};
		// console.log('当前规格',itemObj);
		that.handleAdGoods(itemObj,nums);
	},
	// 点击活动加购商品(无规格)
	onChangeAdGoodsNum(event){
		let that = this;
		let nums = event.detail;
		let item = event.currentTarget.dataset.item;
		let itemObj = {
			good_id: item.add_good_id,
			add_good_rule_id: item.id,
			good_specs_id: item.add_good_spec_id
		};
		that.handleAdGoods(itemObj,nums);
	},
	// 加购商品增删改查
	handleAdGoods(item,nums){
		let that = this;
		let cartId = that.isAddCart(item);
		if(cartId){
			console.log('在')
			// 在购物车
			let params = {
				id: cartId // 购物车ID
			};
			// 活动加购商品
			if(nums != 0){
				params.nums = nums;
				// 修改数量
				myPro.wxRequest("user/v3/carts/editnum","POST",params).then(res=>{
					that.closeAdGoodsSpec();
					that.getCartsList();
				}).catch(err=>{
					console.log('报错信息',err);
					wx.showToast({
						title: err,
						icon: "none"
					})
				})
			}else{
				// 删除
				myPro.wxRequest("user/v3/carts/remove","POST",params).then(res=>{
					that.closeAdGoodsSpec();
					that.getCartsList();
				}).catch(err=>{
					console.log('报错信息',err);
					wx.showToast({
						title: err,
						icon: "none"
					})
				})
			}
		}else{
			console.log('不在')
			let params = {
				good_id: item.good_id,
				good_specs_id: item.good_specs_id,
				nums: nums,
				add_good_rule_id: item.add_good_rule_id,
				is_add: 1 // 是否为加购商品（1是 0否）
			};
			// console.log('参数',params);
			// return;
			myPro.wxRequest("user/v3/carts/create","POST",params).then(res=>{
				that.closeAdGoodsSpec();
				that.getCartsList();
			}).catch(err=>{
				console.log('报错信息',err);
				wx.showToast({
					title: err,
					icon: "none"
				})
			});
		}
	},
	// 核实商品是否存在于购物车
	isAddCart(item){
		let that = this;
		let oldCartGoods = that.data.cartGoods;
		let cartId = null;
		// console.log('item',item);
		// console.log('购物车',oldCartGoods);
		// 检测购物车是否有此商品
		for(let i in oldCartGoods){
			if(item.good_id == oldCartGoods[i].good_id && oldCartGoods[i].add_good_rule_id && item.add_good_rule_id && item.good_specs_id == oldCartGoods[i].good_specs_id){
				cartId = oldCartGoods[i].id;
				break;
			}
		};
		return cartId;
	},
});
