<template>
  <view class="container">
    <navbar :config="config" backColor="#666"></navbar>
    <!-- 有数据 -->
    <view v-if="shopList.length >0">
      <view class="topStatus u-flex-center-sb u-plr30" :style="{top:tabTop+'px'}">
        <text class="u-1A1A1A u-font30">共{{totalNum}}件商品</text>
        <text class="u-1A1A1A u-font30" @click="editorBtn">{{editorStatus?'完成':'编辑'}}</text>
      </view>
      <view class="carbox">
        <view class="shopList  u-mt20" v-for="(item,index) in shopList" :key="item.source_shop_id">
          <view class="u-flex-center-sb">
            <view class="u-flex-center">
              <view class="check u-mr10" @click="shopChecked(index)">
                <text class="iconfont iconbox u-font32 u-FF0000 " v-if="item.flag">&#xe646;</text>
                <view class="radios" v-else></view>
              </view>
              <text class="iconfont3 u-bold u-ml10" style="color: #FA6138;">&#xe655;</text>
              <text class="u-1A1A1A u-font30 u-ml15 u-text1 name-width">{{item.source_shop_name}}</text>
              <text class="u-CCC right-icon iconfont">&#xe6c7;</text>
            </view>
            <!-- <view class="">
							{{item.proxy?'代销商品':'自营商品'}}
						</view> -->

          </view>

          <view class="goodsItem u-border-one-one  u-flex-center"
            v-for="(children,childrenIndex) in item.user_cart_list" :key="children.id">
            <view class="check u-mr10" @click="goodsChecked(index,children.id)">
              <text class="iconfont iconbox u-font32 u-FF0000 " v-if="children.flag">&#xe646;</text>
              <view class="radios" v-else></view>
            </view>
            <view class="u-goods200 u-ml15 positionRetave">
              <view class="positinAble" v-if="!children.goods_valid||!children.sku_valid">已失效</view>
              <image :src="children.goods_cover" class="u-goods200" mode="scaleToFill"></image>
            </view>
            <!-- u-flex-column-start -->
            <view class="u-flex1 right-box rightText u-ml30">
              <view class="u-text2 u-1A1A1A u-font28">
                <view class="tipsStatus" v-if="children.platform_store">自营</view>
                <view class="thirdTag" v-if="children.third">第三方</view>
                <text>{{children.goods_title}}</text>
              </view>
              <view class="u-flex-column-start">
                <text class="u-font22 u-999" v-if="children.sku_set_name">规格： {{children.sku_set_name}}</text>
                <view class="u-flex-center-sb botPrice">
                  <view class="u-FF0000 u-font32 u-flex1">
                    <rich-text :nodes="$mUtil.priceBigSmall(children.sale_price)"></rich-text>
                  </view>
                  <view class="rightAddRes u-flex-center">
                    <text class=" btnTag" @click="resNum(children.id)">-</text>
                    <text class="u-flex1 centertext u-font28 u-999">{{children.num}}</text>
                    <text class="btnTag" @click="addNum(children.id)">+</text>
                  </view>
                </view>
              </view>
            </view>
          </view>

        </view>

      </view>

      <!-- 底部 -->

      <view v-if="ispay" class="botfixed u-flex-center-sb">
        <view class="leftAll u-flex-center" @click="allChecked">
          <view class="check u-mr10">
            <text class="iconfont iconbox u-font32 u-FF0000 " v-if="checkAggrement">&#xe646;</text>
            <view class="radios" v-else></view>
          </view>
          <text class="u-ml5 u-font24 u-999">{{checkAggrement?'反选':'全选'}}</text>
        </view>
        <view class="rightP u-flex-center">
          <view class="u-flex-center" v-if="!editorStatus">
            <text class="u-font30 u-333 u-bold">合计：</text>
            <view class="u-FF0000 u-bold">
              <rich-text :nodes="$mUtil.priceBigSmall(totalPrice)"></rich-text>
            </view>
          </view>
          <view class="u-btn btnWidth u-ml30" v-if="!editorStatus" @click="surePay">去结算({{checkNum}})</view>
          <view class="u-btn btnWidth u-ml30" v-else @click="delCart">删除</view>
        </view>
      </view>
    </view>

    <!-- 没有数据 -->
    <view class="nogoods u-mt30 u-flex-column-center" v-if="shopList.length==0">
      <image src="/static/common/noGoods.png" mode="" class="noImg"></image>
      <text class="u-font26 u-999">您的购物车空空如也~</text>
      <view class="btnview" @click="gotoshop">
        <button class="u-DCCDA4 shop-btn u-font30 ">{{isLogin?'去逛逛':'去登录'}}</button>
      </view>
    </view>

    <!--页面加载动画-->
    <ldLoading isFullScreen :active="loading"></ldLoading>
  </view>
