<template>
	<div class="module-item-goods" :style="!module.base.m ? 'margin-top:0' : ''" v-if="goodsList.length>0">
		<div class="item-goods-con" :style="style">
			<moduleBg :base="module.base" />
			<moduleTwtit :type="module.type" :title="module.title" v-if="module.title.s" />
			<div class="item-goods-style1" :class="module.base.s == 1 ? 'style2' : ''">
				<div class="item" v-for="(item, index) in goodsList" :key="index">
					<div class="pic"  @click="$util.openGoods(module.list,index)">
						<image :src="url+item.cm.thumb"  />
						<template v-if="module.base.sth">
							<span v-if="item.cm.isPreferential === 1 && item.cm.type === 1">特惠</span>
							<span v-if="item.cm.isBuyGive === 1 && item.cm.type === 1">买赠</span>
						</template>
					</div>
					<div class="c">
						<div class="tit" v-if="module.base.t.s">
							<moduleText :text="module.base.t" :type="module.type" :name="item.cm.name" /></div>
						<div class="price" v-if="module.base.sjg || module.base.sgm">
							
							<template v-if="module.base.sjg">
								<span>
									<b>￥{{ item.cm.price }}</b>
								</span>
								<span v-if="item.cm.type == 2">
									<b>{{ item.cm.priceDescribe }}</b>
								</span>
							</template>
							
							<block v-if="systemInfo.set.is_cart==1">
								<view v-if="module.base.sgm && item.cm.stock > 0">
										<view class="flex flex-x-end flex-y-center">
											<view class="spec-btn"
												v-if="item.cm.is_gg == 2" @click="showSpec(item.cm.id)">
												选规格<view class="spec-num flex-center" v-if="item.cm.num>0">{{item.cm.num}}</view>
											</view>
											
											<view class="goods-num-block flex flex-x-end flex-y-center" v-else
												:style="{color:setColor}">
												<view class="car-goods iconfont icon-jian1"
													@click="changeNum(item.cm.category_id,item.cm.id,1,'goods','',item.cm.price,item.cm.many_rebate,item.cm.is_rebate)"
													v-if="item.cm.num>0"></view>
												<view class="num" v-if="item.cm.num>0">{{item.cm.num}}</view>
												<view class="car-goods iconfont icon-jia1 gdsf"
													@click="changeNum(item.cm.category_id,item.cm.id,2,'goods','',item.cm.price,item.cm.many_rebate,item.cm.is_rebate)">
												</view>
											</view>
										</view>
										
										<view class="flex-y-center">
											<view class="price" v-if="item.cm.is_rebate==1 && item.cm.rebate">
												<view class="rebate-border">
													{{item.cm.rebate}}
												</view>
											</view>
			
											<view class="ft24 many_rebate" v-if="item.cm.many_rebate>0 && item.cm.is_rebate==1">
												{{item.cm.many_rebate}}{{item.cm.unit}}起购
											</view>
										</view>
								</view>
							</block>
							
							<block v-else>
								<view @click="$util.openGoods(module.list,index)" class="car-goods iconfont icon-gouwuche2" v-if="module.base.sgm && item.cm.stock > 0"></view>
							</block>
							
						</div>
					</div>
				</div>
			</div>
		</div>
		
         <block v-if="systemInfo.set.is_cart==1">
	     	<shopping-car :carNum="carNum" :isDistance="is_distance" :navBtn="false" 
					:deliveryPrice="delivery_price" :carTotal="carTotal" :carGoods="carGoods" :userInfo="userInfo"
					 @choosebag="choosebag" :checked="pocket"/>
		</block>
		
		<view class="mask flex flex-column flex-nowarp flex-x-center flex-y-center" v-show="maskPop">
			<!-- 规格弹窗 -->
			<block v-if="specPop">
				<view class="pop-block spec-pop">
					<view class="title">{{goodsDetail.name}}</view>
					<scroll-view scroll-y="true" class="content-block">
						<view class="content">
							<block v-for="(item,index) in goodsDetail.edit_value" :key="index">
								<view class="spec-cat-title">
									<text>{{item.spec_name}}</text>
									<text style="font-size:24rpx;color:#aaa">（仅单选）</text>
								</view>
								<view class="spec-list flex">
									<view v-for="(spec,specIndex) in item.spec" :key="specIndex"
										@click="chooseSpec(index,specIndex)"
										:class="['spec-item',spec.active?'active':'']"
										:style="[spec.active?{'background-color':setColor,'border-color':setColor}:'']">
										{{spec.name}}
										<block v-if="spec.price">￥{{spec.price}}</block>
									</view>
								</view>
							</block>
						</view>
					</scroll-view>
					<view class="btm-block flex flex-y-baseline flex-nowarp">
						<view class="flex flex-nowarp flex-y-baseline">
							<view class="price">￥{{goodsDetail.spec_price}}</view>
							<view class="unit">/{{goodsDetail.unit}}</view>
						</view>
						<view class="choose-spec-list text-3" v-if="goodsDetail.specName">
							({{goodsDetail.specName}})</view>
						<block>
							<view class="add-car-btn" :style="{'background-color':setColor}"
								v-if="goodsDetail.num == 0"
								@click="changeNum(goodsDetail.category_id,goodsDetail.id,2,'spec',goodsDetail.many_rebate,goodsDetail.is_rebate)">
								加入购物车</view>
							<view class="goods-num-block flex flex-x-end flex-y-center" v-else
								:style="{color:setColor}">
								<view class="num-btn num-btn-1 iconfont icon-jian1"
									@click="changeNum(goodsDetail.category_id,goodsDetail.id,1,'spec',goodsDetail.many_rebate,goodsDetail.is_rebate)">
								</view>
								<view class="num">{{goodsDetail.num}}</view>
								<view class="num-btn num-btn-2 iconfont icon-jia1"
									@click="changeNum(goodsDetail.category_id,goodsDetail.id,2,'spec',goodsDetail.many_rebate,goodsDetail.is_rebate)">
								</view>
							</view>
						</block>
					</view>
				</view>
				<image src="/static/icon_5.png" mode="aspectFit" class="spec-close-btn" @click="showSpec"></image>
			</block>
		</view>
			
	</div>
