<template>
	<view class="div cart-list-wrapper" :style="'padding-top:'+navHeight+'px'">
		<checkbox-group @change="changeSingleStatu2" >
			<view class="div cart-list" v-for="(cartItem, i) in cartList" :key="i">
                <flex-line class="store-info" :show-border="true">
                	<view class="div wrapper">
                		<view class="div list-checkbox">
                			<checkbox
                					class="checkbox"
                					:id="'store'+cartItem.store_id"
                    :value="cartItem.store_id"
                					:checked="cartItem.checked"
                					:disabled="!isCheckedAll && cartItem.disabled"
                			/>
                			<label class="label" :class="{'checked':cartItem.checked}" :for="'store'+cartItem.store_id"><text class="span iconfont">&#xe69b;</text></label>
                		</view>
                		<text class="span store-name">{{cartItem.store_name}}</text>
                	</view>
                	<text slot="right" v-if="cartItem.voucher_list && cartItem.voucher_list.length" class="span voucher" @click="goVoucher(i)">领券</text>
                </flex-line>
                <checkbox-group @change="changeSingleStatu(i,$event)" >
                	<view class="div list" v-for="(item, index) in cartItem.goods" :key="index">
                       <view class="div list-checkbox">
                            <checkbox
                                class="checkbox"
                                :id="'store'+cartItem.store_id+'goods'+index"
                                :value="item.goods_id"
                                :checked="item.checked"
                                :disabled="!isCheckedAll && item.disabled"
                            />
                            <label class="label" :class="{'checked':item.checked}" :for="'store'+cartItem.store_id+'goods'+index"><text class="span iconfont">&#xe69b;</text></label>
                        </view> 
                        <view class="div list-item" @click="goDetail(item.goods_id)">
                        	<view class="div item">
                        		<view class="div ui-image">
                        			<image mode="aspectFit" class="img" :src="item.goods_image_url" />
                        			<text v-if="item.goods_storage == 0" class="span stock-info"
                        				>已售罄</text
                        			>
                        			<text v-if="item.goods_state!=1" class="span stock-info"
                        			>已下架</text>
                        			<text
                        				v-if="
                        					item.goods_state==1 && item.goods_storage > 0 && item.goods_storage <= 10
                        				"
                        				class="span stock-info"
                        				>仅剩{{ item.goods_storage }}件</text
                        			>
                        			<text
                        				class="span promos"
                        				v-if="item.xianshi_info"
                        				>促销</text
                        			>
                        		</view>
                        		<view class="div list-info">
                        			<view class="div product-header">
                        				<text
                        					class="h3 product-title"
                        					v-bind:class="{ 'disabled-list': item.disabled }"
                        				>
                        					{{ item.goods_name }}
                        				</text>
                        			</view>
                        			<text class="h3 property-info"></text>
                        			<view v-if="item.bl_id" class="div bl_goods_list">
                        				<view class="div bl_goods">+</view>
                        				<view class="div" v-for="(bl_goods,index) in item.bl_goods_list" :key="index">
                        					<view class="div bl_goods" v-if="bl_goods.goods_id!=item.goods_id"><image mode="aspectFit" class="img" :src="bl_goods.goods_image_url" /></view>
                        				</view>
                        			</view>
                        			<view class="div info-price">
                        				<view class="p"
                        					v-bind:class="{ 'disabled-list': item.disabled }"
                        				>
                        					￥{{ item.goods_price }}
                        				</view>
                        				<view class="div ui-number" v-if="!item.disabled">
                        					<view
                        						class="div reduce ui-common"
                        						@click.stop="reduceNumber(item.cart_id, item.goods_num,i,index)"
                        						v-bind:class="{ 'reduce-opacity': item.goods_num <= 1 }"
                        					>
                        						-
                        					</view>
                        					<input
                                            @click.stop
                        						type="number"
                        						min="1"
                        						class="number"
                        						value="1"
                                                @input="printDigitNum(item.cart_id,$event, i,index)"
                        						v-model="item.goods_num"
                        						readonly="true"
                        					/>
                        					<view
                        						class="div add ui-common"
                        						@click.stop="
                        							addNumber(
                        								item.cart_id,
                        								item.goods_num,
                        								i,
                        								index
                        							)
                        						"
                        					>
                        						+
                        					</view>
                        				</view>
                        			</view>
                        		</view>
                        	</view>
                        </view>
                    </view>
                    
                	
                </checkbox-group>
            </view>
            
		
	</checkbox-group>
	</view>