</template>

<script>
  var app = getApp()
  export default {
    data() {
      return {
        totalPrice: 0,
        totalNum: 0,
        checkNum: 0,
        checkAggrement: false,
        noGoods: this.$mAssetsPath.noGoods,
        config: {
          back: true, //false是tolbar页面 是则不写
          title: '购物车',
          color: '#1A1A1A',
          //背景颜色;参数一：透明度（0-1）;参数二：背景颜色（array则为线性渐变，string为单色背景）
          backgroundColor: [1, "#fff"],
          statusBarFontColor: '#000'
        },
        loading: false,
        shopList: [],
        arrLenid: [], //选中的购物车id
        editorStatus: false,
        isLogin: false,
        tabTop: 0,
        ispay: app.globalData.openPay
      }
    },
    onShow() {
      let shop = uni.getStorageSync('shop')
      if (shop) {
        this.shop = shop
        this.shopId = shop.id
        this.cartList(shop.id)
        this.rest()
      }
      let token = uni.getStorageSync("apiToken")
      if (token) {
        this.isLogin = true
      } else {
        this.isLogin = false
      }
    },
    onLoad() {
      this.tabTop = app.globalData.barHeight + 44;
    },
    methods: {
      gotoshop() {
        if (this.isLogin) {
          uni.redirectTo({
            url: '/pages/index/lidaPage'
          })
        } else {
          uni.navigateTo({
            url: '/pages/login/index'
          })
        }
      },
      //选择店铺
      shopChecked(index) {
        this.shopList[index].flag = !this.shopList[index].flag
        this.shopList[index].user_cart_list.forEach(j => {
          if (this.shopList[index].flag) {
            j.flag = true
          } else {
            j.flag = false
          }
        })
        this.checkTotalNum()
      },
      //选择商品
      goodsChecked(index, id) {
        this.shopList[index].user_cart_list.forEach(j => {
          if (j.id == id) {
            j.flag = !j.flag
          }
        })
        this.shopHeightLaign(index)
        this.checkTotalNum()
      },
      //全选
      allChecked() {
        this.checkAggrement = !this.checkAggrement
        this.shopList.forEach(k => {
          k.flag = this.checkAggrement
          k.user_cart_list.forEach(j => {
            j.flag = this.checkAggrement
          })
        })
        this.checkTotalNum()
      },
      //减
      resNum(id) {
        this.shopList.forEach(k => {
          k.user_cart_list.forEach(j => {
            if (j.id == id) {
              if (j.num > 1) {
                j.num--
              } else {
                this.$mUtil.toast('不能再减了~')
              }
            }
          })
        })
        this.checkTotalNum()
      },
      //加
      addNum(id) {
        this.shopList.forEach(k => {
          k.user_cart_list.forEach(j => {
            if (j.id == id) {
              if (j.num >= j.limit_buy_num && j.limit_buy_num > 0) {
                this.$mUtil.toast('商品库存只有' + j.limit_buy_num + '件')
              } else {
                j.num++
              }

            }
          })
        })
        this.checkTotalNum()
      },
      //编辑
      editorBtn() {
        this.editorStatus = !this.editorStatus
      },
      //计算选中的数量和总价
      checkTotalNum() {
        this.checkNum = 0
        let arrLenid = []
        let total = 0
        this.shopList.forEach(k => {
          k.user_cart_list.forEach(j => {
            if (j.flag) {
              arrLenid.push(j.id)
              total += j.sale_price * j.num
            }

          })
        })
        this.totalPrice = total.toFixed(2)
        this.arrLenid = arrLenid
        this.checkNum = arrLenid.length
        if (this.checkNum == this.totalNum) {
          this.checkAggrement = true
        } else {
          this.checkAggrement = false
        }
      },
      //查询当前店铺的商品是否被全选中
      shopHeightLaign(index) {
        let arr = []
        this.shopList[index].user_cart_list.forEach(j => {
          arr.push(j.flag)

        })
        if (arr.indexOf(false) == -1) {
          this.shopList[index].flag = true
        } else {
          this.shopList[index].flag = false
        }
      },
      // 判断结算数组是否存在混合商品
      getIsHaveOnline() {
        return new Promise((resolve, reject) => {
          let arr = []
          for (let item of this.shopList) {
            for (let el of item.user_cart_list) {
              for (let i of this.arrLenid) {
                if (i == el.id) {
                  arr.push(el.third)
                }
              }
            }
          }
          let value = arr.every((item) => {
            return item == arr[0];
          })
          resolve(value)
        })
      },
      //结算
      async surePay() {
        if (this.arrLenid.length > 0) {
          let isBoolean =  await this.getIsHaveOnline()
          if (!isBoolean) return this.$mUtil.toast('本地商品与第三方商品不能混合购买')
          let flagKeys = []
          this.shopList.map((res, i) => {
            res.user_cart_list.map((keys, j) => {
              if (keys.flag) {
                if (!keys.goods_valid || (!keys.sku_valid)) {
                  flagKeys.push('false')

                } else {
                  flagKeys.push('true')
                }

              }

            })

          })
          if (flagKeys.indexOf('false') == -1) {
            this.psotJson()
          } else {
            this.$mUtil.toast('已失效的商品不能结算')
          }

        } else {
          this.$mUtil.toast('请选择需要购买的商品')
        }

      },
      //删除
      delCart() {
        let that = this
        if (that.arrLenid.length > 0) {
          uni.showModal({
            title: '提示',
            content: '确定删除选中的商品？',
            success: function(e) {
              if (e.confirm) {
                that.$http.delete(`/cart/delete`, that.arrLenid)
                  .then(res => {
                    if (res && res.code == 200) {
                      that.$mUtil.toast('删除成功')
                      that.rest()
                      that.cartList(that.shopId)
                    }
                  })
              }
            }
          });

        } else {
          that.$mUtil.toast('请选择需要删除的商品')
        }

      },
      // 重置状态
      rest() {
        this.arrLenid = []
        this.totalPrice = 0
        this.checkNum = 0
        this.checkAggrement = false
      },
      //列表
      cartList(id) {
        let nums = 0
        this.$http.get(`/cart/list/${id}`)
          .then(res => {
            this.loading = false
            if (res && res.code == 200) {
              if (res.list.length > 0) {
                res.list.forEach(k => {
                  k.flag = false
                  nums += k.user_cart_list.length
                  k.user_cart_list.forEach(j => {
                    j.flag = false
                  })
                })
                this.totalNum = nums
                this.shopList = res.list
              } else {
                this.shopList = []
              }

            }
          })
      },
      psotJson() {
        let shop_orders = []
        let parendArr = []
        let childArr = [
          [],
          [],
          [],
          [],
          [],
          [],
          [],
          [],
          []
        ]
        let listArr = []
        let dataJson = {}
        this.shopList.map((res, i) => {

          res.user_cart_list.map((keys, j) => {
            if (keys.flag) {
              childArr[i].push({
                user_cart_id: keys.id,
                activity_goods_id: '0',
                goods_id: keys.goods_id,
                num: keys.num,
                sku_hash_code: keys.sku_hash_code,
              })
            }

          })
          if (childArr[i].length > 0) {
            parendArr.push({
              shop_id: res.shop_id,
              source_shop_id: res.source_shop_id,
              activity_id: 0, //活动id
              sponsor_activity_id: 0, //拼团id
              user_remark: '',
              items: childArr[i]
            })

          }
        })
        dataJson = {
          is_cart: true, //是否来源于购物车
          receipt_id: null,
          shipment_mode: 0, //0物流，1自提
          shop_orders: parendArr,
          marketing_type: 0, //0无活动，1秒杀，2拼团
        }
        uni.setStorageSync('dataJson', dataJson)
        uni.navigateTo({
          url: '../product/surePay/surePay'
        })
        // let shop = uni.getStorageSync('shop')
        // let shopid=shop.id?shop.id:''
        // this.$http.post(`/order/build`,dataJson).then(res=>{
        // 	if(res&&res.code==200){
        // 		uni.setStorageSync('sureData',res.data)

        // 	}
        // })


      },

    }
  }
