<template>
	<view>
		<!--pages/cart/cart.wxml-->
		<view class="page">
			<block v-for="(item, index) in pageList" :key="index">
				<!-- <view class="cart" wx:if="{{item.isTimely == 1 && item.list.length > 0}}">
			<view class="dian dflex">
				<image src="{{item.isActive ? '/pages/images/gou_h.png' : '/pages/images/gou.png'}}" class="check" data-index="{{index}}"
					bindtap="checkProduct"></image>
				<view class="flex">及时达</view>
			</view>
			<view class="list">
				<block wx:for="{{item.list}}" wx:key="index" wx:for-index="idx">
					<view class="li">
						<view class="checkbox" data-index="0" data-idx="{{idx}}" data-store="{{item.store}}"
							bindtap="checkProduct">
							<image src="{{item.isActive ? '/pages/images/gou_h.png' : '/pages/images/gou.png'}}" class="check">
							</image>
						</view>
						<view class="info dflex flex">
							<view class="cimgs" bindtap="toDetail" data-id="{{item.productId}}">
								<image src="{{item.pic}}" mode="aspectFit" class="cimg"></image>
								<image src="/pages/images/jishida.png" class="type"></image>
							</view>
							<view class="zhinfo">
								<view class="zhtit {{item.store <= 0|| item.isInvalid?'color999':''}}" bindtap="toDetail"
									data-id="{{item.productId}}">
									{{item.title}} {{item.store<=0?'已售罄':item.isInvalid?'已下架':''}}({{item.merchantName}}及时达)</view>
								<view wx:if="{{item.baseModelList}}" class="guigecontent">规格：
									<text wx:for="{{item.baseModelList}}" wx:for-item="itemGuige" class="guige"
										decode="{{true}}">{{itemGuige.value}}&nbsp;
									</text>
								</view>
								<view class="jiage">
									<view class="zhjia" bindtap="toDetail" data-id="{{item.productId}}"><text>￥</text>{{item.price}}
									</view>
									<view class="num">
										<view class="jian" bindtap="jianQuantity" data-index="{{0}}" data-idx="{{index}}">-</view>
										<text class="nums">{{item.quantity}}</text>
										<view class="jian" bindtap="jiaQuantity" data-index="{{0}}" data-idx="{{index}}">+</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</block>
			</view>
		</view> -->
				<!-- 普通产品 -->
				<view class="cart" v-if="item.list.length > 0">
					<view class="dian dflex">
						<image :src="item.isActive ? '/static/pages/images/gou_h.png' : '/static/pages/images/gou.png'"
							class="check" :data-merchantId="item.merchantId" :data-index="index" @tap="checkProduct">
						</image>
						<view class="flex dflex top" v-if="item.isTimely==0">
							<view class="merchantName">{{item.shopName?item.shopName:item.merchantName}}</view>
							<block v-if="!isEdit">
								<block v-if="about.Min_Order_Money&&item.merchantMoney>0">
									<view class="dflex">
										<view class="tbg">还差{{item.merchantMoney}}元下单</view>
										<!-- <navigator class="tbg dflex gocou" url="/pages/index/index" open-type="switchTab">去凑单<image src="/pages/images/more.png" class="more"></image></navigator> -->
										<view class=" dflex gocou" @tap="goindex">去凑单 <image
												src="/static/pages/images/more.png" class="more">
											</image>
										</view>
									</view>
								</block>
								<block v-else>
									<view class="dflex" v-if="about.Express_Fee>0">
										<view class="tbg" v-if="item.freeShipping >0">还差{{item.freeShipping }}元包邮</view>
										<view v-if="item.freeShipping >0" class=" dflex gocou" @tap="goindex">去凑单 <image
												src="/static/pages/images/more.png" class="more"></image>
										</view>
										<view v-else class="tbg">已免运费</view>
										<!-- <view>{{item.freeShipping }}</view> -->
									</view>
								</block>
							</block>
						</view>
						<view class="flex" v-if="item.isTimely==1">{{item.shopName?item.shopName:item.merchantName}}及时达
						</view>
					</view>
					<view class="list">
						<block v-for="(item, idx) in item.list" :key="idx">
							<view class="li">
								<view class="checkbox" :data-index="index" :data-idx="idx" :data-store="item.store"
									@tap="checkProduct">
									<image
										:src="item.isActive ? '/static/pages/images/gou_h.png' : '/static/pages/images/gou.png'"
										class="check">
									</image>
								</view>
								<view class="info dflex flex">
									<view class="cimgs" @tap="toDetail" :data-id="item.productId"
										:data-merchant="item.merchantId" :data-type="item.activityType" :data-actid="item.activityProductId">
										<image :src="item.pic+ '?x-oss-process=style/w160'" class="cimg"></image>
										<image src="/static/pages/images/jishida.png" class="type"
											v-if="item.isJs&&!item.activityType"></image>
										<image src="/static/pages/images/tuangou.png" class="type"
											v-if="item.activityType==1"></image>
										<image src="/static/pages/images/seckill.png" class="type"
											v-if="item.activityType==2"></image>
										<image src="/static/pages/images/newbornZone.png" class="type"
											v-if="item.activityType==4"></image>

										<view class="gys" v-if="item.store<=0">已售罄</view>
										<view class="gys" v-else-if="item.isInvalid">已下架</view>
										<view class="gys" v-else-if="item.activityState===1">活动进行中</view>
										<view class="gys" v-else-if="item.activityState===0">活动已结束</view>
										<!-- <view class="gys" wx:if="{{item.store<=0||item.isInvalid}}">{{item.store<=0?'已售罄':item.isInvalid?'已下架':''}}</view> -->
									</view>
									<view class="zhinfo">
										<view :class="'zhtit ' + (item.store <= 0|| item.isInvalid?'color999':'')"
											@tap="toDetail" :data-id="item.productId" :data-merchant="item.merchantId"
											:data-type="item.activityType" :data-actid="item.activityProductId">
											{{item.title}}
										</view>

										<view v-if="item.baseModelList" class="guigecontent">规格：
											<text v-for="(itemGuige,index) in item.baseModelList" class="guige"
												:decode="true" :key="index">{{itemGuige.value}}&nbsp;
											</text>
										</view>

										<view class="jiage"
											:style="item.baseModelList||item.activityState===0||item.store<=0||item.isInvalid?'margin-top: 14rpx;':''">
											<view class="zhjia" @tap="toDetail" :data-id="item.productId"
												:data-merchant="item.merchantId" :data-actid="item.activityProductId" v-if="!integralshop">
												<text>￥</text>{{item.price}}
											</view>
											<view class="integral" v-if="integralshop"><text
													class="intnum">{{item.integral}}积分</text><text
													class="money">+￥{{item.price}}</text></view>
											<view class="num">
												<view class="jian" @tap="jianQuantity" :data-index="index"
													:data-idx="idx">-</view>
												<input class="nums" :value="item.quantity" type="number" @input="getNum"
													@blur="minNum" :data-index="index" :data-idx="idx" />
												<view class="jian" @tap="jiaQuantity" :data-index="index"
													:data-idx="idx">+</view>
											</view>
										</view>
										<view class="tabe dflex"><text v-for="(it, index) in item.tabe"
												:key="index">{{it}}</text></view>
									</view>
								</view>
							</view>
						</block>
					</view>
				</view>
			</block>
		</view>
		<block v-if="ishow">
		<view class="nodata_cart">
			<image :src="picUrlss + 'null.png'"></image>
			<view>购物车是空的</view>
			<navigator :url="header.appId=='ZQ1VK5oc17I387E'?'/pages/timelyDelivery/index':'/pages/index/index'"
				open-type="switchTab">去逛逛</navigator>
		</view>
		</block>
		<view class="wei-login" v-if="!isLogin">
			<image :src="picUrlss + 'wei_login.png'"></image>
			<view>暂未登录</view>
			<navigator url="/pages/authorize/authorize" hover-class="none" class="cart-login">立即登录</navigator>
		</view>
		<view class="cai pdlr20" v-if="likeList.length>0">
			<view class="cai-tit dflex">
				<image src="/static/pages/images/cai_bg1.png"></image>猜您喜欢<image
					src="/static/pages/images/cai_bg2.png"></image>
			</view>
			<view class="tabcon dflex">
				<block v-for="(item, index) in likeList" :key="index">
					<view class="li">
						<view class="jsdimgs" @tap="toDetail" :data-id="item.id">
							<image :src="item.pic + '?x-oss-process=style/w210'" mode="aspectFit" class="jsdpro">
							</image>
							<image src="/static/pages/images/jishida.png" v-if="item.isJs" class="jsdimg"></image>
						</view>
						<view class="jsdinfo">
							<view class="proname" @tap="toDetail" :data-id="item.id">{{item.title}}</view>
							<view class="list-tag ddflex">
								<block v-if="item.label">
								<view v-for="(it,idx) in item.label.split(',')" :key="idx" v-if="idx < 2">{{it}}</view>
								</block>
							</view>
							<view class="xiaol ddflex">
								<view class="vip-news ddflex" v-if="about.show_membership_price==1&&item.actualPrice < item.salePrice"><text class="vip-sale">会员价</text><text class="vip-members">￥{{item.actualPrice}}</text></view>
								<view class="vip-news ddflex" v-if="about.show_membership_price==1&&item.membersPrice<item.salePrice"><text class="vip-sale">会员价</text><text class="vip-members">￥{{item.membersPrice}}</text></view>
								<view class="yishou">{{item.sellStock}}件已售</view>
							</view>
							<view class="operate dflex">
								<view class="price proprice">
									￥<text>{{item.salePrice}}</text>
									<!-- <text class="vip" v-if="about.show_membership_price==1&&item.actualPrice < item.salePrice"><text class="sale">VIP</text><text class="members">{{item.actualPrice}}</text></text>
									<text class="vip"
										v-if="about.show_membership_price==1&&item.membersPrice<item.salePrice"><text
											class="sale">VIP</text><text
											class="members">{{item.membersPrice}}</text></text> -->
									<text class="del"><!-- v-if="about.show_membership_price!=1" -->
										<block v-if="item.marketPrice!=0&&item.marketPrice>item.salePrice">
											￥{{item.marketPrice}}
										</block>
									</text>
								</view>
								<view class="add-cart">
									<view class="nums dflex" v-if="item.count > 0">
										<image src="/static/pages/images/jian.png"></image>
										<view class="num">{{item.count}}</view>
										<image src="/static/pages/images/jia1.png"></image>
									</view>
									<image src="/static/pages/images/jia.png" @tap="addShopCart" :data-id="item.id"
										:data-skuid="item.skuId" :data-index="index" :data-state="item.state"
										v-else></image>
								</view>
							</view>
						</view>
					</view>
				</block>
			</view>
		</view>
		<view class="bot savepadding" v-if="pageList.length > 0">
			<view class="botl">
				<view class="dflex flex">
					<view class="all" data-index="-1" @tap="checkProduct">
						<image :src="isAll ? '/static/pages/images/gou_h.png' : '/static/pages/images/gou.png'"
							class="check"></image>
						全选
					</view>
					<view class="heji flex" v-if="!isEdit&&!integralshop">总计：<text>￥{{money}}</text></view>
					<view class="heji flex" v-if="!isEdit&&integralshop">总计：<text>{{integral}}积分+￥{{money}}</text>
					</view>
				</view>
				<view class="editc">
					<text class="edit" @tap="edit">{{isEdit ? '完成' : '编辑'}}</text>
				</view>
			</view>
			<view class="jiesuan" @tap="deleteCart" v-if="isEdit">删除({{count}})</view>
			<view class="jiesuan" @tap="Settlement" v-else>去结算({{count}})</view>
		</view>


		<!-- <view class="placeholder-view" :style="'height:' + (bottomBlankHeignt + 115) + 'rpx'"></view> -->
		<view class="savepadding"></view>
		<foot channel="cart" :product-type="integralshop?2:1" :isUpdate="isUpdate"></foot>
	</view>
