<template>
  <view class="order_addcart" :style="colorStyle">
    <view class="order_addcart-header-area">
      <view class="received">
        <view class="pictrue">
          <image
            src="http://wine.gzzzyd.com/wx/order_addcart/qiandai.png"
          ></image>
        </view>
        <view class="text-info" @click="goReceived()">
          <view class="received-count">
            {{ moneyObj.receiveItemAmount }}
          </view>
          <view class="received-info"> 已领取红包 </view>
        </view>
      </view>
      <view class="loss" @click="goMissed()">
        <view class="text-info">
          <view class="received-count">
            {{ moneyObj.lossTotalAmount }}
          </view>
          <view class="received-info"> 已错失红包 </view>
        </view>
      </view>
    </view>

    <view class="loop">
      <view class="loop-title"> 当前红包池 </view>
      <view class="loop-count">
        {{ moneyObj.totalRemainItemAmount }}
      </view>
    </view>

    <view class="tab-area">
      <view
        @click="
          isactiveTab = 'todayRank';
          leaderboard();
        "
        :class="{
          'tab-area-active1': isactiveTab === 'todayRank',
          'base-tab': true,
        }"
      >
        <text> 今日红包排行榜</text>
      </view>
      <view
        @click="
          isactiveTab = 'allRank';
          leaderboard();
        "
        :class="{
          'tab-area-active2': isactiveTab === 'allRank',
          'base-tab': true,
        }"
      >
        <text> 红包领取总榜</text>
      </view>
    </view>
    <view class="rank-list">
      <view class="rank-list-item" v-for="(src, i) in rankList" :key="src.id">
        <img
          v-show="i === 0"
          src="http://wine.gzzzyd.com/wx/order_addcart/rank1.png"
          alt=""
        />
        <img
          v-show="i === 1"
          src="http://wine.gzzzyd.com/wx/order_addcart/rank2.png"
          alt=""
        />
        <img
          v-show="i === 2"
          src="http://wine.gzzzyd.com/wx/order_addcart/rank3.png"
          alt=""
        />
        <img v-show="i !== 0 && i !== 1 && i !== 2" :src="src.avatar" alt="" />
        <text class="nuber"> {{ src.userName }}</text>
        <text class="mosaic"> {{ src.phone }}</text>
        <text class="litem-info"> 共领取了</text>
        <text class="balance">{{ src.totalAmount }}</text>
      </view>
    </view>
    <u-overlay :show="show" @click="show = false">
      <view class="warp">
        <view class="rect" @tap.stop>
          <view class="paper_list">
              <text
                :class="{
                  acitiveRedper: activeRedPer.type === item.type,
                }"
                @click="activeRedPer = item;grabAmountFlag = false;"
                v-for="item in redPaper"
                :key="item.type"
              >
                {{ ["随机红包", "专属红包", "共富红包"][item.type] }}
              </text>
            </view>
          <view class="cover-img">
            <img class="avatar" :src="userInfo.avatar" />
          </view>
          <view class="h-info"
            >当前红包
            {{ ["随机红包", "专属红包", "共富红包"][activeRedPer.type] }}
            <view class="grabAmount_count" v-if="grabAmountFlag">
              <text>恭喜您获得</text>
              <text>￥ {{ currentRedpaper.grabAmount }}</text>
            </view>
            <view class="grabAmount_count" v-if="(activeRedPer.msg && !grabAmountFlag)">
              <text>{{ activeRedPer.msg }}</text>
            </view>
          </view>
          <img
            class="op-img"
            @click="doGrab"
            src="http://wine.gzzzyd.com/wx/order_addcart/ling.png"
            alt=""
          />
          <!-- <img class="op-img" src="http://wine.gzzzyd.com/wx/order_addcart/kai.png" alt=""> -->
          <view class="b-info">
            今日已领取{{
              redPaper.filter((e) => {
                return e.flag === 0;
              }).length
            }}/3
          </view>
          <view class="b-box">
            <text> 参与共富模式,用户可下单领取红包 </text>
          </view>
        </view>
      </view>
    </u-overlay>
  </view>
</template>

