<template>
	<view>
		<view class="page">
			<block v-for="(item, index) in pageList" :key="index">
				<!-- 普通产品 -->
				<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" v-if="item.isTimely == 0">{{ item.merchantName }}</view>
						<view class="flex" v-if="item.isTimely == 1">{{ 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">
										<image :src="item.pic" mode="aspectFit" class="cimg"></image>
										<image src="/static/pages/images/jishida.png" class="type" v-if="item.isTimely == 1"></image>
										<view class="gys" v-if="item.isTimely == 2">不支持自提</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">
											{{ item.title }}
										</view>
										<view class="color999" v-if="item.store <= 0 || item.isInvalid">{{ item.store <= 0 ? '已售罄' : item.isInvalid ? '已下架' : '' }}</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">
											<view class="integral">
												<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>
								</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="/integralshop/index/index" open-type="redirect">去逛逛</navigator>
			</view>
			<view class="cai pdlr20">
				<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/w375'" mode="aspectFit" class="jsdpro"></image>
								<image src="/static/pages/images/jishida.png" v-if="item.isTimely === 1" 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="del">￥{{ 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" v-else></image>
									</view>
								</view>
							</view>
						</view>
					</block>
				</view>
			</view>
		</block>

		<view class="bot" :style="'bottom:' + (bottomBlankHeignt + 115) + '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">
						总计:
						<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>
		<foot channel="cart" product-type="2" :isUpdate="isUpdate"></foot>
	</view>
</template>

<script>
const app = getApp();
const req = require('../../utils/request.js');
import foot from '../components/integral-nav/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.0,
			count: 0,
			isEdit: false,
			isUpdate: false,
			// 是否更新消息
			merchant: {},
			integral: 0,
			shopName: '',
			ishow: false
		};
	},

	components: {
		foot
	},
	props: {},

	onLoad(options) {
		this.query = options;
		// console.log(options);
		this.getLikeList();
	},

	onShow: function() {
		let _ts = this;

		_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.merchant = req.getStorage('MERCHANT'); // }

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

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

	methods: {
		toDetail(e) {
			let id = e.currentTarget.dataset.id;
			app.globalData.openPage('integralshop/detail/detail?id=' + id);
		},

		addShopCart(e) {
			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;
			}

			if (!this.isLoad) return false;
			this.isLoad = false;
			let that = this;
			let newList = [];
			this.form.purchaseType = 2;
			// console.log(this.form);
			req.getRequest('/api/purchase/list', this.form, data => {
				let params = []; // 1及时达产品

				params.push({
					isTimely: 1,
					isActive: false,
					list: data.filter(it => it.isTimely == 1)
				}); // 0常规产品

				params.push({
					isTimely: 0,
					list: data.filter(it => it.isTimely == 0 || it.isTimely == 2)
				}); //  常规产品

				params[1].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]
						});
					} else {
						let res = newList.some(item => {
							if (item.merchantId == el.merchantId) {
								item.list.push(el);
								return true;
							}
						});

						if (!res) {
							newList.push({
								merchantId: el.merchantId,
								isTimely: 0,
								merchantName: el.merchantName,
								isActive: false,
								list: [el]
							});
						}
					}
				});
				// console.log(newList);
				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]
						});
					} else {
						let res = jsd.some(item => {
							if (item.merchantId == el.merchantId) {
								item.list.push(el);
								return true;
							}
						});

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

				newList = newList.concat(jsd);
				// console.log(newList); // 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
				});

				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 (!that.pageList[i].list[j].isInvalid) {
								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].isInvalid) {
							d['pageList[' + index + '].list[' + i + '].isActive'] = !this.pageList[index].isActive;
							d['pageList[' + index + '].isActive'] = !this.pageList[index].isActive;
						} // d['isJsd']=index
					}
				} // 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 + '商品已下架或失效');
				}

				d['pageList[' + index + '].list[' + idx + '].isActive'] = !this.pageList[index].list[idx].isActive;
			}

			// console.log(d);
			this.setData(d);

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

			this.CalculationMoney(index);
		},

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

			if (this.pageList[index].list.filter(it => it.isActive).length == this.pageList[index].list.length) {
				if (this.pageList.filter(it => it.isActive).length == this.pageList.length) {
					d['isAll'] = true;
				}

				d['pageList[' + index + '].isActive'] = true;
			} else {
				d['pageList[' + index + '].isActive'] = false;
				d['isAll'] = false;
			}

			this.setData(d);
		},

		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.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;
				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('商品已下架或失效');
			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);
				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) return req.msg(page.title + '已售罄');
			if (page.isInvalid) return req.msg('商品已下架或失效');
			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);
			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 (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();
				});
			} 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();
				});
			}
		},

		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
						});
						this.setData({
							isUpdate: !this.isUpdate
						}); // if (page.isActive) that.CalculationMoney();
					}
				);
			});
		},

		CalculationMoney(index) {
			//计算商品总价格
			let arr = [];
			let jsdMoney = 0;
			let money = 0;
			let integral = 0;
			this.pageList.forEach(el => {
				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;
					});
			});
			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
			});
		},

		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 (ids.length == 0) return req.msg('未选择结算商品');
			const timely = [];
			const noTimely = [];
			const merchantList = [];
			const timelyList = [];
			page.map(item => {
				item.list.map(it => {
					if (it.isActive && it.isTimely === 1) timely.push(it);
					if (it.isActive && (it.isTimely === 0 || it.isTimely === 2)) noTimely.push(it);
				});
			}); // 常规产品

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

					if (!res) {
						merchantList.push({
							merchantId: el.merchantId,
							isTimely: 0,
							merchantName: el.merchantName,
							isActive: false,
							list: [el]
						});
					}
				}
			}); // 及时达

			timely.forEach(el => {
				if (timelyList.length == 0) {
					timelyList.push({
						merchantId: el.merchantId,
						merchantName: el.merchantName,
						isTimely: 1,
						isActive: false,
						list: [el]
					});
				} else {
					let res = timelyList.some(item => {
						if (item.merchantId == el.merchantId) {
							item.list.push(el);
							return true;
						}
					});

					if (!res) {
						timelyList.push({
							merchantId: el.merchantId,
							isTimely: 1,
							merchantName: el.merchantName,
							isActive: false,
							list: [el]
						});
					}
				}
			}); // 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(merchantList, timelyList, timely, noTimely); // 海外购产品

			let hwg = noTimely.filter(it => it.isOtc == 5);
			if (timely.length > 0 && noTimely.length > 0) return req.alertMsg('及时达商品和非及时达商品不能一起下单');
			if (merchantList.length >= 2 || timelyList.length >= 2) return req.alertMsg('门店与门店之间不能一起下单'); //判断是否及时达订单

			let redirect = 'product/subOrder/subOrder?ids=' + ids.join(',');
			let orderType = 1;
			let merchantId = '';

			if (merchantList.length > 0) {
				merchantId = merchantList[0].merchantId;
			} // if (timely.length > 0) orderType = 5, merchantId = timelyList[0].merchantId;
			// if (hwg.length > 0) orderType = 10

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

		edit() {
			this.setData({
				isEdit: !this.isEdit
			});
		},

		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);
					that.setData({
						likeList: res
					});
				}
			);
		}
	}
};
</script>
<style>
@import './cart.css';
</style>