</template>
<script>
import moduleBg from './bg.vue';
import moduleText from './text.vue';
import moduleTwtit from './twtit.vue';
// import SelectGoods from '@/views/attr/selectGoods.vue';
import shoppingCar from '@/components/shoppingCar.vue';
import { mapState } from 'vuex';
export default {
	props: ['module'],
	components: { moduleBg, moduleText,moduleTwtit,shoppingCar},
	data() {
		return {
			goodsList:this.module.list,
			 showSelectGoods:false,
			 url:getApp().globalData.URL,
			carGoods: [], //购物车商品
			carTotal:0,
			is_distance:0,
			delivery_price:0,
			carNum:0,
			specPop: false,
			maskPop:false,
			goodsDetail:null,
			pocket:1
		};
	},

	computed: {
		...mapState(['systemInfo', 'store_id', 'userInfo', 'setColor','table_id','vx_carGoods','teen_index', 'address',]),
		style() {
			if (this.module.base.fc != '') {
				return `color:${this.module.base.fc}`;
			}
		},
		dateRanges() {
			const {
				store_id,
				userInfo,
			} = this;
			return {
				store_id,
				userInfo,
			}
		},
	},
	
    watch:{	
		vx_carGoods(nVal){
			
			console.log(nVal,"goods")
			
			if (nVal) {
				this.getCarList();
				this.getDeliveryPrice();
			}
		},
      // 弹窗校检
      dateRange: {
      	handler(val) {
			this.getCarList();
		  }
	   }
	},
	
	mounted() {
		if(this.userInfo && this.store_id ){
			this.getCarList();
		}
	},
	
	methods: {
		choosebag(index) {
			this.pocket = index;
		},
		
		// 获取配送费
		getDeliveryPrice() {
			this.$http.request('xcx/getDeliveryPrice', {
				lat: this.address.lat || '',
				lng: this.address.lng || '',
				store_id: this.store_id,
			}, "", "", true).then(res => {
		
				let distance = Number(res.data.distance);
				if (distance) {
					if (!distance) {
						this.is_distance = 2;
						return
					}
					this.delivery_price = Number(res.data.delivery_price);
					if (!this.systemInfo.set.number || !distance) {
						this.is_distance = 1;
						return
					}
					// 如果大于商家距离is_distance = 2 提出超出距离
					if (distance > this.systemInfo.set.number) {
						this.is_distance = 2;
					} else {
						this.is_distance = 1;
					}
				} else {
					this.is_distance = 3;
				}
			}).catch(err => {})
		},
		
		/**
			 * 改变商品数量
			 * @category_id:分类id
			 * @goods_id:商品id
			 * @type:1减少 2增加
			 * @data_from 购物车列表传 'car' 规格弹窗传 'spec' 无规格传 'goods' 否则不传
			 * @car_index 购物车下标 data_form = 'car'传
			 * @goods_price 商品价格 data_from = 'goods' 传
			 * */
		changeNum(category_id, goods_id, type, data_from, car_index, goods_price, many_rebate = '', is_rebate = '',
				idx = '') {
				/* pocket 购物口袋
				  goodsList 数据列表
				  idx 如果是有从购物车加入 */
				let money = 0,
					pocket = this.pocket,
					carGoods,
					num = 0,
					spec = '',
					new_list = this.new_list,
					carItem = false;
				carGoods = this.carGoods;
				pocket = idx === '' ? pocket : idx;
				if (type == 2) {
					for (let i of new_list) {
						if (i.pocket == pocket) {
							carGoods = i.list;
						}
					}
				}
				
				if (type == 1) {
					function getData(new_list,pocket,goods_id) {
	                    let as = false
						for (let i of new_list) {
							for(let j of i.list){	
								if (i.pocket == pocket && j.goods_id == goods_id) {
									  as = true
								}
							}
						}
						return as	
					}
					// 判断当前选中的购物口袋是否选中并且还有产品
					let isAllStudentType = getData(new_list,pocket,goods_id)
					if (isAllStudentType) {
						for (let i of new_list) {
						  if (i.pocket == pocket) {
						        carGoods = i.list;
						   }
						}
					} else {
						for (let i of new_list) {
							for (let j of i.list) {
								if (j.goods_id == goods_id) {
									pocket = i.pocket
									carGoods = i.list
								}
							}
						}
					}
				}
				if (data_from == 'car') {
					//购物车规格
					carItem = carGoods[car_index]
					spec = carItem.spec || ''
					money = carItem.price
				} else if (data_from == 'spec') {
					let specArr = []
					let specList = this.goodsDetail.edit_value
					for (let i in specList) {
						for (let j in specList[i].spec)
							if (specList[i].spec[j].active) {
								specArr.push(specList[i].spec_name + ':' + specList[i].spec[j].name)
								break
							}
					}
					if (specArr.length != specList.length) {
						uni.showToast({
							title: "请选择规格",
							icon: 'none'
						})
						return false
					} else {
						spec = specArr.join(',')
						money = this.goodsDetail.spec_price
					}
				} else if (data_from == 'goods') {
					//无规格商品
					spec = ''
					money = goods_price
				}
				if (data_from != 'car') {
					for (let i in carGoods) {
						if (carGoods[i].goods_id == goods_id && carGoods[i].spec == spec) {
							carItem = carGoods[i]
							break
						}
					}
				}
				num = carItem ? carItem.num : 0
				if (type == 1) {
					if (num > 0) {
						// 起购
						if (many_rebate > 0 && is_rebate == 1) {
							if (many_rebate >= num) {
								num = num - many_rebate;
							} else {
								num--;
							}
						} else {
							num--
						}
					} else {
						return false
					}
				} else if (type == 2) {
					// 起购
					if (many_rebate > 0 && is_rebate == 1) {
						if (many_rebate <= num) {
							num++
						} else {
							num = num + many_rebate;
						}
					} else {
						num++
					}
				} else {
					return false
				}

				let datas = {
					user_id: this.userInfo.id,
					category_id: category_id, //分类id
					goods_id: goods_id, //是	string	商品id
					num: num <= 0 ? 0 : num, //是	string	购买数量
					table_id: this.table_id, //是	string	桌号
					spec: spec, //是	string	规格（json），有的传
					money: money,
					group: this.table_id,
					type: 'add_cart',
					store_id: this.store_id,
					pocket: pocket
				}
				if (this.systemInfo.is_qian_many == 1 && app.globalData.readyReset == 1) {
					app.sendSocketMessage(JSON.stringify(datas)).then(res => {
						this.number = num;
					})
				} else {
					this.$http.request('xcx/add_cart', datas, 'POST', false, true).then(res => {
						if (res.data.list.length == 0 && data_from == 'car') {
							this.pocket =1
							this.maskPop = false
							this.carGoodsPop = false
						}
						let arr = this.$utils.removal(res.data.list)
						this.new_list = res.data.new_list;
						this.computGoodsNum(arr, res.data.total_price, num, res.data.new_list)
					}).catch(err => {})
				}
			},
			//获取购物车数据
			getCarList() {
				var url = 'xcx/cart_list',
					datas;
			        datas = {
						user_id: this.userInfo.id,
						store_id: this.store_id,
				   }
				this.$http.request(url, datas, "", "", true).then(res => {
					if(res.data.list<=0){
						this.pocket = 1
					}
					let arr = this.$utils.removal(res.data.list)
					this.new_list = res.data.new_list;
					this.computGoodsNum(arr, res.data.total_price, 0, res.data.new_list)
					this.isloading = false;
				}).catch(err => {})
			},

			//根据购物车列表计算购物车数据
			computGoodsNum(list, total_price, spec_num, new_list = []) {

					if (this.goodsList.length <= 0) {
						return
					}
					let num = 0
					//计算商品数量
					let goodsList = this.goodsList;
					for (let i in goodsList) {
						goodsList[i].cm.num = 0
					}
					for (let i in list) {
						num += list[i].num
						for (let j in goodsList) {
							if (list[i].goods_id == goodsList[j].cm.id) {
								goodsList[j].cm.num += list[i].num
								break
							}
						}
					}
					this.goodsList = goodsList
					this.carNum = num
					this.carGoods = new_list
					this.carTotal = total_price
					if (this.detailPop || this.specPop) {
						this.goodsDetail.num = spec_num
					}
			
			},

			//清空购物车
			clearCar() {
				console.log("clearCar")
				this.pocket = 1
				this.new_list = []
				this.carGoods = []
				this.$store.commit('SET_CARGOODS', []) //监听购物车是否有变化
				this.carNum = 0
				this.carTotal = 0
				this.maskPop = false
				this.carGoodsPop = false
				let goodsList = this.goodsList
				for (let i in goodsList) {
					goodsList[i].cm.num = 0
				}
				this.goodsList = goodsList
			},

			//显示规格弹窗
			showSpec(goods_id) {
				if (this.specPop) {
					this.maskPop = false
					this.specPop = false
					return false
				}
				this.$http.request('xcx/goodinfo', {
					goods_id: goods_id
				}, "", "", true).then(res => {
					let info = res.data.goods
					let edit_value = info.edit_value
					for (let i in edit_value) {
						for (let j in edit_value[i].spec) {
							edit_value[i].spec[j] = {
								'name': edit_value[i].spec[j],
								active: false
							}
						}
					}
					info.edit_value = edit_value
					info.spec_price = info.price
					info.num = 0
					info.specName = ""
					this.goodsDetail = info
					this.maskPop = true
					this.specPop = true
				}).catch(err => {})
			},
			
			//选择规格
			chooseSpec(index, specIndex) {
				let spec = this.goodsDetail.edit_value[index].spec
				for (let i in spec) {
					if (i == specIndex) {
						spec[i].active = true
					} else {
						spec[i].active = false
					}
				}
				this.goodsDetail.edit_value[index].spec = spec
				this.goodsDetail.num = 0
				this.computSpecPrice()
			},
			//计算规格价格
			computSpecPrice() {
				let edit_value = this.goodsDetail.edit_value
				let specNameArr = [],
					carSpecArr = []
				for (let i in edit_value) {
					for (let j in edit_value[i].spec) {
						if (edit_value[i].spec[j].active) {
							specNameArr.push(edit_value[i].spec[j].name)
							carSpecArr.push(edit_value[i].spec_name + ':' + edit_value[i].spec[j].name)
							break
						}
					}
				}
				let specName = specNameArr.join(":")
				this.goodsDetail.specName = specNameArr.join(',')
				let spec = this.goodsDetail.spec
				for (let i in spec) {
					if (spec[i].spec == specName) {
						this.goodsDetail.spec_price = this.userInfo.is_vip == 1 ? spec[i].growth : spec[i].growth
						break
					}
				}
				let carGoods = this.carGoods
				carSpecArr = carSpecArr.join(",")
				for (let i in carGoods) {
					if (this.goodsDetail.id == carGoods[i].goods_id && carSpecArr == carGoods[i].spec) {
						this.goodsDetail.num = carGoods[i].num
						break
					}
				}
			},
	}
};
</script>

<style>
	@import url("./goods.css");
	.many_rebate {
		color: red;
		text-align: right;
	}
	
	.textDecoration {
		text-decoration: line-through;
		color: #999999;
		font-size: 20rpx;
	}
	
</style>