<script>
// #ifdef APP-PLUS
let sysHeight = uni.getSystemInfoSync().statusBarHeight + 'px';
// #endif
// #ifndef APP-PLUS
let sysHeight = 0
// #endif
import {
  grabFlag,
  leaderboard,
  doGrab,
  todayStatistics
} from '@/api/home.js';
import {
  getProductHot,
  collectAll,
  getProductDetail
} from '@/api/store.js';
import {
  toLogin
} from '@/libs/login.js';
import {
  mapGetters
} from "vuex";
import recommend from '@/components/recommend';
import productWindow from '@/components/productWindow';
// #ifdef MP
import authorize from '@/components/Authorize';
// #endif
import pageFooter from '@/components/pageFooter/index.vue'
import colors from "@/mixins/color";
import {
  HTTP_REQUEST_URL
} from '@/config/app';
const hot_res = require('@/mock/json/hot_res.json')
import {
  getNavigation
} from '@/api/public.js'
import {
  colorChange
} from '../../api/api';
export default {
  components: {
    pageFooter,
    recommend,
    productWindow,
    // #ifdef MP
    authorize
    // #endif
  },
  mixins: [colors],
  data () {
    return {
      isactiveTab: 'todayRank',
      grabFlagisOpen: false,
      grabAmountFlag: false,
      show: false,
      userInfo: {},
      activeRedPer: {
        type: 0
      },
      currentRedpaper: {
        // 抢到的金额
        grabAmount: '0.00'
      },
      moneyObj: {
        lossTotalAmount: "0",
        receiveItemAmount: "0",
        receiveItemCount: 0,
        redEnvelopeItemCount: 0,
        remainItemCount: 0,
        totalReceivedRedEnvelopeAmount: "0",
        totalRedEnvelopeAmount: "0",
        totalRemainItemAmount: "0"
      },
      imgHost: HTTP_REQUEST_URL,
      is_diy: uni.getStorageSync('is_diy'),
      canShow: false,
      cartCount: 0,
      goodsHidden: true,
      footerswitch: true,
      hostProduct: [],
      cartList: {
        valid: [],
        invalid: []
      },
      isAllSelect: false, //全选
      selectValue: [], //选中的数据
      selectCountPrice: 0.00,
      isAuto: false, //没有授权的不会自动授权
      isShowAuth: false, //是否隐藏授权
      hotScroll: false,
      hotPage: 1,
      hotLimit: 10,
      loading: false,
      loadend: false,
      loadTitle: this.$t(`我也是有底线的`), //提示语
      page: 1,
      limit: 20,
      loadingInvalid: false,
      loadendInvalid: false,
      loadTitleInvalid: this.$t(`加载更多`), //提示语
      pageInvalid: 1,
      limitInvalid: 20,
      attr: {
        cartAttr: false,
        productAttr: [],
        productSelect: {}
      },
      rankList: [],
      redPaper: [],
      productValue: [], //系统属性
      storeInfo: {},
      attrValue: '', //已选属性
      attrTxt: this.$t(`请选择`), //属性页面提示
      cartId: 0,
      product_id: 0,
      sysHeight: sysHeight,
      newData: {},
      activeRouter: '',
      is_diy_set: false
    };
  },
  computed: mapGetters(['isLogin']),
  onPullDownRefresh () {
    this.grabFlag()
    console.log('下拉刷新');
  },
  onLoad (options) {
    let that = this;
    if (that.isLogin == false) {
      toLogin();
    }
    let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
    let curRoute = routes[routes.length - 1].route //获取当前页面路由
    this.activeRouter = '/' + curRoute
  },
  onShow () {

  },
  created () {
    this.userInfo = JSON.parse(this.$Cache.get("USER_INFO"));
    console.log(this.userInfo, this.userInfo.avatar);
    this.grabFlag('created')
    this.leaderboard()
    this.todayStatistics()
  },
  methods: {
    change (e) {
      this.show = e.show
    },
    goReceived () {
      uni.navigateTo({
        url: '/pages/order_addcart/wallet_received/index'
      })
    },
    goMissed () {
      uni.navigateTo({
        url: '/pages/order_addcart/wallet_missed/index'
      })
    },

    // 授权关闭
    authColse: function (e) {
      this.isShowAuth = e;
    },

    leaderboard () {
      let that = this
      uni.showLoading({
        title: this.$t(`加载中`),
        mask: true
      });
      let postData = {
        flag: this.isactiveTab === 'todayRank' ? 1 : 0
      }
      leaderboard(postData).then(res => {
        if (res.data.length > 0) {
          that.$set(that, "rankList", res.data)
        } else {
          that.$set(that, "rankList", [])
        }
        uni.hideLoading();
      })
    },
    doGrab () {
      doGrab({
        type: this.activeRedPer.type
      }).then(res => {
        // if (res.code === 200) {
        //   this.grabFlag('dograbAmountFlag')
        // }
        this.currentRedpaper = res.data
        this.grabAmountFlag = true
        this.grabFlag('dograbAmountFlag')
      })
    },
    grabFlag (params) {
      grabFlag().then(res => {
        this.redPaper = res.data
        if (!params) {
          this.grabAmountFlag = false
        }
        if (params === 'created') {
          this.activeRedPer = res.data[0]
          let flag = this.redPaper.filter((e) => {
            return e.flag === 1;
          }).length
          console.log(flag,this.activeRedPer);
          if (flag === 0) {
            this.show = false
            uni.stopPullDownRefresh();
            return
          }
      
        }

        this.show = true
        uni.stopPullDownRefresh();
      })
    },
    todayStatistics () {
      uni.showLoading({
        title: this.$t(`加载中`),
        mask: true
      });
      let postData = {
        flag: this.isactiveTab === 'todayRank' ? 1 : 0
      }
      todayStatistics().then(res => {
        this.moneyObj = res.data
        uni.hideLoading();
      })
    },

    /**
     * 购物车手动填写
     * 
     */
    iptCartNum: function (e) {
      this.$set(this.attr.productSelect, 'cart_num', e);
    },

    inArray: function (search, array) {
      for (let i in array) {
        if (array[i] == search) {
          return true;
        }
      }
      return false;
    },
    switchSelect: function () {
      let that = this;
      let validList = that.cartList.valid;
      let selectValue = that.selectValue;
      let selectCountPrice = 0.00;
      if (selectValue.length < 1) {
        that.selectCountPrice = selectCountPrice;
      } else {
        for (let index in validList) {
          if (that.inArray(validList[index].id, selectValue)) {
            selectCountPrice = that.$util.$h.Add(selectCountPrice, that.$util.$h.Mul(validList[index]
              .cart_num, validList[
                index].truePrice))
          }
        }
        that.selectCountPrice = selectCountPrice;
      }
    },
    getInvalidList: function () {
      let that = this;
      if (this.loadendInvalid) return false;
      if (this.loadingInvalid) return false;
      let data = {
        page: that.pageInvalid,
        limit: that.limitInvalid,
        status: 0
      }
      let resData = {
        "valid": [],
        "invalid": [],
        "deduction": {
          "seckill_id": 0,
          "bargain_id": 0,
          "combination_id": 0,
          "discount_id": 0
        }
      }
      // getCartList(data).then(res => {
      let cartList = resData,
        invalid = cartList.invalid,
        loadendInvalid = invalid.length < that.limitInvalid;
      let invalidList = that.$util.SplitArray(invalid, that.cartList.invalid);
      that.$set(that.cartList, 'invalid', invalidList);
      that.loadendInvalid = loadendInvalid;
      that.loadTitleInvalid = loadendInvalid ? that.$t(`我也是有底线的`) : that.$t(`加载更多`);
      that.pageInvalid = that.pageInvalid + 1;
      that.loadingInvalid = false;
      // }).catch(res => {
      // 	that.loadingInvalid = false;
      // 	that.loadTitleInvalid = that.$t(`加载更多`);
      // })

    },
    getHostProduct: function () {
      let that = this;
      if (that.hotScroll) return
      that.hotPage++
      that.hotScroll = hot_res.length < that.hotLimit
      that.hostProduct = that.hostProduct.concat(hot_res)
    },
  },
  onReachBottom () {
    let that = this;
    if (that.loadend) {
      that.getInvalidList();
    }
    if (that.cartList.valid.length == 0 && that.cartList.invalid.length == 0) {
      that.getHostProduct();
    }
  }
}
</script>

