//积分排行版
<style lang="less">
page {
  height: 100%;
  background-color: #f3f3f3;
}
.page-container {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  position: relative;
  font-family: PingFang SC;
  .rankHeadTitle {
    position: absolute;
    top: -72px;
    left: 0;
    width: 100%;
    font-size: 40rpx;
    color: #000;
    height: 72px;
    text-align: center;
    line-height: 72px;
  }
  .energyHead {
    padding: 34rpx 44rpx 32rpx;
    display: flex;
    justify-content: space-between;
    .totalEnergy {
      display: flex;
      flex-direction: column;
      // align-items: flex-end;
      //justify-content: flex-end;
      height: 80px;
      line-height: 1;
      .name {
        color: #4d5262;
        font-size: 25rpx;
      }
      .value {
        padding-top: 12px;
        color: #000;
        font-size: 87rpx;
        font-family: Montserrat;
      }
    }
    .rightCont {
      display: flex;
      flex-direction: column;
      // align-items: flex-end;
      .rankTitle {
        font-size: 40rpx;
        color: #000;
      }
      .pointExplain {
        color: #4d5262;
        display: flex;
        align-items: center;
        justify-content:flex-end;
        padding-top: 20rpx;
        .text {
          font-size: 24rpx;
          margin-right: 8rpx;
        }
        .icon {
          font-size: 30rpx;
        }
      }
      .timeButton {
        display: flex;
        padding-top: 30rpx;
        font-family: Montserrat;
        font-size: 13px;
        font-weight: 400;
        line-height: 18px;
        color: #4d5262;
        .timeStr {
          margin-right: 6rpx;
        }
      }
      .timeButton2 {
        display: flex;
        align-items: center;
        background: rgba(196, 196, 196, 0.2);
        border-radius: 34rpx;
        color: #9fb7cd;
        font-size: 25rpx;
        margin-top: 30rpx;
        font-family: Montserrat;
        font-weight: 400;
        .timeItem {
          width: 140rpx;
          height: 72rpx;
          line-height: 72rpx;
          text-align: center;
          color: #576b95;
        }
        .weekItem {
          width: 160rpx;
        }
        .sel {
          background: #fff;
          border-radius: 34rpx;
          color: #000000;
        }
      }
    }
  }
  .rankList {
    background: #fff;
    padding-left: 44rpx;
    position: relative;
    .controlDiv {
      width: 230rpx;
      height: 70rpx;
      background: #fff;
      right: 2rpx;
      top: -70rpx;
      position: absolute;
      border-radius: 10rpx;
      border: 1px solid #c3c3c3;
      box-sizing: border-box;
    }
    .eachItem {
      display: flex;
      // justify-content: flex-start;
      align-items: center;
      height: 130rpx;
      box-sizing: border-box;
      .leftCont {
        color: #140050;
        font-size: 32rpx;
        width: 64rpx;
      }
      .centerCont {
        height: 100%;
        flex: 1;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #e6e6e6;
        padding-right: 44rpx;
        box-sizing: border-box;
        overflow: hidden;
        .leftHead {
          display: flex;
          align-items: center;
          .headImg {
            width: 80rpx;
            height: 80rpx;
            border-radius: 80rpx;
            margin-right: 40rpx;
            // background: red;
          }
          .name {
            color: #000000;
            font-size: 30rpx;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
        }
        .point {
          // flex-shrink: 0;
          text-align: right;
          width: 80rpx;
          color: #4d5262;
          font-size: 32rpx;
        }
      }
    }
  }
  .bottomCont {
    height: 80rpx;
  }
  .logo-text {
    display: flex;
    justify-content: center;
    width: 100%;
    height: 24rpx;
    padding: 98rpx 0 80rpx;
    margin-top: 80rpx;
  }
  .nodata {
    text-align: center;
    color: #c4c4c4;
    position: absolute;
    top: 50%;
    left: 0;
    width: 100%;
    transform: translate(0px, -100px);
    .nodataImg {
      width: 100%;
      image {
        width: 96px;
        height: 96px;
      }
    }
    .firstTitle {
      font-size: 34rpx;
    }
    .secondTitle {
      margin-top: 6px;
      font-size: 26rpx;
      .showExplain {
        text-decoration: underline;
      }
    }
  }
}
</style>

<template>
    <div class="page-container">
        <!-- <div class="rankHeadTitle">排行榜</div> -->
        <div class="energyHead">
            <div class="totalEnergy">
                <div class="name">我的{{carbonCreditText}}</div>
                <div class="value">{{(monthPoints||monthPoints==0)?monthPoints:'--'}}</div>
            </div>
            <div class="rightCont">
                <!-- <div class="rankTitle">节能分排行榜</div> -->
                <div
                    class="pointExplain"
                    @tap="showPointExplain"
                >
                    <span class="text">积分说明</span>
                    <van-icon
                        class="icon"
                        name="question-o"
                    />
                </div>
                <div
                    class="timeButton2"
                >
                <!-- <span class="timeStr">{{nowDateStr}}</span>
                    <van-icon name="arrow-down" /> -->
                        <div
                        class="timeItem"  @tap="showTimePopup('month')"
                            :class="{'sel':timeType == 'month'}"
                        >{{nowDateStr}}</div>
                        <div
                        class="timeItem weekItem"  @tap="showTimePopup('week')"
                            :class="{'sel':timeType == 'week'}"
                        >{{nowWeekStr}}</div>
                </div>
            </div>
        </div>
        <div class="rankList">
            <!-- <div class="controlDiv"></div> -->
            <div
                class="eachItem"
                v-for="item in rankList"
            >
                <div class="leftCont">
                    {{item.orderNum}}
                </div>
                <div class="centerCont">
                    <div class="leftHead">
                        <image
                            class="headImg"
                            :src="item.headImgUrl"
                            mode="widthFix"
                        />
                        <div class="name">{{item.userName}}</div>
                    </div>
                    <div class="point">
                        {{item.totalPoints}}
                    </div>
                </div>
            </div>
        </div>
        <div v-show="totalGet">
            <image
                class="logo-text"
                src="{{h5StaticPath}}/page-home/tenatslink.svg"
            ></image>
        </div>
        <div
            class="nodata"
            v-if="noDataShow"
        >
            <div class="nodataImg">
                <image
                    :src="h5StaticPath+'/page-portrait/nodata.png'"
                    mode="widthFix"
                />
            </div>
            <div class="firstTitle">暂时没有排名</div>
            <div class="secondTitle">快去查看<span
                    class="showExplain"
                    @click="showPointExplain"
                >积分说明</span>来增加您的{{carbonCreditText}}吧</div>
        </div>
        <van-popup
            custom-style="height: 50%"
            overlay-style="background: rgba(0, 0, 0, 0.4)"
            position="bottom"
            round
            @close="visible = false"
            :show="visible"
        >
            <div v-if="timeType=='week'" style="height: 320px;">
                <weekcom
                    @checkTime="checkWeekTime"
                    :yearWeekText="nowWeekStr"
                ></weekcom>
            </div>
            <div v-if="timeType=='month'" style="height: 320px;">
                <monthcom
                    @checkTime="checkMonthTime"
                    :yearMonthText="nowDateStr"
                ></monthcom>
            </div>
        </van-popup>
    </div>
</template>

<script>
import wepy from '@wepy/core';
import store from '@/store';
import config from '@/config';
import { mapState } from '@wepy/x';
import {
  queryIntegralRank,
  queryAllIntegral
} from '@/packagesEnv/api/portrait';
import { getCompmayUsers } from '@/api/user';
import moment from 'moment';
import { carbonCredit } from '../common.js'

wepy.page({
  store,
  data: {
    carbonCreditText: '',
    page: 1,
    pageCount: 12,
    totalPage: 0,
    totalGet: false,
    rankList: [],
    monthPoints: null, // 上个月的节能分
    nowDate: '',
    nowDateStr: '',
    visible: false,
    h5StaticPath: config.h5StaticPath,
    allUser: [],
    noDataShow: false,
    timeType: 'month',
    nowWeekStr: ''
  },
  computed: {
    ...mapState({
      token: (state) => state.user.token,
      userInfo: (state) => state.user.userInfo,
      projectId: state => state.company && state.company.companyConfig && state.company.companyConfig.sagacareProjectId,
      allUser2: (state) => {
        var udata = state.portrait.userData;

        if (JSON.stringify(udata) === '{}') return;
        let arr = [];
        for (let key in udata) {
          arr.push(...udata[key]);
        }
        // console.log("val33",arr);
        return arr;
      }
    })
  },
  watch: {},
  onLoad() {
    this.carbonCreditText = carbonCredit(this.projectId);

    this.nowDate = moment()
      .subtract(1, 'month')
      .format('YYYYMM');
    this.nowDateStr = moment()
      .subtract(1, 'month')
      .format('YYYY.MM');
    this.nowWeekStr = moment()
      .weekday(-6)
      .format('YYYY.MM.DD');
    // this.queryCompmayUsers().then((res) => {
    //     debugger;
    //     var allUser = res;
    //     this.rankList.forEach((ele, index) => {
    //         var filterUser = allUser.filter(function (item) {
    //             return item.id == ele.userId;
    //         })
    //         ele.headImgUrl = (filterUser[0] || {}).headImgUrl;
    //     });

    // });

    this.queryAllIntegral();
    this.queryRankingList();
    let menuButtonBoundingClientRect = wx.getMenuButtonBoundingClientRect();
  },
  onReady() {},
  onReachBottom() {
    if (this.page == this.totalPage) return;
    this.page++;
    wx.showLoading({
      title: '加载中'
    });
    this.queryRankingList();
  },
  methods: {
    // combineUser() {
    //     //var allUser = val || [];
    //     this.rankList.forEach((ele, index) => {
    //         var filterUser = this.allUser2.filter(function (item) {
    //             return item.id == ele.userId;
    //         })
    //         ele.headImgUrl = (filterUser[0] || {}).headImgUrl;
    //     });
    // },
    queryCompmayUsers() {
      return getCompmayUsers().then((res) => {
        // console.log('getCompmayUsers', res);
        var resdata = res.data || {};
        var allUser = [];
        for (var i in resdata) {
          allUser.push(...resdata[i]);
        }
        this.allUser = allUser;
        return allUser;
      });
    },
    showTimePopup(type) {
      // if (this.timeType == 'week') {
      //   this.timeType = 'month';
      // } else {
      //   this.timeType = 'week';
      // }
      this.timeType = type;
      console.log('type', type);
      this.visible = true;
    },
    checkWeekTime(seltime) {
      this.nowDate = moment(seltime.replaceAll('.', '-')).format('YYYYMMDD');
      this.nowWeekStr = seltime;

      this.visible = false;
      this.rankList = [];
      this.page = 1;
      this.queryAllIntegral();
      this.queryRankingList();
    },
    checkMonthTime(seltime) {
      wx.uma.trackEvent('portrait_ranking_changemonth', {
        key: '使用统计-排行榜记录-月份切换'
      });

      this.visible = false;

      this.nowDate = seltime;
      this.nowDateStr = moment(seltime.replaceAll('.', '-')).format('YYYY.MM');

      this.rankList = [];
      this.page = 1;
      this.queryAllIntegral();
      this.queryRankingList();
    },
    queryAllIntegral() {
      // 获取上月的总积分
      var _this = this;
      // var lastMonth = moment().subtract(1, 'month').format("YYYYMM");
      var param = {
        criteria: {
          // date:lastMonth,
          date: _this.nowDate,
          type: _this.timeType == 'week' ? 3 : 1
        }
      };
      queryAllIntegral(param).then((res) => {
        var resData = res.content || [];
        this.monthPoints = (resData[0] || {}).totalPoints || null;
        console.log('queryAllIntegral-monthPoints', this.monthPoints);
      });
    },
    queryRankingList() {
      // 获取所有用户的排名
      var _this = this;
      var param = {
        criteria: {
          date: _this.nowDate,
          type: _this.timeType == 'week' ? 3 : 1
        },
        orders: [
          {
            column: 'totalPoints',
            asc: false
          },
          {
            column: 'userId',
            asc: false
          }
        ],
        page: _this.page,
        size: _this.pageCount
      };
      console.log('queryAllIntegral1');
      queryIntegralRank(param).then((res) => {
        var allRes = res.content || [];
        _this.totalPage = Math.ceil((res.count || 0) / _this.pageCount);
        _this.totalGet = _this.totalPage == _this.page;
        // var intergralList=this.intergralList;
        var orderNum =
          (_this.rankList[_this.rankList.length - 1] || {}).orderNum || 0;
        // debugger;
        allRes.forEach((ele, index) => {
          ele.orderNum = orderNum + index + 1;
          // ele.userId='0fdfbe828aa94c659b33e9c605b5c9ea';
          var filterUser = (this.allUser2 || []).filter(function(item) {
            return item.id == ele.userId;
          });
          ele.headImgUrl = (filterUser[0] || {}).headImgUrl;

          if (ele.userId == this.userInfo.userId) {
            ele.headImgUrl =
              this.userInfo.avatarUrl || this.userInfo.headImgUrl;
          }
          _this.rankList.push(ele);
        });
        _this.noDataShow = !(_this.rankList.length > 0);
        // console.log('_this.rankList', _this.rankList);
        wx.hideLoading();
      });
    },
    showPointExplain() {
      wx.uma.trackEvent('portrait_ranking_explainclick', {
        key: '使用统计-排行榜记录-积分说明问号'
      });

      wx.navigateTo({
        url: './pointExplain'
      });
    }
  }
});
</script>

<config>
{
    'navigationBarBackgroundColor': '#f3f3f3',
    'navigationBarTextStyle':'black',
    'backgroundColor': '#f3f3f3',
    'navigationBarTitleText': '排行榜',
        usingComponents: {
         "monthcom":"./components/monthcom",
         "weekcom":"./components/weekcom",
         "van-icon": "module:@vant/weapp/dist/icon",
         "van-popup": "module:@vant/weapp/dist/popup",
    }

}
</config>
