<template>
  <!-- #ifdef H5 -->
	<zj-page-layout
		:hasFooter="goodsList.length ? true : false"
		:isScroll="true"
		:refresherTriggered="refresherTriggered"
		@refresherrefresh="refresherrefresh"
		@scrolltolower="scrolltolower">
		<template slot="header" v-if="goodsList.length">
			<view class="noticebar-container" v-if="isNoticebar">
				<uni-notice-bar v-if="noticeContent" scrollable="true" single="true" showClose="true" :text="noticeContent" background-color="#f6e6e7" color="#de3749" @close="isNoticebar = false"></uni-notice-bar>
			</view>
			<view class="top-container">
				<view class="total">共{{allNum}}件商品</view>
				<view v-if="!isEditor" @tap="isEditor = !isEditor">编辑</view>
				<view v-else @tap="isEditor = !isEditor">完成</view>
			</view>
		</template>

		<view class="list-container" v-if="goodsList.length">
			<block v-for="(item, index) in goodsList" :key='index'>
				<view class="item" @tap="$navPage(`/packageGoods/pages/detail?id=${item.goodsId}`)">
					<view class="check" v-if="item.selected" @tap.stop="selectList(index)">
						<text class="iconfont icon-danxuan2 active"></text>
					</view>
					<view class="check" v-else @tap.stop="selectList(index)">
						<text class="iconfont icon-danxuan"></text>
					</view>
					<image :src="item.goodsImg" mode="aspectFill" class="img"></image>
					<view class="right">
						<view class="main">
							<view class="title ellipsis-2">{{item.goodsName}}</view>
							<view class="des ellipsis">{{item.specValue}}</view>
							<view class="tags" v-if="item.promotionFullPiece">
								<view class="it">满件打折</view>
							</view>
						</view>
						<view class="last">
							<view class="price"><text>¥</text>{{item.price | priceFilter}}</view>
							<u-number-box
								@tap.stop
								v-model="item.num"
								:min="1"
								:buttonSize="26"
								iconStyle="font-size: 12px;"
								@change="changeCount($event, index)">
							</u-number-box>
						</view>

					</view>
				</view>
			</block>
		</view>
    <Loading
       v-if="!goodsList.length"
    	:type="3"
    	:loadStatus="2"
    	:showText="'购物车空空如也，去逛逛吧~'"
    />

		<view v-if="recomList.length">
			<view style="padding: 0 20rpx;">
				<u-divider text="可能你想要" lineColor="#cccccc" :hairline="false"></u-divider>
			</view>

			<view class="goods-waterfall-list">
				<view class="left">
					<block v-for="(item, index) in recomList" :key='index'>
						<view class="item" v-if="index%2==0" @tap="$navPage(`/packageGoods/pages/detail?id=${item.goodsId}`)">
							<view class="image">
								<image :src="item.imgUrl" mode="aspectFill" class="img"></image>
							</view>
							<view class="content">
								<view class="title ellipsis-2">{{item.goodsName}}</view>
								<view class="tags" v-if="item.tags1 && item.tags1.length > 0">
									<view class="it" v-for="(it, idx) in item.tags1" :key="idx">{{it}}</view>
								</view>
								<view class="tags2" v-if="(item.tags2 && item.tags2.length > 0) || item.promotionFullPiece || item.isTrade == 'YES'">
									<view class="it" v-if="item.promotionFullPiece">满件打折</view>
                  <view class="it" v-if="item.isTrade == 'YES'">以旧换新</view>
									<view class="it" v-for="(it, idx) in item.tags2" :key="idx">{{it}}</view>
								</view>
								<view class="price">
									<view class="price-1">¥{{item.goodsPrice | priceFilter}}</view>
									<view class="price-2">¥{{item.orgGoodsPrice | priceFilter}}</view>
								</view>
								<view class="text">销量：{{item.soldNum}}</view>
							</view>
						</view>
					</block>
				</view>
				<view class="right">
					<block v-for="(item, index) in recomList" :key='index'>
						<view class="item" v-if="index%2==1" @tap="$navPage(`/packageGoods/pages/detail?id=${item.goodsId}`)">
							<view class="image">
								<image :src="item.imgUrl" mode="aspectFill" class="img"></image>
							</view>
							<view class="content">
								<view class="title ellipsis-2">{{item.goodsName}}</view>
								<view class="tags" v-if="item.tags1 && item.tags1.length > 0">
									<view class="it" v-for="(it, idx) in item.tags1" :key="idx">{{it}}</view>
								</view>
								<view class="tags2" v-if="(item.tags2 && item.tags2.length > 0) || item.promotionFullPiece || item.isTrade == 'YES'">
									<view class="it" v-if="item.promotionFullPiece">满件打折</view>
                  <view class="it" v-if="item.isTrade == 'YES'">以旧换新</view>
									<view class="it" v-for="(it, idx) in item.tags2" :key="idx">{{it}}</view>
								</view>
								<view class="price">
									<view class="price-1">¥{{item.goodsPrice | priceFilter}}</view>
									<view class="price-2">¥{{item.orgGoodsPrice | priceFilter}}</view>
								</view>
								<view class="text">销量：{{item.soldNum}}</view>
							</view>
						</view>
					</block>
				</view>
			</view>

			<Loading
				:loadStatus="loadStatus"
				:dataList="recomList"
			/>
		</view>

		<template slot="footer">
			<view class="bottom-container">
				<view class="check" @tap="selectAll">
					<text class="iconfont icon-danxuan2 active" v-if="selectAllStatus"></text>
					<text class="iconfont icon-danxuan" v-else></text>
					<text class="text">全选</text>
				</view>
				<view class="right" v-if="!isEditor">
					<view class="price">
						<view class="row-1">
							<view class="it-1">已选{{totalNum}}件，</view>
							<view class="it-2">合计:</view>
							<view class="it-3"><text>¥</text>{{((totalPrice*1000) - (fullPieceDiscount*1000)) / 1000 | priceFilter}}</view>
						</view>
						<view class="row-2" v-if="fullPieceItem">
							<view class="it-1">满{{fullPieceItem.satisfyNum}}件打{{fullPieceItem.discountRate * 10}}折，</view>
							<view class="it-2">共减<text>¥{{fullPieceDiscount}}</text></view>
						</view>
					</view>
					<u-button type="primary" text="去结算" @click="toOrder"></u-button>
				</view>
				<view class="right" v-else>
					<u-button type="primary" plain text="删除" @click="clickDelete"></u-button>
				</view>
			</view>
		</template>
	</zj-page-layout>
  <!-- #endif -->

  <!-- #ifndef H5 -->
  <web-view :src="webViewHref(`/packageGoods/pages/cart`, pam, crossPagePam)" @message="crossPage.$listener"></web-view>
  <!-- #endif -->