</template>

<script>
import { urlencode } from '@/util/common'
import { mapState, mapMutations } from 'vuex'
import flexLine from '../../../flexLine'
import {
  cartGet,
  cartDelete,
  cartUpdate,
  cartQuantity
} from '../../../../api/homecart'

export default {
  props: {
    isCheckedAll: {
      type: Boolean,
      default: false
    }
  },
	components:{flexLine},
  data () {
    return {
      navHeight: 0,
      cartList: [], // 购物车列表
      indicator: { spinnerType: 'fading-circle' },
      totalPrice: 0, // 购物车总价
      cartId: '', // 购物车中选中的商品
      totalAmount: 0, // 购物车数量
      promosIds: [] // 促销信息IDS
    }
  },
  created () {
    this.getCartList(true)
  },
  mounted: function() {
    // #ifdef  MP-WEIXIN
    this.navHeight = uni.getMenuButtonBoundingClientRect().height
    // #endif
  },
  methods: {
    ...mapMutations({
      getAmount: 'calculationAmount',
      getPrice: 'calculationPrice',
      setCartNumber: 'setCartNumber',
      saveSelectedCartGoods: 'saveSelectedCartGoods',
      saveVoucher: 'saveVoucher'
    }),
    printDigitNum(id,e,i,index){
        if(e.detail.value != ''){
             this.updateCartQuantity(id, e.detail.value, i, index)
        }
    },
    /*
		 * getCartList: 获取购物车列表
		 */
    getCartList (value) {
      cartGet().then(res => {
        if (res && res.result.cart_val.length > 0) {
          this.cartList = Object.assign([], res.result.cart_val)
          for (var i in this.cartList) {
              this.cartList[i].store_id = String(this.cartList[i].store_id)
              for(var j in this.cartList[i].goods){
                  this.cartList[i].goods[j].goods_id = String(this.cartList[i].goods[j].goods_id)
              }
          }
          this.addChecked(value,this.isCheckedAll)
          this.renderCart()
        } else {
          this.cartList = []
          this.getAmount(0)
          this.getPrice(0.0)
        }
        uni.$emit('list-is-empty', this.cartList)
      })
    },

    /*
		 * addChecked: 为每个商品添加checked 属性
		 * @param: isSelectedall 是否选中商品 Boolean
		 */
    addChecked (isSelectedall,isCheckedAll) {
      let temp = this.cartList
      let total_disabled_length = 0
      for (var j in temp) {
        let list = temp[j].goods
		  let k = 0
		  let disabled_length = 0
        for (var i in list) {
        	if (list[i].goods_storage == 0 || list[i].goods_state != 1) {
            list[i].disabled = true
            disabled_length++
          }
          if (!isCheckedAll && list[i].disabled) {
            list[i].checked = false
			  k++
          } else {
            list[i].checked = isSelectedall
          }
        }
		  temp[j].disabled = (disabled_length == list.length)
		  if (temp[j].disabled) {
			  total_disabled_length++
		  }
		  temp[j].checked = (k == list.length) ? false : isSelectedall
      }
      this.cartList = Object.assign([], temp)
      if (temp.length == total_disabled_length) {
        uni.$emit('change-footer-status', false)
		  uni.$emit('change-footer-disabled', true)
      }
    },

    /*
		 *  renderCart: 修改商品数量和点击是否选中后 重新计算商品价格和数量
		 */
    renderCart () {
      let temp = this.cartList
      this.promosIds = []
      let cartGoods = []
      let totalAmount = 0
      let totalPrice = 0
      for (var j in temp) {
        let data = temp[j].goods
        for (var i in data) {
          if (data[i].checked) {
            totalAmount += parseInt(data[i].goods_num)
            totalPrice += parseInt(data[i].goods_num) * parseFloat(data[i].goods_price)
            cartGoods.push(data[i].cart_id + '|' + data[i].goods_num)
          }
        }
      }
      this.cartId = cartGoods.toString()
      this.totalPrice = totalPrice.toFixed(2)
      this.totalAmount = totalAmount
      uni.$emit('calcu-cart-data', { totalPrice: this.totalPrice, totalAmount: this.totalAmount, cartId: this.cartId })
    },

    /*
		 * deleteSelected: 删除购物车数据
		 */
    deleteSelected () {
      let temp = this.cartList
      let deleteGoods = []
      this.promosIds = []
      for (var j in temp) {
        let data = temp[j].goods
        for (var i in data) {
          if (data[i].checked) {
            deleteGoods.push(data[i].cart_id)
          }
        }
      }
      if (deleteGoods.length > 0) {
        deleteGoods = deleteGoods.toString()
      } else {
        uni.showToast({icon:'none',title: '当前没有可删除的商品'})
        return
      }
      uni.showLoading({ title: '加载中' })
      cartDelete(deleteGoods).then(res => {
        if (res) {
          this.getCartList(false)
          uni.hideLoading()
        }
      })
    },

    /*
		 *  changeSingleStatu: 改变单个商品是否选中的状态, 然后重新获取商品的件数和价格
		 */
    changeSingleStatu (j,e) {
      var value=e.detail.value
      let data = this.cartList
      let length = 0
      let totalLength = 0
      let status = false
      	let list = data[j].goods
		  let k = 0
		  for (var i in list) {
			  if (value.indexOf(list[i].goods_id)>-1) {
          list[i].checked=true
				  length = length + 1
				  k++
			  }else{
          list[i].checked = false
        }
		  }
		  if (k == list.length) {
			  data[j].checked = true
		  } else {
			  data[j].checked = false
		  }
		  totalLength += list.length
      if (length == totalLength) {
        status = true
      } else {
        status = false
      }
      uni.$emit('change-footer-status', status)
      if (!this.isCheckedAll) {
        this.renderCart()
      }
      this.cartList = Object.assign([], data)
    },
	  changeSingleStatu2 (e) {
          var value=e.detail.value
		  let data = this.cartList
		  let length = 0
		  let totalLength = 0
		  let status = false
          
          for(var j in data){
            let list = data[j].goods
            let k = 0
            for (var i in list) {
                if (!this.isCheckedAll && list[i].disabled) {
                    list[i].checked = false
                    data[j].checked = false
                    k++
                } else {
                    list[i].checked = value.indexOf(data[j].store_id)>-1?true:false
                    data[j].checked = value.indexOf(data[j].store_id)>-1?true:false
                }
            }  
          }
		  
          for (var q in data) {
			  if (value.indexOf(data[q].store_id)>-1) {
				  length += data[q].goods.length
			  }
			  totalLength += data[q].goods.length
		  }
		  if (length == totalLength) {
			  status = true
		  } else {
			  status = false
		  }

		  uni.$emit('change-footer-status', status)
		  if (!this.isCheckedAll) {
			  this.renderCart()
		  }
		  this.cartList = Object.assign([], data)
	  },
    /*
		 *  reduceNumber: 数量减少
		 *  @param: id 当前减少的购物车id
		 *  @param: amount 数量
		 *  @param： i 当前减少的购物车组的index
		 *  @param： index 当前减少的购物车的index
		 */
    reduceNumber (id, amount, i, index) {
      if (amount > 1) {
        amount--
        this.updateCartQuantity(id, amount, i, index)
      } else {
        uni.showToast({icon:'none',title: {
          message: '受不了了， 宝贝不能再少了'
        }})
      }
    },

    /*
		 *  addNumber: 数量增加
		 *  @param: id 当前增加的购物车id
		 *  @param: amount 数量
		 *  @param： i 当前增加的购物车组的index
		 *  @param： index 当前增加的购物车的index
		 */
    addNumber (id, amount, i, index) {
      amount++
      this.updateCartQuantity(id, amount, i, index)
    },

    /*
		 * updateCartQuantity: 商品数量加减更新数
		 * @param: id 当前减少的购物车id
		 * @param: amount 数量
		 * @param： i 当前购物车组的index
		 * @param： index 当前购物车的index
		 */
    updateCartQuantity (id, amount, i, index) {
	  uni.showLoading({ title: '加载中' })
      cartUpdate(id, amount).then(
        res => {
          if (res) {
            uni.hideLoading()
            this.cartList[i].goods[index].goods_num = amount
			this.cartList[i].goods[index].goods_price = res.result.goods_price
            this.renderCart()
            // this.getCartNumber()
          }
        },
        error => {
          uni.showToast({icon:'none',title: error.message})
          uni.hideLoading()
        }
      )
    },
    /*
		 * getCartNumber： 获取购物车列表
		 */
    getCartNumber () {
      cartQuantity().then(res => {
        if (res) {
          this.setCartNumber(res.quantity)
        }
      })
    },

    /*
		 *  goDetail: 跳转到详情
		 */
    goDetail (id) {
      uni.navigateTo({ url: '/pages/home/goodsdetail/Goodsdetail'+'?'+urlencode( { goods_id: id } )})
    },
	  goVoucher (index) {
		  this.saveVoucher(this.cartList[index].voucher_list)
		  uni.navigateTo({ url: '/pages/home/storedetail/StoreVoucher' })
	  }

  }
}
</script>