</template>

<script>
	const app = getApp();
	const req = require("../../utils/request.js");
	let commodity = [];
	let merchantArr = [];
	let deliverWay = [];
	let ativityType = [];
	import foot from "../../components/nav-bar/index";

	export default {
		data() {
			return {
				picUrlss: req.public.picUrls,
				bottomBlankHeignt: app.globalData.isIPhoneX ? 68 : 0,
				form: {},
				pageList: [],
				page: 1,
				likeList: [],
				isLoad: true,
				isLikeLoad: true,
				isAll: false,
				isJsdAll: false,
				isCgAll: false,
				money: 0.00,
				count: 0,
				isEdit: false,
				isUpdate: false,
				// 是否更新消息
				merchant: {},
				integral: 0,
				integralshop: false,
				shopName: "",
				show_membership_price: 0,
				ishow: false,
				header: req.header,
				isLogin: false,
				about: {}
			};
		},

		components: {
			foot
		},
		props: {},

		onLoad(options) {
			this.query = options;

			if (options.integralshop == 1) {
				this.setData({
					integralshop: true
				});
			}

			// console.log(options);
			this.getLikeList();
		},

		onShow: function() {
			let _ts = this;
			let userInfo = req.getStorage('userInfo');
			if(userInfo) _ts.isLogin = true;
			this.getConfig();

			_ts.setData({
				isUpdate: !_ts.isUpdate
			}); // if (req.getStorage("MERCHANT").isDefault != 1) {
			//   req.getRequest('/api/merchant/getMerchantList', {}, res => {
			//     res = res.filter(it => it.isDefault == 1)
			//     console.log(res)
			//     this.data.merchant = res[0]
			//   })
			// } else {
			// this.data.merchant = req.getStorage("MERCHANT");
			//默认门店
			// if (req.getStorage("defaultMerchant") != "") {
			// 	this.merchant = req.getStorage("defaultMerchant")
			// }
			//用户选择的门店
			if (req.getStorage("MERCHANT") != "") {
				this.merchant = req.getStorage("MERCHANT")
			}
			// }

			this.isLoad = true;
			this.setData({
				count: 0,
				money: 0,
				shopName: this.merchant.title,
				isEdit: false
			});
			if(_ts.isLogin){
				this.getList();
			}
		},

		onHide() {
			this.query.integralshop = 0;
			this.setData({
				integralshop: false
			});
		},

		methods: {
			toDetail(e) {
				// console.log(e, "123132456")
				let id = e.currentTarget.dataset.id;
				let merchantId = e.currentTarget.dataset.merchant
				let actId=e.currentTarget.dataset.actid
				let url = 'product/detail/detail?id=' + id
				let type = e.currentTarget.dataset.type
				if (!type) {
					if (merchantId) {
						app.globalData.openPage(url + '&merchantId=' + merchantId)
					} else {
						app.globalData.openPage('product/detail/detail?id=' + id);
					}
				} else if (type == 1) {
					app.globalData.openPage('product/groupDetail/groupDetail?acid=' + actId + "&id=" + id +
						'&merchantId=' + merchantId)
				} else if (type == 2) {
					app.globalData.openPage('activity/seckillDetails/seckillDetails?acid=' + actId + "&id=" + id +
						'&merchantId=' + merchantId)
				} else if (type == 4) {
					app.globalData.openPage('activity/newbornDetails/newbornDetails?acid=' + actId + "&id=" + id +
						'&merchantId=' + merchantId)
				}


			},

			getConfig() {
				var _this = this;

				return new Promise((resolve, reject) => {
					req.getRequest('/api/config', {}, function(res) {
						if (res && res.show_membership_price == 1) {
							_this.setData({
								show_membership_price: 1
							});
						}
						if (res) {
							_this.setData({
								about: res
							});
						}

						resolve();
					});
				});
			},

			addShopCart(e) {
				let state = e.currentTarget.dataset.state;
				let skuId = e.currentTarget.dataset.skuid;
				let id = e.currentTarget.dataset.id;
				let params = {
					skuId: skuId,
					quantity: 1,
					productId: id
				};
				// if(state!=1){
				//   return req.msg('您来晚了，商品已经下架')
				// }

				if (this.merchant) {
					params.merchantId = this.merchant.id;
				}

				req.postRequest('/api/purchase/cart', params, res => {
					req.msg('加入购物车成功');
					this.setData({
						isUpdate: !this.isUpdate
					});
					this.isLoad = true;
					this.getList();
				});
			},

			getList() {
				let isShowLoading = false;

				if (this.form.page == 1 && !isShowLoading) {
					req.loadIng('加载中');
					isShowLoading = true;
				} // if (!this.data.isLoad) return false;


				this.isLoad = false;
				let that = this;
				let newList = [];
				// console.log(this.query.integralshop);

				if (this.query.integralshop == 1) {
					this.form.purchaseType = 2;
				} else {
					this.form.purchaseType = 1;
				}
				if(this.merchant){
					this.form.merchantId = this.merchant.id;
				}
				// console.log(this.form);
				req.getRequest('/api/purchase/list', this.form, data => {
					data = data.map(it => {
						let arr = ['自提', '邮寄', '同城配送', '自主配送'];
						let tabe = [];
						let deliverWays = JSON.parse(it.deliverWay);
						deliverWays.forEach(it => {
							tabe.push(arr[it - 1]);
						});

						if (it.isOtc == 5) {
							it.tabe = ['邮寄'], it.deliverWay = "[2]";
						} else {
							it.tabe = tabe;
						}

						if (it.deliverWay && JSON.parse(it.deliverWay).indexOf(3) != -1) it.isJs = true;
						return it;
					});
					// console.log(data);
					data = data.map(it => {
						if (it.deliverWay && JSON.parse(it.deliverWay).indexOf(3) != -1) it.isJs = true;
						return it;
					});

					if (this.query.integralshop == 1) {
						data = data.filter(it => it.productType == 2);
					}

					commodity.forEach(it => {
						data.forEach(el => {
							if (it.id == el.id && !el.isInvalid && it.deliverWay == el
								.deliverWay) {
								el.isActive = true;
							}
						});
					});
					this.setData({
						count: commodity.length
					});
					let params = []; // 1及时达产品

					// params.push({
					// 	isTimely: 1,
					// 	isActive: false,
					// 	list: data.filter(it => {
					// 		if (JSON.parse(it.deliverWay) && JSON.parse(it.deliverWay).indexOf(3) != -1) return it;
					// 	})
					// }); // 0常规产品

					params.push({
						isTimely: 0,
						list: data
					});
					// console.log(params); //  常规产品

					params[0].list.forEach(el => {
						if (el.merchantId == "" || el.merchantId == null) {
							let merchant = this.merchant; // let merchant = req.getStorage('MERCHANT');

							el.merchantId = merchant.id;
							el.merchantName = merchant.title;
						}
						if (newList.length == 0) {
							newList.push({
								merchantId: el.merchantId,
								merchantName: el.merchantName,
								isTimely: 0,
								isActive: false,
								list: [el],
								shopId: el.shopId,
								shopName: el.shopName,
								merchantMoney: this.about.Min_Order_Money?this.about.Min_Order_Money:0,
								freeShipping: this.about.Free_Shipping
							});
						} else {
							let res = newList.some(item => {
								if (item.merchantId == el.merchantId && item.shopId == el.shopId) {
									item.list.push(el);
									return true;
								}
							});

							if (!res) {
								newList.push({
									merchantId: el.merchantId,
									isTimely: 0,
									merchantName: el.merchantName,
									isActive: false,
									list: [el],
									shopId: el.shopId,
									shopName: el.shopName,
									merchantMoney: this.about.Min_Order_Money?this.about.Min_Order_Money:0,
									freeShipping: this.about.Free_Shipping
								});
							}
						}
					});
					let jsd = [];
					// params[0].list.forEach(el => {
					// 	if (el.merchantId == "" || el.merchantId == null) {
					// 		console.log(el); // let merchant = req.getStorage('MERCHANT');

					// 		let merchant = this.merchant;
					// 		el.merchantId = merchant.id;
					// 		el.merchantName = merchant.title;
					// 	}

					// 	if (jsd.length == 0) {
					// 		jsd.push({
					// 			merchantId: el.merchantId,
					// 			merchantName: el.merchantName,
					// 			isTimely: 1,
					// 			isActive: false,
					// 			list: [el],
					// 			shopId: el.shopId,
					// 			shopName: el.shopName
					// 		});
					// 	} else {
					// 		let res = jsd.some(item => {
					// 			if (item.merchantId == el.merchantId && item.shopId == el.shopId) {
					// 				item.list.push(el);
					// 				return true;
					// 			}
					// 		});

					// 		if (!res) {
					// 			jsd.push({
					// 				merchantId: el.merchantId,
					// 				isTimely: 1,
					// 				merchantName: el.merchantName,
					// 				isActive: false,
					// 				shopId: el.shopId,
					// 				shopName: el.shopName,
					// 				list: [el]
					// 			});
					// 		}
					// 	}
					// }); 

					newList = newList.concat(jsd);
					let i = 0;
					newList.forEach(it => {
						let arr = it.list.filter(el => el.isActive);
						// console.log(arr, it.list.length);

						if (arr.length == it.list.length) {
							it.isActive = true;
						}
					});
					let abb = newList.filter(res => res.isActive);
					// console.log(abb, newList.length);

					if (abb.length == newList.length && abb.length != 0) {
						this.setData({
							isAll: true
						});
					} else {
						this.setData({
							isAll: false
						});
					} // console.log(newList,i)
					// newList.forEach(el => {
					//   if (el.merchantId == '' || el.merchantName == '' || el.merchantName == null || el.merchantId == null) {
					//     let merchant = req.getStorage('MERCHANT');
					//     el.merchantId = merchant.id
					//     el.merchantName = merchant.title
					//     el.list.forEach(item => {
					//       item.merchantId = merchant.id
					//       item.merchantName = merchant.title
					//       if (item.merchantId == el.merchantId) {
					//         console.log(el)
					//         // item.list.push(el.list)
					//         // return true
					//       }
					//     })
					//     console.log(el)
					//   }
					// })


					that.setData({
						pageList: newList
					});
					that.CalculationMoney();
					if (this.pageList <= 0) {
						that.setData({
							ishow: true
						});
					} else {
						that.setData({
							ishow: false
						});
					}

					if (isShowLoading) {
						uni.hideLoading();
						isShowLoading = false;
					}
				});
			},

			checkProduct(event) {
				// debugger
				//选择商品
				const that = this;
				const index = event.currentTarget.dataset.index;
				const idx = event.currentTarget.dataset.idx;
				const store = event.currentTarget.dataset.store;
				const merchantId = event.currentTarget.dataset.merchantid;
				let d = {};

				if (idx == undefined) {
					// console.log("进行全选和店铺全选");

					if (index == -1) {
						// 全选
						// console.log("全选");
						const isAll = that.isAll;
						for (let i = 0, len = that.pageList.length; i < len; i++) {
							for (let j = 0, len = that.pageList[i].list.length; j < len; j++) {
								if (!this.isEdit) {
									if (this.pageList[i].list[j].store <= 0) return req.msg(this.pageList[i].list[j]
										.title + "商品已售罄");
									if (this.pageList[i].list[j].isInvalid) return req.msg(this.pageList[i].list[j].title +
										'商品已下架或失效');
									if (this.pageList[i].list[j].activityState === 0) return req.msg(this.pageList[i].list[
											j].title +
										'活动已结束');
									if (this.pageList.length > 1) return req.msg('门店与门店之间不能一起下单'); // 发货方式判断
									if(this.pageList[i].list.every(it=>it.ativityType === this.pageList[i].list[0].ativityType)){
									      return req.msg('活动商品不支持一起下单')
									}
									// 先存一个选择的发货方式
									if (deliverWay.length < 1) {
										deliverWay.push(JSON.parse(this.pageList[i].list[j].deliverWay));
									}
									// 先存一个选择的活动类型
									let activityTypes = '';
									if(!this.pageList[i].list[j].activityType){
										activityTypes = 99;
									}else{
										activityTypes = this.pageList[i].list[j].activityType;
									}
									if (ativityType.length < 1) {
										ativityType[0] = activityTypes;
									}

									let k = 0;
									// console.log(deliverWay, this.getTheSame(
										// deliverWay)); //  this.getTheSame 拿到重复的发货方式 去循环判断点击的发货方式里面存不存在这个共同的发货方式

									this.getTheSame(deliverWay).forEach(it => {
										if (JSON.parse(this.pageList[i].list[j].deliverWay).indexOf(it) == -1) {
											this.fou = true;
											// console.log("123");
											this.CalculationMoney(index);
										} else {
											ativityType.map(it=>{
												if (activityTypes != it) {
													this.fou = true;
												}else{
													k++;
													this.fou = false;
												}
											})
											// k++;
											// this.fou = false;
										}
									});

									if (k > 0) {
										this.fou = false;
									}

									// console.log(k);
								}

								if (!that.pageList[i].list[j].isInvalid) {
									this.pageList.some(item => {
										if (item.merchantId == this.pageList[i].merchantId) {
											if (merchantArr.length > 0) {
												if (merchantArr[0] != this.pageList[i].merchantId) {
													// return false
													let res = this.pageList.map(it => {
														if (it.isActive) {
															it.isActive = !it.isActive;
														}

														it.merchantMoney = 0;
														it.list.map(el => {
															if (el.isActive) {
																el.isActive = !el.isActive;
																return el;
															}
														});
														return it;
													});
													merchantArr.splice(0, 1, this.pageList[i].merchantId);
													this.setData({
														pageList: res
													});
												}
											} else {
												merchantArr.push(item.merchantId);
											}
										}
									});
								}
								if (this.fou) {
									return req.msg('暂不支持一起下单');
								} else {
									// console.log("545");
									d['pageList[' + i + '].list[' + j + '].isActive'] = !isAll;
									d['pageList[' + i + '].isActive'] = !isAll;
								}
							}
						}

						d['isAll'] = !isAll;

					} else {
						for (let i = 0, len = this.pageList[index].list.length; i < len; i++) {
							if (!this.isEdit) {
								if (this.pageList[index].list[i].store <= 0) return req.msg(this.pageList[index].list[i]
									.title + "商品已售罄");
								if (this.pageList[index].list[i].isInvalid) return req.msg(this.pageList[index].list[i]
									.title + '商品已下架或失效');
								if (this.pageList[index].list[i].activityState === 0) return req.msg(this.pageList[index]
									.list[i]
									.title +
									'活动已结束');
								// 发货方式判断
								// 先存一个选择的发货方式
								// 判断是否切换了门店，切换了就清空deliverWay

								if (this.pageList[index].merchantId != merchantArr[0]) {
									deliverWay = [];
								} // 判断deliverWay长度是否小于1，小于1就默认拿当前第一个产品的发货方式存进去


								if (deliverWay.length < 1) {
									deliverWay.push(JSON.parse(this.pageList[index].list[i].deliverWay));
								} 
								// 先存一个选择的活动类型
								let activityTypes = '';
								if(!this.pageList[index].list[i].activityType){
									activityTypes = 99;
								}else{
									activityTypes = this.pageList[index].list[i].activityType;
								}
								if (ativityType.length < 1) {
									ativityType[0] = activityTypes;
								}
								// 设置j标识


								let j =
									0; //  this.getTheSame 拿到重复的发货方式 去循环判断点击的发货方式里面存不存在这个共同的发货方式 不存在就提示用户不能一起下单，存在就j++，只要j大于0就说明有共同的发货方式

								this.getTheSame(deliverWay).forEach(it => {
									if (JSON.parse(this.pageList[index].list[i].deliverWay).indexOf(it) == -1) {
										this.fou = true;
										this.CalculationMoney(index);
									} else {
										ativityType.map(it=>{
											if (activityTypes != it) {
												this.fou = true;
											}else{
												j++;
												this.fou = false;
											}
										})
										// j++;
										// this.fou = false;
									}
								});

								if (j > 0) {
									this.fou = false;
								}
							}

							if (!this.pageList[index].list[i].isInvalid) {
								this.pageList.some(item => {
									if (item.merchantId == this.pageList[index].merchantId) {
										if (merchantArr.length > 0) {
											if (merchantArr[0] != this.pageList[index].merchantId) {
												let res = this.pageList.map(it => {
													if (it.isActive) {
														it.isActive = !it.isActive;
													}

													it.merchantMoney = 0;
													it.list.map(el => {
														if (el.isActive) {
															el.isActive = !el.isActive;
															return el;
														}
													});
													return it;
												});
												merchantArr.splice(0, 1, this.pageList[index].merchantId);
												this.setData({
													pageList: res
												});
											}
										} else {
											merchantArr.push(item.merchantId);
										}
									}
								});
							}

							if (this.fou) {
								return req.msg('暂不支持一起下单');
							} else {
								d['pageList[' + index + '].list[' + i + '].isActive'] = !this.pageList[index].isActive;
								d['pageList[' + index + '].isActive'] = !this.pageList[index].isActive;
							}

						}
					} // if (this.data.index == index) {
					//   isJsdAll = this.data.isJsdAll
					// }else{
					//   isJsdAll=false
					// }

				} else {
					// 单选
					// console.log("单选");

					if (!this.isEdit) {
						if (this.pageList[index].list[idx].store <= 0) return req.msg(this.pageList[index].list[idx]
							.title + "商品已售罄");
						if (this.pageList[index].list[idx].isInvalid) return req.msg(this.pageList[index].list[idx].title +
							'商品已下架或失效');
						if (this.pageList[index].list[idx].activityState === 0) return req.msg(this.pageList[index].list[
								idx].title +
							'活动已结束');
						// 发货方式判断
						// 先存一个选择的发货方式

						// console.log(deliverWay);

						if (deliverWay.length < 1) {
							deliverWay.push(JSON.parse(this.pageList[index].list[idx].deliverWay));
						}
						// 先存一个选择的活动类型
						let activityTypes = '';
						if(!this.pageList[index].list[idx].activityType){
							activityTypes = 99;
						}else{
							activityTypes = this.pageList[index].list[idx].activityType;
						}
						if (ativityType.length < 1) {
							ativityType[0] = activityTypes;
						}
						let i = 0;
						// console.log(deliverWay); //  this.getTheSame 拿到重复的发货方式 去循环判断点击的发货方式里面存不存在这个共同的发货方式
						this.getTheSame(deliverWay).forEach(it => {
							if (JSON.parse(this.pageList[index].list[idx].deliverWay).indexOf(it) == -1) {
								this.fou = true;
							} else {
								ativityType.map(it=>{
									if (activityTypes != it) {
										this.fou = true;
									}else{
										i++;
										this.fou = false;
									}
								})
								// i++;
								// this.fou = false;
							}
						});

						if (i > 0) {
							this.fou = false;
						}
						// console.log(i);
						// console.log(this.fou);
					}

					// 单独门店的最低消费和包邮计算
					this.pageList.some(item => {
						if (item.merchantId == this.pageList[index].merchantId) {
							if (merchantArr.length > 0) {
								if (merchantArr[0] != this.pageList[index].merchantId) {
									// return false
									let res = this.pageList.map(it => {
										if (it.isActive) {
											it.isActive = !it.isActive;
										} else {
											it.merchantMoney = 0;
										}

										it.list.map(el => {
											if (el.isActive) {
												el.isActive = !el.isActive;
												return el;
											}
										});
										return it;
									});
									merchantArr.splice(0, 1, this.pageList[index].merchantId);
									this.setData({
										pageList: res
									});
								}
							} else {
								merchantArr.push(item.merchantId);
							}
						}
					});
					if (this.fou) {
						return req.msg('暂不支持一起下单');
					} else {
						d['pageList[' + index + '].list[' + idx + '].isActive'] = !this.pageList[index].list[idx].isActive;
					}
				}
				
				// console.log(d);
				this.setData(d);
				// console.log(this.pageList);
				commodity = [];
				this.pageList.forEach(it => {
					it.list.forEach(el => {
						if (el.isActive) {
							commodity.push({
								id: el.id,
								deliverWay: el.deliverWay
							});
						}
					});
				});
				// console.log(...new Set(commodity));

				if (index != -1) {
					this.merchantCheckProduct(index, idx);
				}

				this.CalculationMoney(index);
			},
			// 获取重复的配送方式值
			getTheSame(arr) {
				return arr.reduce(function(a, b) {
					return a.filter(function(item) {
						return b.includes(item);
					})
				})
			},
			// 获取重复的活动类型值
			getTheSameType(arr) {
				return arr.reduce(function(a, b) {
					return a.filter(function(item) {
						return b.includes(item);
					})
				})
			},

			// 判断店铺的商品是否全部选择
			merchantCheckProduct(index, idx) {
				let d = {}; // debugger

				// console.log("=======================", this.pageList[index].list.filter(it => it.isActive).length == this
					// .pageList[
						// index].list.length, this.pageList.filter(it => it.isActive).length == this.pageList.length);
				// console.log(this.pageList[index].list.filter(it => it.isActive))
				if (this.pageList[index].list.filter(it => it.isActive).length == this.pageList[index].list.length) {
					d['pageList[' + index + '].isActive'] = true;
				} else {
					d['pageList[' + index + '].isActive'] = false;
					d['isAll'] = false;
				}

				this.setData(d);

				if (this.pageList.filter(it => it.isActive).length == this.pageList.length) {
					this.setData({
						isAll: true
					});
				}
			},

			adjustmentQuantity(id, quantity, skuId, success) {
				req.postRequest('/api/purchase/quantity', {
					id: id,
					skuId: skuId,
					quantity: quantity
				}, () => {
					this.setData({
						isUpdate: !this.isUpdate
					});
					success.call(this);
				});
			},

			jianQuantity(event) {
				const index = event.currentTarget.dataset.index;
				const idx = event.currentTarget.dataset.idx;
				const page = this.pageList[index].list[idx];
				if (page.store <= 0) return req.msg(page.title + '已售罄');
				if (page.isInvalid) return req.msg('商品已下架或失效');
				if (page.activityState === 0) return req.msg('该活动已结束');
				if (page.quantity <= 1) return false;
				const q = parseInt(page.quantity) - 1;
				let that = this;
				this.adjustmentQuantity(page.id, q, page.skuId, () => {
					let d = {};
					d['pageList[' + index + '].list[' + idx + '].quantity'] = q;
					this.getList();
					that.setData(d);
					// if (page.isActive) that.CalculationMoney();
				});
			},

			jiaQuantity(event) {
				const index = event.currentTarget.dataset.index;
				const idx = event.currentTarget.dataset.idx;
				const page = this.pageList[index].list[idx];
				if (page.store <= 0) return req.msg(page.title + '已售罄');
				if (page.isInvalid) return req.msg('商品已下架或失效');
				if (page.activityState === 0) return req.msg('该活动已结束');
				let q = parseInt(page.quantity) + 1;

				if (page.maxBuy > 0) {
					// console.log(page, q, "===========================");
					if (q > page.maxBuy) return req.msg('非常的抱歉，本产品最多可购买' + page.maxBuy);
					else {
						q = parseInt(page.quantity) + 1;
					}
				}

				let that = this;
				this.adjustmentQuantity(page.id, q, page.skuId, () => {
					let d = {};
					d['pageList[' + index + '].list[' + idx + '].quantity'] = q;
					that.setData(d);
					this.getList();
					// if (page.isActive) that.CalculationMoney();
				});
			},

			// 获取输入的值
			getNum(event) {
				const index = event.currentTarget.dataset.index;
				const idx = event.currentTarget.dataset.idx;
				const page = this.pageList[index].list[idx];
				if (page.store <= 0) {
					req.msg(page.title + '已售罄');
					return 1
				} else if (page.isInvalid) {
					req.msg('商品已下架或失效');
					return 1
				} else if (page.activityState === 0) {
					req.msg('该活动已结束');
					return 1
				} else {
					let q = event.detail.value;

					if (page.maxBuy > 0) {
						if (q > page.maxBuy) {
							req.msg('非常的抱歉，本产品最多可购买' + page.maxBuy);
							q = page.maxBuy;
						} else {
							q = event.detail.value;
						}
					}

					let d = {};
					d['pageList[' + index + '].list[' + idx + '].quantity'] = q;
					this.setData(d);
					return q
				}
				// if (page.isActive) this.CalculationMoney(); // let that = this;
				// console.log(q)
				// if(q!=''){
				//   this.adjustmentQuantity(page.id, q, page.skuId, () => {
				//     let d = {};
				//     d['pageList[' + index + '].list[' + idx + '].quantity'] = q;
				//     that.setData(d);
				//     if (page.isActive) that.CalculationMoney();
				//   })
				// }
			},

			minNum(event) {
				const index = event.currentTarget.dataset.index;
				const idx = event.currentTarget.dataset.idx;
				const page = this.pageList[index].list[idx];
				let that = this;
				if (page.store <= 0) {
					req.msg(page.title + '已售罄');
					return 1
				} else
				if (page.isInvalid) {
					req.msg('商品已下架或失效');
					return 1
				} else
				if (page.activityState === 0) {
					req.msg('该活动已结束');
					return 1
				} else
				if (event.detail.value == '') {
					let q = 1;
					this.adjustmentQuantity(page.id, q, page.skuId, () => {
						let d = {};
						d['pageList[' + index + '].list[' + idx + '].quantity'] = q;
						that.setData(d);
						// if (page.isActive) that.CalculationMoney();
						this.getList();
					});
				} else {
					let q = parseInt(event.detail.value);

					if (q > page.store) {
						req.msg('非常的抱歉，本产品库存量剩余' + page.store);
						q = page.store;
					}

					this.adjustmentQuantity(page.id, q, page.skuId, () => {
						let d = {};
						d['pageList[' + index + '].list[' + idx + '].quantity'] = q;
						that.setData(d);
						// if (page.isActive) that.CalculationMoney();
						this.getList();
						return q
					});
				}
			},

			deleteCart(event) {
				//删除购物车数据
				// const index = event.currentTarget.dataset.index;
				// const page = this.data.pageList[index];
				const page = this.pageList;
				let ids = [];
				page.map(item => {
					item.list.map(it => {
						if (it.isActive) ids.push(it.id);
					});
				});
				if (!ids || ids.length == 0) return req.msg('请选择删除项');
				let that = this;
				req.msgConfirm('确定删除该商品', () => {
					req.postRequest('/api/purchase/deletes', {
						ids: ids.join(',')
					}, () => {
						let data = [];

						for (let i = 0, len = that.pageList.length; i < len; i++) {
							data.push({
								merchantId: that.pageList[i].merchantId,
								merchantName: that.pageList[i].merchantName,
								isTimely: that.pageList[i].isTimely,
								list: that.pageList[i].list.filter(it => !it.isActive)
							});
						}

						data = data.filter(res => res.list.length != 0);

						if (data.length <= 0) {
							that.setData({
								ishow: true,
								isAll: false
							});
						} else {
							that.setData({
								ishow: false
							});
						}

						that.setData({
							pageList: data,
							count: 0,
							money: 0.00
						});
						this.setData({
							isUpdate: !this.isUpdate
						}); // if (page.isActive) that.CalculationMoney();
					});
				});
			},

			CalculationMoney(index) {
				//计算商品总价格
				let arr = [];
				let jsdMoney = 0;
				let money = 0.00;
				let integral = 0;
				let merchantMoney = 0;
				deliverWay = [];
				this.pageList.forEach(el => {
					if(el.list.filter(it => it.isActive).length < 1){
						ativityType = [];
					}
					arr.push(el.list.filter(it => it.isActive).length);
					el.list.filter(it => it.isActive).forEach(lst => {
						jsdMoney += lst.quantity * lst.price;
						integral += lst.quantity * lst.integral;
						deliverWay.push(JSON.parse(lst
							.deliverWay
						)); // deliverWay=[...new Set(deliverWay.concat(JSON.parse(lst.deliverWay)))]
					}); // console.log(deliverWay);
				}); // console.log(deliverWay);

				let res = this.pageList.map(el => {
					el.merchantMoney = this.about.Min_Order_Money ? this.about.Min_Order_Money : 0;
					if (commodity.length == 0) {
						el.freeShipping = parseFloat(this.about.Free_Shipping - merchantMoney).toFixed(2);
					}
					el.list.filter(it => it.isActive).forEach(lst => {
						if (merchantArr[0] == lst.merchantId) {
							// console.log("4546456")
							merchantMoney += lst.quantity * lst.price;
							el.merchantMoney = parseFloat(this.about.Min_Order_Money - merchantMoney)
								.toFixed(2);
							el.freeShipping = parseFloat(this.about.Free_Shipping - merchantMoney).toFixed(
								2);
							return lst;
						}
					});
					return el;
				});

				var count = arr.reduce(function(prev, cur) {
					return prev + cur;
				}, 0);
				// console.log(res, "=============")
				money = Number(jsdMoney);
				this.setData({
					count: count,
					money: parseFloat(money).toFixed(2),
					integral: integral,
					pageList: res

				});
			},

			Settlement() {
				// debugger
				const page = this.pageList;
				const ids = [];
				// console.log(page);
				page.map(item => {
					item.list.map(it => {
						if (it.isActive) ids.push(it.id);
					});
				});
				if (this.about.Min_Order_Money) {
					if (this.about.Min_Order_Money - this.money > 0) {
						// console.log('还差' + parseFloat(this.about.Min_Order_Money).toFixed(2) - parseFloat(this.money)
							// .toFixed(2) + '元下单');
						return req.msg('还差' + (parseFloat(this.about.Min_Order_Money).toFixed(2) - parseFloat(this.money)
								.toFixed(2)) +
							'元下单');
					}
				}
				if (ids.length == 0) return req.msg('未选择结算商品');
				const timely = [];
				const noTimely = [];
				const merchantList = [];
				const timelyList = [];
				const all = []
				page.map(item => {
					item.list.map(it => {
						//发货方式：自提1,邮寄2,同城配送3,自主配送4;
						if (it.isActive && it.deliverWay && JSON.parse(it.deliverWay).indexOf(3) != -1)
							timely.push(it);
						if ((it.isActive && it.deliverWay && JSON.parse(it.deliverWay).indexOf(3) == -1) ||
							(it.deliverWay == null && it.isActive)) noTimely.push(it);
						if (it.isActive) all.push(it);
					});
				}); // 常规产品

				noTimely.forEach(el => {
					if (merchantList.length == 0) {
						merchantList.push({
							merchantId: el.merchantId,
							merchantName: el.merchantName,
							isTimely: 0,
							isActive: false,
							list: [el],
							shopId: el.shopId,
							shopName: el.shopName
						});
					} else {
						let res = merchantList.some(item => {
							if (item.merchantId == el.merchantId && item.shopId == el.shopId) {
								item.list.push(el);
								return true;
							}
						});

						if (!res) {
							merchantList.push({
								merchantId: el.merchantId,
								isTimely: 0,
								merchantName: el.merchantName,
								isActive: false,
								list: [el],
								shopId: el.shopId,
								shopName: el.shopName
							});
						}
					}
				});
				// 及时达
				timely.forEach(el => {
					if (timelyList.length == 0) {
						timelyList.push({
							merchantId: el.merchantId,
							merchantName: el.merchantName,
							isTimely: 1,
							isActive: false,
							list: [el],
							shopId: el.shopId,
							shopName: el.shopName
						});
					} else {
						let res = timelyList.some(item => {
							if (item.merchantId == el.merchantId && item.shopId == el.shopId) {
								item.list.push(el);
								return true;
							}
						});

						if (!res) {
							timelyList.push({
								merchantId: el.merchantId,
								isTimely: 1,
								merchantName: el.merchantName,
								isActive: false,
								list: [el],
								shopId: el.shopId,
								shopName: el.shopName
							});
						}
					}
				}); // const timely = this.data.pageList.filter(it => it.isActive && it.isTimely === 1);
				// const noTimely = this.data.pageList.filter(it => it.isActive && it.isTimely === 0);

				// console.log(timely, noTimely); // 海外购产品
				let hwg = noTimely.filter(it => it.isOtc == 5);
				let act = all.filter(it => it.activityType)
				let otc = all.filter(it => !it.activityType)
				let active = []
				if (act.length > 0) {
					all.forEach(it => {
						if (it.activityType == act[0].activityType) {
							active.push(it)
						}

					})
				}
				// if (timely.length > 0 && noTimely.length > 0) return req.alertMsg('及时达商品和非及时达商品不能一起下单');
				// console.log("act", act, "otc", otc, "active", active, "all", all)
				if (merchantList.length >= 2 || timelyList.length >= 2) return req.alertMsg('门店与门店之间不能一起下单'); //判断是否及时达订单

				let redirect = 'product/subOrder/subOrder?ids=' + ids.join(',');
				let orderType = 1;
				let merchantId = '';
				let shopId;
				if (timely.length > 0) merchantId = timelyList[0].merchantId;
				if (active.length > 0 && act.length > 0) {
					if (active.length == all.length) {
						if (act[0].activityType == 1) orderType = 2
						if (act[0].activityType == 2) orderType = 3
						if (act[0].activityType == 3) orderType = 4
						if (act[0].activityType == 4) orderType = 6
						if (act[0].activityType == 5) orderType = 7
					} else {
						orderType = 20
					}
				} else {
					if (timely.length > 0) orderType = 5;
					if (hwg.length > 0) orderType = 10;
					if (act.length > 0 && otc.length > 0) orderType = 20
					if (this.query.integralshop == 1) orderType = 11;
				}
				if (merchantList.length > 0) {
					merchantId = merchantList[0].merchantId;

					if (merchantList[0].shopId) {
						shopId = merchantList[0].shopId;
						redirect += '&shopId=' + shopId;
					}
				}
				


				redirect += '&orderType=' + orderType + '&merchantId=' + merchantId;
				app.globalData.openPage(redirect);
				// console.log(redirect)
			},

			edit() {
				deliverWay = [];
				merchantArr = [];
				commodity = [];

				if (this.isEdit) {
					let res = this.pageList.map(it => {
						it.merchantMoney = this.about.Min_Order_Money ? this.about.Min_Order_Money : 0;
						it.freeShipping = this.about.Free_Shipping ? this.about.Free_Shipping : 0;
						it.list.map(el => {
							el.isActive = false;
							return el;
						});
						it.isActive = false;
						return it;
					});
					// console.log(res);
					this.setData({
						pageList: res,
						isAll: false,
						money: 0.00
					});
				}

				if (!this.isEdit) {
					// console.log(this.fou);
					this.fou = false;
				}
				this.setData({
					isEdit: !this.isEdit
				});
			},
			goindex() {
				uni.switchTab({
					url: req.header.appId == 'ZQ1VK5oc17I387E' ? '/pages/timelyDelivery/index' :
						'/pages/index/index'
				})
			},
			getLikeList() {
				//Recommend
				if (!this.isLikeLoad) return false;
				this.isLikeLoad = false;
				let that = this;
				req.getRequest('/api/product/list', {
					page: that.page,
					limit: 10,
					attr: 'sell_well'
				}, res => {
					if (res && res.length >= 10) that.isLikeLoad = true;
					if (that.page > 1) res = that.likeList.concat(res);
					res = res.map(it => {
						if (it.deliverWay && JSON.parse(it.deliverWay).indexOf(3) != -1) it.isJs = true;
						return it;
					});
					that.setData({
						likeList: res
					});
				});
			}

		}
	};
</script>
<style>
	@import "./cart.css";
</style>
