<template>
	<view class="shop-car">
	  <!-- 辅助进货 -->
	  <view v-if="isPurchase" @click="goPurchase" ref="wwww">
		<left-right-cell>
		  <text style="color: #6bb82d" slot="left">辅助进货</text>
		  <span slot="right"></span>
		</left-right-cell>
	  </view>
	  <!-- 没有商品 -->
	  <view class="no-shopcar" v-if="!carCount">
		<list-none img="img-noShopCar" msg="购物车中没有商品哦"></list-none>
		<text @click="goGoods" class="btn-toGoods">去购物</text>
	  </view>
	  <!-- 商品 -->
	  <view v-else>
		<view class="goods-content">
			<car-group 
				ref="carGrounp" 
				v-for="(val, key) in shopCarByGroup" 
				:key="key" 
				:storeID="key" 
				:skuNames="val" 
				@handleSkuNamePlus="handleSkuNamePlus" 
				@handleSkuNameMinus="handleSkuNameMinus" 
				@handleSkuNameCheck="handleSkuNameCheck" 
				@handleSkuNameChange="handleSkuNameChange"
			>
			</car-group>
		</view>
	  </view>

	  <!-- 推荐商品 -->
	  <!-- <div v-if="!isMaterial" class="recommend" >
		<div class="recommend-top" :style="sizeStyle">
		  <div class="recommend-line">------------</div>
		  <div class="recommend-icon">
			<div class="recommend-img">
				<img src="https://image.jxc4.com/image/3a71aa1d0bf559abd803643905935485.png" alt="" :style="imgStyle"/>
			</div>
			<div style="margin-left:10rpx;">为您推荐</div>
		  </div>
		  <div class="recommend-line">------------</div>
		</div> -->

		<!-- 瀑布流 -->
		<!-- <waterfall 
			:value="newTopGood" 
			:imageKey="'img'"
			@clickPlus="skuNamePlusRecommend"
			@clickMinus="skuNameMinusRecommend"
			@countChange="skuNameChangeRecommend"
		>
		</waterfall> -->
		<!-- <div class="good">
			<div
			  class="good-item"
			  v-for="(skuName, index) in newTopGood"
			  :key="index"
			  @click.stop="toGoodDetail(skuName.id,skuName.storeID)"
			>
			  <good-cell-big
				:skuName="skuName"
				:index="index"
				@handleSkuNamePlus="skuNamePlusRecommend"
				@handleSkuNameMinus="skuNameMinusRecommend"
				@handleSkuNameChange="skuNameChangeRecommend"
				
			  ></good-cell-big>
			</div>
		</div> -->
	  <!-- </div> -->
	  <!-- <div style="height: 188rpx;" v-if="JSON.stringify(shopCarByGroup) !== '{}'"></div> -->
	  <!-- 底部菜单 -->
	  <view class="shop-car-bottom-bar" v-if="carCount">
		<text class="waybillSLG" v-if="!(waybillSLG.satisfy) && waybillSLG.reduce">免运费￥{{waybillSLG.reduce}}元</text>
		<text class="waybillSLG" v-if="waybillSLG.satisfy && waybillSLG.reduce">商品满￥{{ waybillSLG.satisfy }}减￥{{waybillSLG.reduce}}运费</text>
		
		<!-- #ifdef MP-WEIXIN -->
		<MaterialInfo v-if="isMaterial && !isPurchase"></MaterialInfo>
		<!-- #endif -->
		
		<view class="all-pick" v-if="!isMaterial">
		  <view class="btn-all-pick">
			<check-item @on-click="allCheck" :checked="allChecked" text="全选" :width="40" :height="40" :fontSize="30"></check-item>
		  </view>
		  <text class="pick-count">已选 {{ carCheckedCount }} 件</text>
		</view>
		<view class="total">
		  <view class="btn-clear-shopCar" @click="handleClearAll">
			<span class="icon-delete"></span>
			<text class="icon-text">清空购物车</text>
		  </view>
		  <view class="price">
			<view v-if="!isMaterial && totalPrice">
			  <view class="total-price">
				<span class="total-text">合计:</span>
				<good-price :price="totalPrice"></good-price>
			  </view>
			</view>
			<view :class="{
				'btn-payment': true,
				'btn-disabled':!storeOpen || (!canBuy && storeID[0] ===666666),
			  }" @click="goSettlement">
			  <view>
				<span v-if="!canBuy && storeID[0] ===666666">无法申请</span>
				<span v-else-if="!storeOpen">门店休息中</span>
				<span v-else>提交订单</span>
			  </view>
			</view>
		  </view>
		</view>
	  </view>

	  <!-- loading -->
	  <zy-loading></zy-loading>
	</view>
  </template>
  
  <script>
  import reComputedCarCount from "@/mixins/reComputedCarCount.js";
  import { modal,errToast, toast,jumpPage,queryEleInfo,setTabBarBadge } from "@/utils/uniapi.js";
  import ZyLoading from "@/components/Loading/loading";