</template>

<script>
  // #ifdef H5
	export default {
		data() {
			return {
				goodsList: [],
				totalNum: 0, // 已选商品的数量
				totalPrice: 0, // 已选商品的总价
				allNum: 0, // 所有商品的数量
				selectAllStatus: true, // 全选状态，默认全选

				isEditor: false, // 是否编辑

				isNoticebar: false, // 是否显示通告栏
				noticeContent: '', // 公告内容

				fullPieceList: [],
				fullPieceItem: null,
				fullPieceNum: 0,
				fullPiecePrice: 0,
				fullPieceDiscount: 0,

				recomList: [], // 好物推荐列表

				refresherTriggered: false, // 下拉刷新状态
				pageNum: 1,
				loadStatus: 0,
			}
		},

		onShow() {
			this.getGoodsList();
		},

		onLoad() {
			this.getNoticebar();
			this.getRecomList();
		},

		methods: {
			// 获取公告栏
			getNoticebar() {
				this.$api.get('/shpping/cart/notice')
        .then(res => {
					this.noticeContent = res.data;
					this.isNoticebar = res.data ? true : false;
				})
			},

			// 滚动到底部
			scrolltolower(e) {
				if (this.loadStatus === 0) {
					this.pageNum++;
					this.getRecomList();
				}
			},

			// 触发下拉刷新
			async refresherrefresh(e) {
				this.refresherTriggered = true;
				this.refreshList();
			},

			refreshList() {
				this.pageNum = 1;
				this.recomList = [];
				this.getRecomList();
			},

			// 获取推荐商品列表
			getRecomList() {
				this.loadStatus = 1;
				this.$api.get('/goods/list/page', {
          pageNum: this.pageNum,
          pageSize: 6,
          isRecommend: true
				}).then(res => {
					this.loadStatus = 0;
					let list = res.data.records;
					if (list.length < 6) {
						this.loadStatus = 2;
					}
					this.recomList = this.recomList.concat(list);
				}).catch(() => {
					this.loadStatus = 2;
				}).finally(res => {
					this.refresherTriggered = false;
				})
			},

			// 获取商品列表
			getGoodsList() {
				this.$api.get('/shpping/cart/list', {
					userId: this.$store.state.user.userId
				}).then(res => {
					this.goodsList = res.data.shoppingCartLists;
					this.fullPieceList = res.data.promotionFullPieceItems || [];
					this.allNum = res.data.totalNum;
					this.goodsList.forEach((item, index) => {
						item.selected = true;
					})
					this.selectAllStatus = true;
					this.getTotalPrice();
				})
			},

			findNearestNumber(arr, target) {
			    let result = 0;
			    for (let i = 0; i < arr.length; i++) {
			        if (Math.abs(arr[i] - target) < Math.abs(result - target) && target >= arr[i]) {
			            result = arr[i];
			        };
			    };
			    return result;
			},

			// 统计总价
			getTotalPrice() {
				let goodsList = this.goodsList;
				let total_num = 0;
				let total_price = 0;
				let fullPiece_item = null; // 满件打折活动
				let fullPiece_num = 0; // 满件打折活动：数量
				let fullPiece_price = 0; // 满件打折活动：总金额
				let fullPiece_discount = 0; // 满件打折活动：优惠金额
				// 统计总金额
				for(let i = 0; i<goodsList.length; i++) {
					// 判断选中才会计算价格
					if(goodsList[i].selected) {
						// 所有价格加起来
						total_price += goodsList[i].num * goodsList[i].price;
						total_num += Number(goodsList[i].num);

						// 如果满件打折
						if(this.fullPieceList.length > 0 && goodsList[i].promotionFullPiece) {
							fullPiece_num += goodsList[i].num;
							fullPiece_price += goodsList[i].num * goodsList[i].price;
						}
					}
				}

				if(this.fullPieceList.length > 0 && fullPiece_num > 0) {
					// 找到对应的满件打折活动
					let nums = this.fullPieceList.map(item => {
						return item.satisfyNum;
					})
					let thisNum = this.findNearestNumber(nums, fullPiece_num);
					fullPiece_item = this.fullPieceList.find(item => {
						return item.satisfyNum === thisNum;
					}) || null
					// 计算优惠金额
					if(fullPiece_item) {
						fullPiece_discount = fullPiece_price - (fullPiece_price * fullPiece_item.discountRate);
					}
				}

				// 赋值到data中渲染到页面
				this.goodsList = goodsList;
				this.totalNum = total_num;
				this.totalPrice = total_price.toFixed(2);

				this.fullPieceItem = fullPiece_item;
				this.fullPieceNum = fullPiece_num;
				this.fullPiecePrice = fullPiece_price.toFixed(2);
				this.fullPieceDiscount = fullPiece_discount.toFixed(2);
			},

			// 选择事件
			selectList(index) {
				// 获取购物车列表
				let goodsList = this.goodsList;
				// 获取当前商品的选中状态
				let selected = goodsList[index].selected;
				// 改变状态
				goodsList[index].selected = !selected;
				this.goodsList = goodsList;

				// 改变全选状态
				for (var i=0; i<this.goodsList.length; i++){
					// 当状态为全选时，每个元素其中有一个为false，则取消全选
					// 当状态为非全选时，每个元素都为true，则全选
					if(this.selectAllStatus){
						if(!this.goodsList[i].selected){
							this.selectAllStatus = false;
							break;
						}
					}else {
						if(this.goodsList[i].selected){
							this.selectAllStatus = true;
						}else {
							this.selectAllStatus = false;
							break;
						}
					}
				}

				// 重新获取总价
				this.getTotalPrice();
			},

			// 全选事件
			selectAll(e) {
				// 是否全选状态
				let selectAllStatus = this.selectAllStatus;
				selectAllStatus = !selectAllStatus;
				let goodsList = this.goodsList;
				for (let i = 0; i < goodsList.length; i++) {
					// 改变所有商品状态
					goodsList[i].selected = selectAllStatus;
				}
				this.selectAllStatus = selectAllStatus;
				this.goodsList = goodsList;
				// 重新获取总价
				this.getTotalPrice();
			},

			// 更改数量
			changeCount(e, index) {
				this.goodsList[index].num = e.value;
				this.initCart();
			},

			// 修改数量后更新购物车数据
			initCart() {
				let buyGoods = [];
				this.goodsList.forEach((item, index)=> {
					let goodsItem = {
						goodsId: item.goodsId,
						goodsSpecId: item.goodsSpecId,
						num: item.num,
						shoppingCartId: item.shoppingCartId,
						secKillId: item.secKillId || '',
						promotionGroupId: item.promotionGroupId || '',
					};
					buyGoods.push(goodsItem);
				})
				this.$api.postJson('/shpping/cart/add', {
          userId: this.$store.state.user.userId,
          buyGoods: buyGoods,
				}).then(res => {
					this.allNum = res.data.totalNum;
					this.getTotalPrice();
				})

			},


			// 点击删除
			clickDelete() {
				let delIds = [];
				for(let i = 0; i < this.goodsList.length; i++) {
					if(this.goodsList[i].selected) {
						delIds.push(this.goodsList[i].shoppingCartId)
					}
				}
				if(delIds.length < 1) {
					return this.$toast('至少选择一件商品');
				}

				this.$modal({
					content: '确定要删除选中的商品吗？'
				}).then(() => {
					this.confirmDelete();
				}).catch(() => {})
			},

			// 确认删除
			confirmDelete() {
				let delIds = [];
				for(let i = 0; i < this.goodsList.length; i++) {
					if(this.goodsList[i].selected) {
						delIds.push(this.goodsList[i].shoppingCartId)
					}
				}
				this.$api.post('/shpping/cart/remove', {
          shoppingCartIds: delIds,
          userId: this.$store.state.user.userId
				}).then(res => {
					this.isEditor = false;
					this.$successToast('删除成功');
					this.getGoodsList();
				})
			},

			// 去结算
			toOrder() {
				let buyList = [];
				this.goodsList.forEach((item, index)=> {
					if(item.selected) {
						let goodsItem = {
							goodsId: item.goodsId,
							goodsSpecId: item.goodsSpecId,
							num: item.num,
							shoppingCartId: item.shoppingCartId,
							secKillId: item.secKillId || '',
							promotionGroupId: item.promotionGroupId || '',
						};
						buyList.push(goodsItem);
					}
				})
				if(buyList.length < 1) {
					return this.$toast('至少选择一件商品');
				}

        this.$setStorage('goodsBuyList', buyList);

				// 跳转结算页面
				this.$navToPage({
					url: '/packageGoods/pages/order'
				})
			},
		}
	}
  // #endif
  // #ifndef H5
  export default {
    data() {
      return {
        pam: {},
      }
    },
    onLoad(pam) {
      this.pam = pam;
    }
  }
  // #endif
