<template>
  <view class="pageBg">
    <block v-if="emptyType==0">
      <block v-if="isLogin">
        <view v-if="!(dataList.length<=0 && invalidList.length<=0)" class="coupon">
          <view class="coupon_count">
            <!-- 您当前有<text class="count">{{0}}</text>张优惠券 -->
          </view>
          <view @tap="tapShowEdit" class="coupon_handle">{{isEdit?'删除完成':'批量删除'}}</view>
        </view>

        <DtShopCarGoods ref="dtShopCarGoods" :isEdit="isEdit" 
          :dataList.sync="dataList"
          :invalidList.sync="invalidList"
          :flag.sync="flag"
          @wxchecked="onWxChecked"
          @wxdelchecked="onWxDelChecked"
          @delete="onDeteleItem"
        />
        
        <view v-if="dataList.length<=0 && invalidList.length<=0" class="no-data-wrap">
          <image class="no-data" src="http://139.9.103.171:1888/img/image/noData.png" mode="widthFix"></image>
          <view class="no-data-tips">购物车空空如也，快去逛逛</view>
          <button @tap="tapToIndex" class="btn-base">去逛逛</button>
        </view>

        <view v-if="recomendList.length>0" clsss="recommend">
          <DtRecommendWrap title="新邻推荐" />
          <DtRecommendGoodsList :dataList="recomendList" />
        </view>
        <block v-if="!(dataList.length<=0 && invalidList.length<=0)">
          <view class="bottomHeight"></view>
          <view class="bottom">
            <view v-if="isEdit" @tap="tapCheckAll" class="bottomLeft">
              <image v-if="wxDelCheckAll" class="operation_icon" src="http://139.9.103.171:1888/img/image/selected_icon.png"></image>
              <image v-else class="operation_icon" src="http://139.9.103.171:1888/img/image/no_selected_icon.png"></image>
              <text class="hasSelected">已选（{{wxDelCheckedNum}}）</text>
            </view>
            <view v-else @tap="tapCheckAll" class="bottomLeft">
              <image v-if="wxCheckAll" class="operation_icon" src="http://139.9.103.171:1888/img/image/selected_icon.png"></image>
              <image v-else class="operation_icon" src="http://139.9.103.171:1888/img/image/no_selected_icon.png"></image>
              <text class="hasSelected">已选（{{wxCheckedNum}}）</text>
            </view>
            <view class="bottomRight">
              <view v-if="isEdit" @tap="tapClearCheck" class="settlement">删除</view>
              <block v-else>
                <view class="price"><text class="sign">¥</text>{{totalPrice|moneyEx}}</view>
                <view @tap="tapCheckCart" class="settlement">结算</view>
              </block>
            </view>
          </view>
        </block>

      </block>
      <view v-else class="no-data-wrap" style="height:100vh;padding:0">
        <image class="no-data" src="http://139.9.103.171:1888/img/image/noData.png" mode="widthFix"></image>
        <view class="no-data-tips">购物车空空如也，快去逛逛</view>
        <button @tap="tapToIndex" class="btn-base">去逛逛</button>
      </view>
    </block>
    <!-- 登录弹窗 -->
    <DtLogin ref="dialogLogin" @signIn="onSignIn" />
  </view>