</script>

<style lang="scss">
  page {
    background-color: #f5f5f5;
  }

  .shop-btn {
    width: 300rpx;
    height: 86rpx;
    background: #FA6138;
    border-radius: 43rpx;
    font-size: 30rpx;
    color: #fff;
    text-align: center;
    line-height: 86rpx;
    margin-top: 30rpx;
  }

  .right-icon {
    font-size: 25rpx;
  }

  .border {
    border-bottom: 3rpx solid #E7E7E7;
  }

  .right-box {
    display: flex;
    flex-direction: column;
    // align-items: flex-start;
    justify-content: space-between;
  }

  .name-width {
    max-width: 420rpx;
  }

  .positionRetave {
    position: relative;

    .positinAble {
      position: absolute;
      width: 200rpx;
      height: 40rpx;
      text-align: center;
      background-color: rgba($color: #000000, $alpha: .5);
      color: #fff;
      font-size: 26rpx;
      line-height: 40rpx;
      bottom: 0;
      left: 0;
    }
  }

  .tipsStatus {
    display: inline-block;
    // width: 102rpx;
    // height: 28rpx;
    background: #ff0000;
    border-radius: 10rpx 0px 10rpx 0px;
    line-height: 28rpx;
    text-align: center;
    margin-right: 10rpx;
    color: #fff;
    font-size: 20rpx;

  }
  
  .thirdTag {
    display: inline-block;
    background: #30b885;
    border-radius: 10rpx;
    line-height: 28rpx;
    text-align: center;
    margin-right: 10rpx;
    padding: 6rpx 10rpx;
    color: #fff;
    font-size: 20rpx;
  }

  .check {
    position: relative;
    width: 32rpx;
    height: 32rpx;

    .radios {
      width: 30rpx;
      height: 30rpx;
      display: block;
      border: 1px solid #ccc;
      border-radius: 50%;
      position: absolute;
      left: 0;
      top: 0;
      z-index: 1;
    }

    .iconbox {
      position: relative;
      z-index: 2;
    }

  }

  .topStatus {
    height: 80rpx;
    background-color: #fff;
    position: fixed;
    z-index: 9;

    width: 100%;
    box-sizing: border-box;
  }

  .goodsItem {
    padding: 60rpx 0;
    border-bottom: 3rpx solid #E7E7E7;
  }

  .goodsItem:last-child {
    border-bottom: none;
  }

  .noImg {
    width: 490rpx;
    height: 556rpx;
  }

  .btnview {
    // width: 300rpx;
    // margin: 30rpx auto 0;
  }

  .carbox {
    padding: 80rpx 0 160rpx 0;

    .shopList {
      background-color: #fff;
      padding: 30rpx 30rpx 0;
    }
  }

  .rightText {
    justify-content: space-between;
    height: 200rpx;
  }

  .bottext,
  .botPrice {
    width: 100%;
  }

  .bottext {
    margin-top: 36rpx;
  }

  .rightAddRes {
    width: 172rpx;
    height: 50rpx;
    border-radius: 8rpx;
    border: 1px solid #E5E5E5;

    .centertext {
      text-align: center;
    }

    .btnTag {
      width: 50rpx;
      height: 50rpx;
      line-height: 50rpx;
      text-align: center;
      background-color: #dedede;
      font-size: 46rpx;
      color: #888;
    }
  }

  .btnWidth {
    width: 208rpx;
  }

  .botfixed {
    position: fixed;
    background-color: #fff;
    width: 100%;
    height: 138rpx;
    bottom: 0;
    left: 0;
    z-index: 9;
    padding: 0 30rpx;
    box-sizing: border-box;
  }
</style>
