<template>
	<view>
		<uni-nav-bar :fixed="true" title="咖啡屋" left-icon="left" backgroundColor="rgb(0,0,0,0)" :border="false" @clickLeft="onHome"/>
		<!-- 详情弹窗 -->
		<view class=" detail-pop">
			<!-- <image src="../../static/icon_5.png" mode="aspectFit" class="detail-close-btn"
				@click="showGoodsDetail"></image>-->
			<!-- <scroll-view scroll-y="true" class="content-block"> -->
			<image :src="URL+goodsDetail.thumb" mode="aspectFill" class="goods-img"></image>
			<!-- <view class="" style="padding: 0 10rpx;">
					<rich-text :nodes="goodsDetail.description"></rich-text>
				</view> -->
			<!-- </scroll-view> -->
			<view class="btm-block">
				<!-- <view class="goods-name ft28" style="font-size: 34rpx;">{{goodsDetail.name}}</view> -->
				<view class="flex  box-pack-between">
					<view class="goods-name ft28" style="font-size: 34rpx;flex: 1;">{{goodsDetail.name}}</view>
					<view class="sales ft26 flex-center">已售：{{goodsDetail.fictitious?goodsDetail.fictitious:0}}</view>
				</view>
				<view class="goods-desc">{{goodsDetail.desc}}</view>
				<view class="flex flex-y-center flex-nowarp box-pack-between">
					<view class="">
						<view class="flex flex-nowarp flex-y-baseline">
							<view class="price">￥{{goodsDetail.price}}</view>
							<view class="unit">/{{goodsDetail.unit}}</view>
						</view>
						<view class="price" v-if="goodsDetail.is_rebate==1">
							<view class="rebate-border">
								{{goodsDetail.rebate}}
							</view>
						</view>
					</view>
					<view>
						<view class="add-car-btn" :style="{'background-color':setColor}" v-if="goodsDetail.is_gg == 2"
							@click="showSpec(goodsDetail.id)">选规格</view>
						<view class="add-car-btn" :data-i='goodsDetail.num' :style="{'background-color':setColor}"
							v-else-if="goodsDetail.num == 0"
							@click="changeNum(goodsDetail.category_id,goodsDetail.id,2,'goods','',goodsDetail.price,goodsDetail.many_rebate,goodsDetail.is_rebate)">
							加入购物车
						</view>
						<block v-else>
							<view class="goods-num-block flex flex-x-end flex-y-center" :style="{color:setColor}">
								<view class="num-btn num-btn-1 iconfont icon-jian1"
									@click="changeNum(goodsDetail.category_id,goodsDetail.id,1,'goods','',goodsDetail.price,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,'goods','',goodsDetail.price,goodsDetail.many_rebate,goodsDetail.is_rebate)">
								</view>
							</view>
							<view class="ft24 many_rebate" v-if="goodsDetail.many_rebate>0 && goodsDetail.is_rebate==1">
								{{goodsDetail.many_rebate}}{{goodsDetail.unit}}起购
							</view>
						</block>
					</view>
				</view>
			</view>

			<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>

			<shopping-car :carNum="carNum" :isDistance="is_distance" :navBtn="true" :deliveryPrice="delivery_price"
				:carTotal="carTotal" :carGoods="carGoods" :userInfo="userInfo" @choosebag="choosebag" :checked="pocket"/>


			<view class="detail-title">
				-- 商品详情 --
			</view>

			<view class="detail-content">
				<mp-html :content="description" />
				<!-- <rich-text :nodes="description"></rich-text> -->
			</view>
			<view class="hg100">
			</view>
		</view>

		<!-- #ifdef MP-WEIXIN -->
		<view v-if="goodsDetail.feedid || goodsDetail.finder" class="flex-row flex-y-center share_commission"
			@click="openVideo">
			<image src="/static/wx_video.png"></image>
		</view>
		<!-- #endif -->

	</view>