</template>
<script>
import DtRecommendWrap from '../comps//dt_recommend_wrap.vue'
import DtRecommendGoodsList from '../comps//dt_recommend_goods_list.vue'
import DtShopCarGoods from '../comps//dt_shop_car_goods.vue'
import DtLogin from '../comps//dt_login.vue'
export default {
  components: {
    DtRecommendWrap,
    DtRecommendGoodsList,
    DtShopCarGoods,
    DtLogin
  },
  data() {
    return {
      totalPrice: 0,
      wxDelCheckedNum: 0,
      wxCheckedNum: 0,
      wxCheckAll: false,
      wxDelCheckAll: false,
      respDetail: {},
      dataList: [],
      invalidList: [],
      recomendList: [],
      isEdit: false,
      memberId: 0,
      isLogin: false,

      flag:false,
    }
  },
  methods: {
    tapToIndex() {
		uni.switchTab({
			url:"/pages/life/life"
		})
    },
    
    // 登录成功响应事件
    onSignIn(resp) {
      console.log(143, resp)
      this.$util.refreshPage(['/pages/home', '/pagesM/pages/mine'])
      this.onPullDownRefreshPage()
    },
    onWxChecked(total, wxCheckedNum) {
      this.totalPrice = total
      this.wxCheckedNum = wxCheckedNum
      this.wxCheckAll = wxCheckedNum == this.dataList.length
    },
    onWxDelChecked(wxDelCheckedNum) {
      console.log(117,wxDelCheckedNum)
      this.wxDelCheckedNum = wxDelCheckedNum
      this.wxDelCheckAll = wxDelCheckedNum == this.dataList.length
    },
    onDeteleItem({ totalPrice, wxCheckedNum, wxDelCheckedNum, wxCheckAll, wxDelCheckAll }){
      console.log(118,{totalPrice, wxCheckedNum, wxDelCheckedNum, wxCheckAll, wxDelCheckAll})
      this.totalPrice = totalPrice
      this.wxCheckedNum = wxCheckedNum
      this.wxDelCheckedNum = wxDelCheckedNum
      this.wxCheckAll = wxCheckAll
      this.wxDelCheckAll = wxDelCheckAll
    },
    tapCheckAll() {
       if(this.flag){
        return
      }
      let list = this.dataList.slice(0)
      let totalPrice = 0
      list.map((item) => {
        totalPrice += item.skuDetail.price * item.skuDetail.quantity
        if (this.isEdit) {
          item.wxdelChecked = !this.wxDelCheckAll
        } else {
          item.wxChecked = !this.wxCheckAll
        }
        return item
      })
      // console.log(125,totalPrice)
      if (this.isEdit) {
        this.wxDelCheckedNum = !this.wxDelCheckAll ? list.length : 0
        this.wxDelCheckAll = !this.wxDelCheckAll
      } else {
        this.wxCheckedNum = !this.wxCheckAll ? list.length : 0
        this.wxCheckAll = !this.wxCheckAll
        if (this.wxCheckAll) { // 选择全部
          this.totalPrice = totalPrice
        } else {// 全不选
          this.totalPrice = 0
        }
      }
      this.dataList = list
    },
    // 显示管理
    tapShowEdit() {
      this.isEdit = !this.isEdit
    },
    // 批量删除
    async tapClearCheck() {
       if(this.flag){
        return
      }
      let skuIds = []
      let list = this.dataList.slice(0)
      list.forEach((item) => {
        if (item.wxdelChecked && item.skuDetail.id) {
          skuIds.push(item.skuDetail.id)
        }
      })
      let resp = await this.$api.cartRemoves({
        _isShowLoading: true,
        skuIds: skuIds
      })
      this.$dialog.success('删除成功')
      let newList = []
      let totalPrice = 0, wxCheckedNum = 0
      list.forEach((item) => {
        if (item.wxdelChecked && item.skuDetail.id) {
          return
        }
        if(item.wxChecked){
          totalPrice += item.skuDetail.price * item.skuDetail.quantity
          wxCheckedNum++
        }
        newList.push(item)
      })
      this.totalPrice = totalPrice
      this.wxCheckedNum = wxCheckedNum
      this.wxDelCheckedNum = 0
      this.wxCheckAll = wxCheckedNum == newList.length
      this.wxDelCheckAll = false
      
      this.dataList = newList
    },
    
    // 结算.校验购物车商品
    async tapCheckCart() {
      if(this.flag){
        return
      }
      let cartItemIds = [], skuIds = [];
      let dtos = []
      let list = this.dataList.slice(0)
      let storeId = this.$global.server.storeId
      list.forEach((item) => {
        if (item.wxChecked) {
          cartItemIds.push(item.skuDetail.cartItemId)
          skuIds.push(item.skuDetail.id)
        }
      })
      dtos.push({
        storeId: storeId,
        memo: '',
        skuIds: skuIds,
        codes: []
      })
      let resp = await this.$api.checkCart({
        _isShowLoading: true,
        cartItemIds: cartItemIds
      })
      let params = {
        cartItemIds: JSON.stringify(cartItemIds),
        dtos: JSON.stringify(dtos),
        flag: this.$global.orderFlag.card
      }
      uni.navigateTo({
        url: '/pagesM/pages/order_confirm?' + this.$util.serialize(params)
      })
    },
    // 推荐商品列表
    async queryRecomendList() {
      if (this.isPull) {
        this.isNoMore = false
        this.pageIndex = 0
        this.recomendList.length = 0
      }
      let params = [
        {
          t: 3,
          v: -1,
          k: "hits"
        },
        {
          t: 1,
          v: this.$global.server.storeId,
          k: "storeId"
        }
      ]
      let resp = await this.$api.searchProduct({
        memberId: this.memberId,
        pageNo: this.pageIndex,
        pageSize: 10,
        params: params
      })
      let list = this.getDataList(resp)
      this.recomendList = this.recomendList.concat(list)
    },

    // 购物车列表
    async queryDataList() {
      if (this.isPull) {
        this.dataList.length = 0
        this.invalidList.length = 0
        this.recomendList.length = 0
        this.isEdit = false
      }
      let resp = await this.$api.cartSkuList({
        _isShowLoading: true
      })
      this.emptyType==0
      let list = resp || []
      this.respDetail = list[0] || {}
      if (list[0] && list[0].cartItems) {
        let cartItems = list[0].cartItems || []
        let newCartItems = []
        cartItems.forEach((item) => {
          item.skus.forEach(skuItem => {
            let newItem = Object.assign({}, item)
            newItem.skuDetail = Object.assign({}, skuItem)
            let specList = skuItem.specificationValues || []
            let specificationDescArr = []
            specList.forEach((spec) => {
              specificationDescArr.push(spec.value)
            })
            // newItem.specificationValues = skuItem.specificationValues
            newItem.specificationDesc = specificationDescArr.join('+')
            newCartItems.push(newItem)
          })
        })

        let datalist = [], invalidList = []
        if (!list[0].isEnabled) {
          invalidList = cartItems
        } else {
          newCartItems.forEach((item) => {
            if (!item.isMarketable || !item.isActive) {
              invalidList.push(item)
            } else {
              datalist.push(item)
            }
          })
        }
        this.invalidList = this.invalidList.concat(invalidList)
        this.dataList = this.dataList.concat(datalist)
      }
    },

    onLoadPage() {
	  // wx.hideShareMenu();
      if (this.isPull || this.isLoad) {
        this.isLogin = this.$auth.isAuth
        if (!this.$auth.isAuth) {
          this.emptyType = 0
          this.$refs.dialogLogin.show()
          return
        }else{
          this.$refs.dialogLogin.hide()
        }
        this.totalPrice = 0
        this.wxDelCheckedNum = 0
        this.wxCheckedNum = 0
        this.wxCheckAll = false
        this.wxDelCheckAll = false
        this.memberId = this.$auth.getMemberId()
        this.queryDataList()
        this.queryRecomendList()
      }
      if (this.isReach) {
        this.queryRecomendList()
      }
    },
  },
  onShow() {
    this.onShowPage()
  },
  onReachBottom() {
    this.onReachBottomPage()
  }
}
</script>