<style scoped lang="scss">
.order_addcart {
  padding: 20rpx;
}

.rank-list {
  background: white;
  margin-top: 20rpx;
  padding-top: 20rpx;
  padding-bottom: 10rpx;
  height: 600rpx;
  overflow: auto;

  .rank-list-item {
    margin: 20rpx;
    margin-bottom: 40rpx;
    width: calc(100% - 40rpx);
    height: 50rpx;
    display: flex;

    image {
      width: 50rpx;
      height: 50rpx;
      margin-right: 20rpx;
      margin-left: 10rpx;
    }

    .nuber {
      font-size: 18rpx;
      margin-right: 20rpx;
      line-height: 0rpx;
    }

    .mosaic {
      font-size: 18rpx;
      margin-right: 20rpx;
      color: #999999;
      line-height: 0rpx;
    }

    .litem-info {
      text-align: right;
      flex-grow: 1;
      font-size: 24rpx;
      line-height: 50rpx;
      margin-right: 20rpx;
      color: #666666;
    }

    .balance {
      line-height: 50rpx;
      color: #eb4c63;
    }
  }
}

.loop {
  background: url("http://wine.gzzzyd.com/wx/order_addcart/hongbaochi.png")
    no-repeat;
  width: 100%;
  height: 250rpx;
  background-size: 100% 100%;
  position: relative;

  .loop-title {
    padding: 20rpx;
    padding-left: 35rpx;
    font-size: 32rpx;
  }

  .loop-count {
    text-align: center;
    line-height: 97rpx;
    font-size: 48rpx;
    color: #eb4c63;
    width: 420rpx;
    height: 97rpx;
    background: #ffffff;
    border-radius: 23px;
    border: 1px solid #eb4c63;
    position: absolute;
    left: 50%;
    top: 47%;
    transform: translateX(-50%);
  }

  // image {
  // 	width: 100%;
  // }
}