</script>

<style lang="scss">
	.top-container {
		padding: 0 20rpx;
		box-sizing: border-box;
		background: #FFFFFF;
		height: 88rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .1), 0 0 3px 0 rgba(0, 0, 0, .2);
		.total {
			font-size: 32rpx;
		}
	}

	.list-container {
		padding: 20rpx;
		.item {
			margin-bottom: 20rpx;
			border-radius: 10rpx;
			padding: 20rpx 20rpx;
			display: flex;
			align-items: center;
			background: #FFFFFF;
			.check {
				.iconfont {
					font-size: 40rpx;
					color: #999999;
					&.active {
						color: $theme-color;
					}
				}
			}
			.img {
				width: 180rpx;
				height: 180rpx;
				display: block;
				margin: 0 20rpx;
				flex-shrink: 0;
			}
			.right {
				flex: 1;
				display: flex;
				justify-content: space-between;
				flex-direction: column;
				min-height: 180rpx;
				.main {
					display: flex;
					justify-content: space-between;
					flex-direction: column;
					.title {
						line-height: 36rpx;
						font-weight: 600;
					}
					.des {
						font-size: 28rpx;
						color: $sec-font;
						line-height: 28rpx;
						margin-top: 10rpx;
					}
					.tags {
						display: flex;
						flex-wrap: wrap;
						margin-top: 14rpx;
						.it {
							font-size: 20rpx;
							line-height: 20rpx;
							padding: 4rpx 6rpx;
							margin-right: 10rpx;
							border: 1px solid #FE781F;
							color: #FE781F;
							box-sizing: border-box;
							margin-bottom: 10rpx;
							display: flex;
							align-items: center;
							border-radius: 10rpx;
						}
					}
				}
				.last {
					display: flex;
					justify-content: space-between;
					align-items: center;
					.price {
						color: $minor-color;
						font-weight: 500;
						font-size: 32rpx;
						text {
							font-size: 24rpx;
						}
					}
					::v-deep .u-number-box {
						.u-number-box__minus, .u-number-box__plus {
							width: 26px;
						}
					}
				}
			}
		}
	}

	.bottom-container {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx;
		.check {
			display: flex;
			align-items: center;
			.iconfont {
				font-size: 40rpx;
				color: #999999;
				margin-right: 12rpx;
				&.active {
					color: $theme-color;
				}
			}
		}
		.right {
			display: flex;
			align-items: center;
			.price {
				display: flex;
				flex-direction: column;
				margin-right: 20rpx;
			}
			.row-1 {
				font-size: 28rpx;
				display: flex;
				align-items: center;
				justify-content: flex-end;
				line-height: 36rpx;
				.it-1 {
					color: #999999;
				}
				.it-2 {
					margin-right: 4rpx;
				}
				.it-3 {
					color: $minor-color;
					font-weight: 500;
					font-size: 36rpx;
					text {
						font-size: 28rpx;
					}
				}
			}
			.row-2 {
				font-size: 24rpx;
				color: #999999;
				display: flex;
				align-items: flex-end;
				justify-content: flex-end;
				margin-top: 8rpx;
				line-height: 28rpx;
				.it-2 {
					display: flex;
					align-items: center;
					color: $minor-color;
					text {
						font-size: 28rpx;
						font-weight: 500;
						margin-left: 4rpx;
					}
				}
			}
			::v-deep .u-button {
				width: 170rpx;
				border-radius: 80rpx;
			}
		}
	}
</style>
