<template>
	<view class="cartPage" :style="[mainStyle]">
		<!-- <view :class="'top-fixed' + (skinNotColor ? ' not-color' : '')" :style="'height: '+ systems.barHeight + 'rpx;'">
			<view :class="'bgcolor' + (isTop == 1 ? ' opacity' : '')" :style="'height:' + systems.barHeight + 'rpx'">
			</view>
			<view class="top-fixed-c"
				:style="'height: '+ systems.navigationHeight + 'rpx;margin-top:' + systems.ktxStatusHeight + 'rpx;'">
				<navigator v-if="backBtn" url="" hover-class="none" open-type="navigateBack" class="back">
					<image :src="picUrlss+'back_black.png'"></image>
				</navigator>
				<view class="top-title tover"
					:style="'line-height: '+ systems.navigationHeight + 'rpx;'+(backBtn?'':'padding-left:30rpx;')">购物车
				</view>
			</view>
		</view>
		<view :style="'height: '+ systems.barHeight + 'rpx;'"></view> -->
		<view class="page">
			<block v-for="(items, index) in pageList" :key="index">
				<!-- 普通产品 -->
				<view class="cart" v-if="items.list.length > 0">
					<view class="dian dflex">
						<image :src="items.isActive ? '/static/pages/images/gou_h.png' : '/static/pages/images/gou.png'"
							class="check" :data-merchantId="items.merchantId" :data-index="index" @tap="checkProduct">
						</image>
						<view class="flex dflex top" v-if="items.isTimely == 0">
							<view class="merchantName">{{ items.shopName ? items.shopName : items.merchantName }}</view>
							<block v-if="!isEdit">
								<block v-if="about.Min_Order_Money && items.merchantMoney > 0">
									<view class="dflex">
										<view class="tbg">还差{{ items.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="items.freeShipping > 0">还差{{ items.freeShipping }}元包邮
										</view>
										<view v-if="items.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="items.isTimely == 1">
							{{ items.shopName ? items.shopName : items.merchantName }}及时达</view>
					</view>
					<view class="list">
						<block v-for="(item, idx) in items.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-if="item.productForm == 1" 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 open-type="navigateBack">去逛逛</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="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">￥{{ item.marketPrice }}</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>
		</block>
		<view @click="jumpLogin()" hover-class="none" class="cart-login" v-if="!isLogin">请点击登录，查看购物车</view>
		<view class="bot savepadding" :style="'bottom:'+(isSwitchTab ? '115':'-1')+'rpx;'" 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>
		<foot channel="cart" :isUpdate="isUpdate" v-if="isSwitchTab"></foot>
		<!-- #ifdef MP-WEIXIN -->
		<update-userinfo :update-info="isUpdateInfo" :update-mobile="isUpdateMobile" v-if="isShowUpdate"
			@closeUpdate="closeUpdate" @updateInfo="updateInfo" @updateMobile="updateMobile"></update-userinfo>
		<!-- #endif -->
	</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 {
		components: {
			foot
		},
		data() {
			return {
				mainStyle: app.globalData.mainStyle,
				picUrlss: req.public.picUrls,
				bottomBlankHeignt: app.globalData.isIPhoneX ? 68 : 0,
				systems: {},
				isTop: 0,
				query: {},
				form: {},
				pageList: [],
				page: 1,
				likeList: [],
				isLoad: true,
				isLikeLoad: true,
				isAll: false,
				isJsdAll: false,
				isCgAll: false,
				money: 0.0,
				count: 0,
				isEdit: false,
				isUpdate: false,
				// 是否更新消息
				merchant: {},
				integral: 0,
				integralshop: false,
				shopName: '',
				show_membership_price: 0,
				ishow: false,
				header: req.header,
				isLogin: false,
				about: {},
				isShowUpdate: false, //是否显示更新信息弹窗
				isUpdateInfo: false, //更新用户信息
				isUpdateMobile: false, //绑定手机号
				isSwitchTab: false, //是否是tab
				backBtn: false
			};
		},
		props: {},

		async onLoad(options) {
			console.log('cart onLoad')
			let pages = getCurrentPages();
			var prevPage = pages[pages.length - 2];
			if (prevPage) {
				this.backBtn = true
			}
			// 如果是tab页面不往下执行跳转tab缓存页面
			await this.getConfig().then(async res => {
				if (req.isTabPage('cart', this.about.solution_name)) {
					req.toTabBar('cart', options)
					return false
				} else {
					this.onLoadPage(options)
				}
			});
		},

		onShow: async function() {
			let _ts = this;
			let userInfo = req.getStorage('userInfo');
			if (userInfo) _ts.isLogin = true;
			// #ifdef MP-WEIXIN
			uni.hideHomeButton();
			// #endif
			// 如果是tab页面不往下执行跳转tab缓存页面
			await this.getConfig().then(async res => {
				if (req.isTabPage('cart', this.about.solution_name)) {
					return false
				} else {
					this.onShowPage()
				}
			});
		},

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

		methods: {

			jumpLogin() {
				req.isLogins(true);
			},


			onLoadPage(options) {
				console.log("--------options", options)
				this.query = options;

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

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

			onShowPage: 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') != '') {
					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();
				}
			},
			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
							});
						}
						if (req.isTabPage('cart', _this.about.solution_name)) {
							_this.isSwitchTab = true;
						}
						resolve(res);
					});
				});
			},

			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 (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;
				}
				this.isLoad = false;
				let that = this;
				let newList = [];

				if (this.query.integralshop == 1) {
					this.form.purchaseType = 2;
				} else {
					this.form.purchaseType = 1;
				}
				if (this.merchant) {
					this.form.merchantId = this.merchant.id;
				}
				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: 0,
						list: data
					});
					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 = [];
					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
						});
					}

					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 && 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;
									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;
												}
											});
										}
									});

									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;
											}
										});
									}
								});

								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;
							}
						}
					}
				} else {
					// 单选
					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 + '活动已结束');

						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;
									}
								});
							}
						});

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

					// 单独门店的最低消费和包邮计算
					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
							});
						}
					});
				});

				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
				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) {
					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;
				}
			},

			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);
						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);
						this.getList();
						return q;
					});
				}
			},

			deleteCart(event) {
				//删除购物车数据
				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.0
							});
							this.setData({
								isUpdate: !this.isUpdate
							});
						}
					);
				});
			},

			CalculationMoney(index) {
				//计算商品总价格
				let arr = [];
				let jsdMoney = 0;
				let money = 0.0;
				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));
						});
				});

				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) {
								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);
				money = Number(jsdMoney);
				this.setData({
					count: count,
					money: parseFloat(money).toFixed(2),
					integral: integral,
					pageList: res
				});
			},

			/**
			 * 判断勾选的产品是否为同一类型的产品（实物/虚拟物+服务）：1实物、2虚拟物、3服务；判断是否能下单
			 */
			isCheckProOrder() {
				var list = [];
				var productNum = 0; //选择的产品个数
				this.pageList.map(it => {
					it.list.map(itx => {
						if (itx.isActive) {
							productNum++;
							if (itx.productForm == 1) {
								list.push(itx);
							}
						}
					});
				});
				console.log('list====>>>', list);
				if (list.length == 0 || list.length == productNum) {
					return true;
				}

				return false;
			},

			Settlement() {
				// #ifdef MP-WEIXIN
				if (!req.getStorage('userInfo').mobile) {
					this.isShowUpdate = true;
					this.isUpdateMobile = true;
					return false;
				}
				// #endif

				//判断勾选的产品是否为同一类型的产品（实物、虚拟物、服务）
				if (!this.isCheckProOrder()) {
					return req.msg('暂不支持一起下单');
				}
				// 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) {
						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
							});
						}
					}
				});
				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 (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 (req.getStorage('user_merchantId')) {
					merchantId = req.getStorage('user_merchantId');
				} else {
					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 (req.getStorage('user_merchantId')) {
					merchantId = req.getStorage('user_merchantId');
				} else {
					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.0
					});
				}

				if (!this.isEdit) {
					// console.log(this.fou);
					this.fou = false;
				}
				this.setData({
					isEdit: !this.isEdit
				});
			},
			goindex() {
				uni.reLaunch({
					url: '/pages/service/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
						});
					}
				);
			},
			closeUpdate() {
				this.isShowUpdate = false;
			},
			updateInfo(e) {
				this.isUpdateInfo = e;
			},
			updateMobile(e) {
				this.isUpdateMobile = e;
			}
		},
		mounted() {
			const systemInfo = uni.getSystemInfoSync();
			// px转换到rpx的比例
			let pxToRpxScale = 750 / systemInfo.windowWidth;
			let systems = {
				ktxStatusHeight: systemInfo.statusBarHeight * pxToRpxScale, // 状态栏的高度
				navigationHeight: 44 * pxToRpxScale // 导航栏的高度
			};
			systems.barHeight = systems.ktxStatusHeight + systems.navigationHeight;
			this.systems = systems;
		},
		onPageScroll: function(e) {
			if (e.scrollTop > this.systems.barHeight) {
				this.isTop = 1;
			} else {
				this.isTop = 0;
			}
		}
	};
</script>
<style scoped>
	@import './cart.css';
</style>