//   import CarGroup from "@/componentst/car-group/car-group.vue";
  import { mapGetters, mapActions } from "vuex";
  import ListNone from "@/components/commonCmp/list-none.vue";
  import CheckItem from "@/components/checkItem/check-item.vue";
  import { msgData } from "@/config.js";
  import goodCellBig from "@/components/goodCmp/good-cell-index/good-cell-big.vue"; 
  
  // #ifdef MP-WEIXIN
  import MaterialInfo from "@/components/material-info/index.vue";
  // #endif
  
  import LeftRightCell from "@/components/layout/left-right-cell.vue";
  import GoodPrice from '@/components/goodCmp/good-price/good-price';

  import PlusMinus from "@/components/goodCmp/plus-minus/plus-minus";
  import apiStore from '@/apis/apiStore';
//   import waterfall from '@/components/waterfall/index.vue'
  import {store} from "@/store";

  export default {
	name: "ShopCar",
	mixins: [reComputedCarCount],
	components: {
		ZyLoading,
		// CarGroup,
		ListNone,
		CheckItem,
		// #ifdef MP-WEIXIN
		MaterialInfo,
		// #endif
		LeftRightCell,
		GoodPrice,
		goodCellBig,
		PlusMinus,
		// waterfall
	},
	data() {
		return {
			shopCarByGroup: {},
			allChecked: false,
			storeOpen: true,
			vipArr: [],
			vipCount: 1,
			msg: "",
			imgStyle:'width:20px;height:20px',
			sizeStyle:'',
		};
	},
	async created() {
		// 这一串不知道是干嘛用的------------
		if(!this.isLogin) return 
  		this.vipArr = await apiStore.getConfigInfo('vip')
		if (this.selfInfo.userMembers) {
			for (let item of this.vipArr) {
			  if (num === item.id) {
				this.vipCount = Number(item.pricePercentage) / 100
			  }
			}
			console.log(this.vipCount);
			let num = this.selfInfo.userMembers[0].memberTypeID
		}
	},
	async onShow() {
		if(!this.isLogin) return 
		this.pageInit()
		if(this.carCount) setTabBarBadge('set',this.carCount)
	},
	computed: {
  		...mapGetters({
			selfInfo: "login/selfInfo",
			isLogin: "login/isLogin",
			storeID: "indexPage/storeID",
			storeMap: "indexPage/storeMap",
			isMaterial: "indexPage/isMaterial",
			fromStoreID: "indexPage/fromStoreID",
			notBuyPackbag: "indexPage/notBuyPackbag",
			newTopGood:'indexPage/topGoods',
			isPurchase: "indexPage/isPurchase",
			canBuy: "indexPage/canBuy",
  			waybillSLG: "indexPage/waybillSLG",
			materialInfo:"indexPage/materialInfo",
			validCarList: "cartPage/validCarList",
			totalPrice: "cartPage/totalPrice",
			carCount: "cartPage/carCount",
			cartList: "cartPage/cartList",
			carCheckedCount: "cartPage/carCheckedCount",
			cartNeedReload:"cartPage/cartNeedReload",
			addressList: "addressVue/addressList",
			confirmCheckShow: "confirmCheckShow",
			isShowShop: "isShowShop",
			isB2B:'indexPage/isB2B',
			iosOrAndroid: "iosOrAndroid",
			storeList:"indexPage/storeList"
		}),
	},
	watch: {
	  	carCheckedCount(val) {
			// console.log(val);
			if (val === this.carCount) {
			this.allChecked = true;
			} else {
			this.allChecked = false;
			}
  		},
		carCount: {
			handler(val) {
				if(val) setTabBarBadge('set',val)
			},
			immediate:true
		}
	},
	methods: {
  		...mapActions({
  			checkAllOrCancel: "cartPage/checkAllOrCancel",
  			clearAllShopCar: "cartPage/clearAllShopCar",
  			changeCar: "cartPage/changeCar",
			getCarListVuex:"cartPage/getCarList",
			
  		}),
		// 初始化页面
		async pageInit() {
			// console.log("onShow,购物车中，你调用了几次",this.carCount);
			try {
				this.showLoad()
				if (this.cartNeedReload) {
					this.refreshData()
  				}
				//  
				
				// 获取购物车
				this.shopCarByGroup = {}; // 先清空再设置
				if (this.isLogin) {
					// 获取门店状态
					await store.dispatch('indexPage/getStoreInfo', { storeID: this.storeID[0] })	// 获取当前门店的信息
					// if(this.isMaterial && !isPurchase)
					this.storeOpen = this.storeMap[this.storeID[0]].status === 1 ? true : false
					this.shopCarByGroup = await this.getCarList()
					// #ifdef APP-PLUS || APP
					// if (this.storeID && this.shopCarByGroup[this.storeID]) {
					// 	// this.shopCarByGroup[this.storeID].forEach(item => {
					// 	// 	// this.reIndexGoodData(item.id, item.count)
					// 	// })
					// }
					// #endif
  				}
			} catch (e) {
				console.error(e);
				errToast(e);
			} finally {
				this.hideLoad();
			}
		},
		// 获取购物车商品
		async getCarList() {
			try {
				let shopCar = this.cartList
				let json = {}
				shopCar.forEach(item => {
					let key = item.storeID
					if (key in json) {
						json[key].push(item)
					} else {
						json[key] = []
						json[key].push(item)
					}
				})
				if (this.carCheckedCount === this.carCount) {
					this.allChecked = true;
				} else {
					this.allChecked = false;
				}
				return json;
			} catch (e) {
  				throw e;
			}
		},
		// 跳转到商品详情页
		toGoodDetail(id,storeID) {
			jumpPage('navigateTo',`/pagesGoods/good-detail/index?skuID=${id}&storeID=${storeID}`)
		},
		// 商品 +
		async skuNamePlusRecommend(index,type) {
  			const skuName = type === 'cart' ? this.shopCarByGroup[this.storeID[0]][index] : this.newTopGood[index]
			await this.changeCar({
				skuName,
				count:skuName.count + 1
			})
			this.shopCarByGroup = await this.getCarList();
		},
		// 商品 -
  		async skuNameMinusRecommend(index, type) {
			let skuName = type === 'cart'?this.shopCarByGroup[this.storeID[0]][index]:this.newTopGood[index]
			await this.changeCar({
				skuName: skuName,
				count:skuName.count - 1,
			})
			this.shopCarByGroup = await this.getCarList()
		},


		// 商品change
		async skuNameChangeRecommend(count,index,type) {
			const skuName = type ==='cart'?this.shopCarByGroup[this.storeID[0]][index]:this.newTopGood[index];

			await this.changeCar({
				skuName: skuName,
				count,
			});
			this.shopCarByGroup = await this.getCarList()
		},


		//更新降价or 升价 重新获取`数据就行
		async refreshData() {
			await store.dispatch('indexPage/getTopGoods', this.storeID)
		},
		// 购物车商品相加
		async handleSkuNamePlus({ index, key }) {
			this.skuNamePlusRecommend(index,'cart')
		},
		handleSkuNameMinus({ index, key }) {
  			this.skuNameMinusRecommend(index, 'cart')
		},
		async handleSkuNameChange({ index, count, key }) {
			this.skuNameChangeRecommend(count,index,'cart')
		},
		// 勾选
		handleSkuNameCheck({ index, key, checkStatus }) {
			let skuName = this.shopCarByGroup[key][index];
			skuName.checked = checkStatus
		},
		// 跳转到商品页面
		goGoods() {
			uni.navigateTo({ url: "/pagesStore/store/index" })
		},
		// 全选
		async allCheck() {
			try {
			if (this.allChecked) {
				// 取消全选
				await this.checkAllOrCancel(false);
			} else {
				// 全选
				await this.checkAllOrCancel(true);
			}
			this.shopCarByGroup = await this.getCarList();
			} catch (e) {
			console.error(e);
			errToast(e);
			}
		},
		// 清空购物车
		async handleClearAll() {
			try {
				let res = await modal("温馨提示", msgData.clearAllShopCar);
				if (res) {
					await this.clearAllShopCar();
				}
			} catch (e) {
				console.error(e);
				errToast(e);
			}
		},
		// 去结算页面
		async goSettlement() {

			// #ifdef MP-WEIXIN
			if (this.isMaterial && this.materialInfo && this.materialInfo.fromStoreInfo.packageSwitch === 1) return toast(`非常抱歉,无法购买物料，请联系运营${this.materialInfo.fromStoreInfo.marketManPhone}`)
			// #endif
			
			if ((!this.storeOpen || !this.canBuy && this.storeID[0] ===666666)) {
				return false;
			}
			if (this.isLogin) {
				if (this.validCarList.length === 0) {
					toast(msgData.noCheckGoods);
					return false;
				}
				
				jumpPage('navigateTo','/pagesOrders/create-order/index')
			} else {
				toast('请登录')
				jumpPage('switchTab','/pages/mine/index')
			}
		},
		//到辅助进货页面
		goPurchase() {
			jumpPage('navigateTo','/pagesOrders/help-purchase/index')
		}
	},
	mounted() {
	  // 获取推荐分类在页面中的信息
	//   if (this.iosOrAndroid.platform === 'ios') {
	// 	this.imgStyle = `width:40px;height:40px`
	// 	this.sizeStyle = 'font-size:30px'
  	//   }	
	},
	// 下拉刷新
  	async onPullDownRefresh() {
		try {
  			this.storeOpen = this.storeMap[this.storeID[0]].status === 1 ? true : false
  			if (this.isLogin) {
				await this.getCarListVuex()
				this.shopCarByGroup = await this.getCarList()
			}
			
			if(this.carCount) setTabBarBadge('set',this.carCount)
  		} catch (e) {
			console.error(e);
			errToast(e);
  		} finally {
			uni.stopPullDownRefresh();
		}
  		
	},
	onHide() {
		store.commit('cartPage/cartNeedReload',false)	// 去掉重载标识
	},
  };
  </script>
  
  <style lang="scss" scoped>
  @import "./shop-car.scss";
  </style>