.tab-area {
  margin-top: 20rpx;
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
  line-height: 90rpx;
  text-align: center;

  .base-tab {
    width: 48%;
    height: 90rpx;
  }

  .tab-area-active1 {
    background: url("http://wine.gzzzyd.com/wx/order_addcart/tab1.png")
      no-repeat;
    background-size: 340rpx 120rpx;
  }

  .tab-area-active2 {
    background: url("http://wine.gzzzyd.com/wx/order_addcart/tab2.png")
      no-repeat;
    background-size: 340rpx 120rpx;
  }
}

.order_addcart-header-area {
  display: flex;

  .received {
    width: 405rpx;
    height: 175rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
    margin-right: 20rpx;
    background-color: #fff;
    border-radius: 20rpx;
    overflow: hidden;
    position: relative;
    display: flex;

    .pictrue {
      display: flex;
      align-items: center;

      image {
        width: 98rpx;
        height: 98rpx;
      }

      margin-right: 20rpx;
    }

    .text-info {
      display: flex;
      flex-direction: column;
      justify-content: center;

      color: #6eb03a;

      .received-count {
        font-size: 38rpx;
        margin-bottom: 10rpx;
        letter-spacing: 2px;
      }

      .received-info {
        font-size: 28rpx;
      }
    }
  }

  .loss {
    flex-grow: 1;
    height: 175rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
    background-color: #fff;
    border-radius: 20rpx;
    overflow: hidden;
    position: relative;
    display: flex;

    .text-info {
      width: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      text-align: center;
      color: #d08d5b;

      .received-count {
        font-size: 38rpx;
        margin-bottom: 10rpx;
        letter-spacing: 2px;
      }

      .received-info {
        font-size: 28rpx;
      }
    }
  }
}
.warp {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.rect {
  position: relative;
  width: 700rpx;
  height: 950rpx;
  background: url("http://wine.gzzzyd.com/wx/order_addcart/hongbao_bg.png")
    no-repeat;
  padding-top: 60rpx;
  background-size: 700rpx 950rpx;
  .cover-img {
    margin-top: 40rpx;
    position: relative;
    left: 50%;
    transform: translate(-50%, 0%);
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    overflow: hidden;
    .avatar {
      position: absolute;
      z-index: 9999;
      width: 120rpx;
      height: 120rpx;
    }
  }
  .paper_list {
    display: flex;
    margin: 0 auto;
    justify-content: space-between;
    color: rgb(244, 180, 53);
    border-radius: 50rpx;
    width: 80%;
    font-size: 32rpx;
    height: 80rpx;
    line-height: 60rpx;
    background: rgb(196, 40, 62);
    text-align: center;
      text {
        flex:31%;
        border-radius: 50rpx;
        margin: 10rpx;
      }
    }
  .h-info {
    position: relative;
    text-align: center;
    padding: 10rpx;
    height: 290rpx;
    color: white;

    .grabAmount_count {
      position: relative;
      left: 50%;
      transform: translate(-50%, 0rpx);
      width: 60%;
      text-align:center;
      margin-top: 80rpx;
      font-size: 32rpx;
      font-weight: 600;
      color: rgb(244, 180, 53);
      &:nth-child(1) {
        font-size: 32rpx;
      }
    }
  }
  .op-img {
    cursor: pointer;
    position: relative;
    left: 50%;
    transform: translate(-50%, 0rpx);
    width: 150rpx;
    height: 150rpx;
  }
  .b-info {
    font-size: 22rpx;
    width: 100%;
    text-align: center;
    color: rgb(244, 180, 53);
    margin-bottom: 30rpx;
  }
  .b-box {
    margin: 0 auto;
    color: rgb(244, 180, 53);
    border-radius: 50rpx;
    width: 55%;
    font-size: 22rpx;
    height: 40rpx;
    line-height: 40rpx;
    background: rgb(196, 40, 62);
    text-align: center;
  }
}
.acitiveRedper {
  background: rgb(244, 180, 53);
  border-radius: 50rpx;
  color: white;
}
</style>