<style lang="scss" scoped>
.coupon {
  height: 80upx;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 0 30upx;
  background: #fff;
  .coupon_count {
    font-size: 26upx;
    color: #999999;
    .count {
      display: inline-block;
      padding: 0 10upx;
      color: #F3993A;
    }
  }
  .coupon_handle {
    font-size: 26upx;
    border-radius: 25px;
	background-color: $dt-color-primary;
    color: #fff;
    padding: 10upx 20upx;
  }
}
.bottomHeight {
  height: 100upx;
}
.bottom {
  height: 98upx;
  background: white;
  position: fixed;
  bottom: 0;
  width: 100%;
  font-size: 30upx;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  border-top: 2upx solid rgb(238, 238, 238);
  z-index:90;
  .bottomLeft {
    display: flex;
    flex-direction: row;
    align-items: center;
    color: #666666;
    font-size: 26upx;
    image {
      width: 40upx;
      height: 40upx;
      padding: 20upx 20upx 20upx 30upx;
    }
  }
  .bottomRight {
    display: flex;
    flex-direction: row;
    align-items: center;
    box-sizing: border-box;
    .settlement {
      background: $dt-color-primary;
      width: 210upx;
      text-align: center;
      height: 98upx;
      line-height: 98upx;
      color: white;
      box-sizing: border-box;
      font-size: 30upx;
    }
    .price {
      padding-right: 40upx;
      text-align: right;
      color: #ee1515;
      font-size: 34upx;
      .sign {
        font-size: 24upx;
        text-align: right;
        display: inline-block;
        margin-right: 10upx;
      }
    }
  }
}

.no-data-wrap {
  padding: 100upx 0;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .no-data {
    width: 180upx;
  }
  .no-data-tips {
    color: #999;
    text-align: center;
    font-size: 24upx;
    padding: 30upx 0 40upx;
  }
  .btn-base {
    position: relative;
    width: 160rpx;
    height: 60rpx;
    line-height: 60upx;
    text-align: center;
    color: $dt-color-primary;
    border-radius: 6rpx;
    background-color: transparent;
  }
  .btn-base:before {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: 6upx;
    box-sizing: border-box;
    border: 1upx solid $dt-color-primary;
    content: "";
  }
}
</style>