<style lang="scss" scoped>
.cart-list-wrapper {
	overflow-y: auto;
	position: fixed;
	width: 100%;
  bottom: $footerHeight;
	padding-bottom: constant(safe-area-inset-bottom);/*兼容 IOS<11.2*/padding-bottom: env(safe-area-inset-bottom);/*兼容 IOS>11.2*/
	top: $headerHeight;
  margin-top:var(--status-bar-height);
	.cart-list{margin-bottom:$modelSpace;background:#fff;}
	.store-info{border-bottom:1px dashed #eee;display:flex;margin-left:$pageSpace;margin-right:$pageSpace;align-content: center;align-items: center;
	.wrapper{display: flex;align-items: center}
		.store-name{font-size:$h2;line-height: 2rem;flex:1;}
		.voucher{width:2rem;font-size:$subFontSize;color:$primaryColor;border:1px solid $primaryColor;text-align: center;border-radius:.1rem;}
	}
	.list-checkbox {
		width: 1rem;
		height: 1rem;
		flex-basis: 1rem;
		flex-shrink: 0;
		position: relative;
		margin-right:0.25rem;
		.label {
      padding:0;
			position: absolute;
			left:0;
			top: 0;
			width: 1rem;
			height: 1rem;
			display: inline-block;
			border-radius:50%;
			border:1px solid #333;
			box-sizing:border-box;
			.iconfont{display: none;line-height: 1rem;text-align: center;}
      &.checked{
      	border-color:$primaryColor;
      	background-color:$primaryColor;
      	.iconfont{display: block;color:#fff}
      }
		}
		.checkbox {
			position: relative;
			width: 1rem;
			margin: 0;
			opacity: 0;
			background-color: #fff;
		}
	}
	.list {
		background-color: #fff;
		padding: 0.6rem;
		display: flex;
		align-content: center;
		align-items: center;

		.list-item {
			display: flex;
			width: 100%;
			flex-direction: column;
			.div.item {
				display: flex;
				width: 100%;
				.div.ui-image {
					flex-shrink: 0;
					width: 4.5rem;
					height: 4.5rem;
					flex-basis: 4.5rem;
					position: relative;
					.img {
						width: 100%;
						height: 100%;
						border-radius: 0.4rem;
					}
					.span.promos {
						position: absolute;

						width: 1.8rem;
						height: 0.95rem;
						color: #ffffff;
						font-size:$h6;
						top: 0;
						/* left: 0; */
						background-size: cover;
						font-weight: 100;
						line-height: 0.95rem;
						text-align: left;
						padding-left:0.25rem;
					}
					.span.stock-info {
						position: absolute;
						height: 1rem;
						background: rgba(243, 244, 245, 1);
						line-height: 1rem;
						text-align: center;
						font-size:$subFontSize;
						color: $primaryColor;
						width: 100%;
						bottom: 0;
						left: 0;
					}
				}
				.div.list-info {
					margin-left: 0.4rem;
					width: 100%;
					display: flex;
					flex-direction: column;
					align-content: center;
					justify-content: space-between;
					.product-header {
						display: flex;
						align-items: center;
						.promos-icon {
							width: 0.8rem;
							height: 0.8rem;
							margin-right: 0.2rem;
						}
						.product-title {
							font-size: $subFontSize;
							line-height:1rem;
							height: 2rem;
							padding: 0;
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 2;
							overflow: hidden;
							&.disabled-list {
								color: #a4aab3;
							}
						}
					}
					.h3 {
						font-size:$subFontSize;
						color: rgba(78, 84, 93, 1);
						padding: 0;
						margin: 0;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 2;
						overflow: hidden;
						&.disabled-list {
							color: #a4aab3;
						}
					}
					.h3.property-info {
						font-size:$fontSize;
						color: #7c7f88;
					}
					.div.info-price {
						width: 100%;
						display: flex;
						justify-content: space-between;
						align-content: flex-end;
						align-items: flex-end;
						.p {
							font-size: $mainFontSize;
							color: $primaryColor;
							padding: 0;
							margin: 0;
							display: inline-block;
							&.disabled-list {
								color: #a4aab3;
							}
						}
					}
					.div .ui-number {
						height: 1.2rem;
						display: flex;
						border-radius: 0.15rem 0 0 0.15rem;
						input,
						.div {
							height: 1.2rem;
							text-align: center;
							color: #404245;
							display: inline-block;
							padding: 0;
							margin: 0;
							border: 0;
							outline-offset: 0;
						}
						.ui-common {
							line-height: 1.2rem;
							width: 1.3rem;
							height: 1.2rem;
							border: 1px solid #c7c7cd;
							cursor: pointer;
						}
						.reduce {
							border-right: 0;
						}
						.reduce-opacity {
							opacity: 0.4;
						}
						.add {
							border-left: 0;
						}
						.number {
							width: 1.3rem;
							border: 1px solid #c7c7cd;
							border-radius: 0;
							border-image-width: 0;
							box-shadow: 0;
							vertical-align: bottom;
							&:focus {
								outline: none;
							}
						}
					}
				}
			}
			.p.list-promotion-info {
				margin-top: 0.6rem;
				padding: 0.4rem 0;
				line-height: auto;
				font-size:$h6;
				color: #000;
				background: #f8f8f8;
				width: 100%;
				.span {
					border: 1px solid $primaryColor;
					padding: 1px 0.2rem;
					border-radius: 0.1rem;
					font-size:$h6;
					color: $primaryColor;
					margin: 0 0.4rem;
					text-align: center;
				}
			}
		}
	}
}
.has-bottom {
	bottom: 4.7rem;
}
	.bl_goods_list{overflow: hidden;
		.bl_goods{float: left;height: 2rem;line-height: 2rem;
			.img{width:2rem;height: 2rem;margin-right: .2rem;}
		}
	}
</style>