</template>
<script>
	import mpHtml from '@/uni_modules/mp-html/components/mp-html/mp-html'
	let hideLoading = false;
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import shoppingCar from '@/components/shoppingCar.vue';
	export default {
		components: {
			shoppingCar
		},
		data() {
			return {
				carGoods: [], //购物车商品
				carNum: 0, //购物车数量
				carTotal: 0, //购物车价格
				goodsDetail: {}, //详情数据
				URL: getApp().globalData.URL,
				description: '', //文本
				maskPop: false,
				specPop: false,
				goodsList: [],
				goods_id: '',
				is_distance: null,
				delivery_price: 0,
				pocket: 1,
				list: []
			}
		},

		onLoad(e) {
			console.log(e, "eeee")
			this.goods_id = e.id;
			if (e.userInfo & e.store_id & e.setColor & e.systemInfo) {
				this.userInfo = e.userInfo;
				this.store_id = e.store_id;
				this.setColor = e.setColor;
				this.systemInfo = e.systemInfo;
				this.$store.commit('SET_STORE_ID', e.store_id)
				// this.$store.commit('SET_TEEN_INDEX', 1)
				//重置默认
				this.$store.commit('SET_TABLE_ID', "")
				this.$store.commit('SET_CATE_ID', '')
				this.$store.dispatch('getSystemStup', e.store_id);
				this.$store.dispatch('getOpenid', e.store_id);
				this.$store.dispatch('SET_USER_INFO', e.userInfo);
				this.$store.dispatch('SET_MONITOR_COLOR', e.setColor);
				this.$store.dispatch('SET_SYSTEM', e.systemInfo);
			}

			this.goodInfo();


			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.setColor,
			})
		},
		onShow() {
			this.getDeliveryPrice();
		},

		onShareAppMessage(e) {
			return {
				title: this.goodsDetail.name,
				path: 'menber/goods_detail?id=' + this.goodsDetail.id,
				imageUrl: this.URL + this.goodsDetail.thumb,
			}
		},

		onShareTimeline() {
			return {
				title: this.goodsDetail.name,
				query: `id=${this.goodsDetail.id}&setColor=${this.setColor}&store_id=${this.store_id}&userInfo=${this.userInfo}&systemInfo=${this.systemInfo}`,
				imageUrl: this.URL + this.goodsDetail.thumb,
			}
		},

		computed: {
			...mapState(['systemInfo', 'setColor', 'store_id', 'userInfo', 'address'])
		},

		watch: {
			setColor(nVal) {
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: nVal,
				})
			},
			address(val) {
				this.getDeliveryPrice();
			}
		},

		methods: {
			choosebag(index) {
				this.pocket = index;
			},
           onHome(e){
           	uni.switchTab({
           		url:'/pages/home/home'
           	})
           },
			// 获取配送费
			getDeliveryPrice() {
				this.$http.request('xcx/getDeliveryPrice', {
					lat: this.address.lat || '',
					lng: this.address.lng || '',
					store_id: this.store_id,
				}, "", "", hideLoading).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 => {})
			},

			openVideo() {
				let goods = this.goodsDetail;
				if (goods.feedid && goods.finder) {
					wx.openChannelsActivity({
						finderUserName: goods.finder,
						feedId: goods.feedid,
						success: () => {
							console.log("打开成功")
						}
					})
				} else {
					wx.openChannelsUserProfile({
						finderUserName: goods.finder,
						success: () => {
							console.log("打开成功")
						}
					})
				}
			},
			//清空购物车
			clearCar() {
				this.pocket=1
				this.goodsDetail.num =0 
				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].num = 0
					for (let j in goodsList[i].goods_list) {
						goodsList[i].goods_list[j].num = 0
					}
				}
				this.goodsList = goodsList
				
			},

			showSpec() {
				if (this.specPop) {
					this.maskPop = false
					this.specPop = false
					return false
				}
				this.maskPop = true
				this.specPop = true
			},

			goodInfo() {
				this.$http.request('xcx/goodinfo', {
					goods_id: this.goods_id,
				}, "", "", hideLoading).then(res => {
					let info = res.data.goods;
					if (res.data.goods.description) {
						this.description = res.data.goods.description.replace(/\<img/gi,
							'<img style="max-width:100%;height:auto" ');
					}
					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.category_id = info.category_id
					this.goodsDetail = info;
					this.getCarList();
					console.log(info, "infoinfoinfoinfo")
				}).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
				// 	}
				// }
			},
			
			//获取购物车数据
			getCarList() {
				this.$http.request('xcx/cart_list', {
					user_id: this.userInfo.id,
				}, "", "", hideLoading).then(res => {
					if(res.data.list<=0){
						this.pocket=1
					}
					let arr = this.$utils.removal(res.data.list),
						num = 0;
					// this.list = arr;
					this.computGoodsNum(arr, res.data.total_price, num, res.data.new_list);

				}).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 = '') {
				console.log(many_rebate, is_rebate)
				let money = 0,
					pocket = this.pocket,
					num = 0,
					spec = '',
					carItem = false,
					new_list = this.carGoods,
					carGoods = this.carGoods;

				// carGoods = ? this.list : 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
								}
							}
						}
					}
				}

				console.log(carGoods, "carGoods")

				if (data_from == 'car') {
					//购物车规格
					carItem = carGoods[car_index]
					spec = carItem.spec || ''
					money = carItem.price
					// console.log(money, "money")
				} 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
				}
				this.$http.request('xcx/add_cart', {
					user_id: this.userInfo.id, //是	string	用户id
					category_id: category_id, //分类id
					goods_id: goods_id, //是	string	商品id
					num: num, //是	string	购买数量
					table_id: this.systemInfo.table_id, //是	string	桌号
					spec: spec, //是	string	规格（json），有的传
					money: money,
					pocket,
				}, 'POST', false, true).then(res => {
					// console.log(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.computGoodsNum(arr, res.data.total_price, num, res.data.new_list)

				}).catch(err => {})
			},

			//根据购物车列表计算购物车数据
			computGoodsNum(list, total_price, spec_nums, new_list) {
				let num = 0,
					spec_num = 0;
				//计算商品数量

				for (let i in list) {
					num += list[i].num
				}

				this.carNum = num
				this.carGoods = new_list
				this.list = list;

				this.$store.commit('SET_CARGOODS', list) //监听购物车是否有变化
				this.carTotal = total_price

				// if (this.detailPop || this.specPop) {
				for (let i of list) {
					if (i.goods_id == this.goodsDetail.id) {
						spec_num = i.num
					}
				}
				this.goodsDetail.num = spec_num || 0
				// }
			},
		},
	}
</script>

<style>
	@import url("../pages/index/index.css");

	.sales {
		font-size: 9pt;
		color: #999;
		padding-left: 20rpx;
		min-width: 100rpx;
	}

	.share_commission {
		position: absolute;
		right: 0;
		top: 450rpx;
		border-top-left-radius: 40rpx;
		border-bottom-left-radius: 40rpx;
	}

	.share_commission image {
		width: 100rpx;
		height: 126rpx;
		margin-right: 14rpx;
		margin-left: 20rpx;
	}

	.detail-pop {
		width: 100%;
	}

	.detail-pop .goods-img {
		width: 100%;
	}

	.detail-pop .btm-block {
		background-color: #FFFFFF;
		margin-bottom: 20rpx;
	}

	.detail-pop .detail-title {
		height: 100rpx;
		text-align: center;
		background-color: #FFFFFF;
		line-height: 100rpx;
		border-bottom: 1rpx solid #f1f1f1;
	}

	.detail-pop .detail-content {
		background-color: #FFFFFF;
	}

	.hg100 {
		height: 100rpx;
	}

	.many_rebate {
		margin-top: 20rpx;
	}
</style>
