<template>
  <div>
    <!-- B分排名 -->
    <van-nav-bar :title="title" left-text="返回" @click-left="$route_back" left-arrow></van-nav-bar>
    <van-dropdown-menu>
      <van-dropdown-item :title="dateDropdownItemTitle" ref="dateDropdownItem">
        <div class="date-type__wrap">
          <div class="date-type__label" v-if="dateType == o.value" v-for="o in dateOption" :key="o.value" :class="{ active: dateType == o.value }" @click.stop="dateType = o.value">
            <span>{{ o.name }}</span>
          </div>
        </div>
        <van-picker v-if="dateType == 0" :columns="yearOption" @change="onYearChange" :default-index="10" item-height="40" />
        <van-datetime-picker v-show="dateType !== 0" v-model="date" type="year-month" :show-toolbar="false" item-height="40" :formatter="formatter" :filter="dateFilter" />
        <div class="date-picker__toolbar">
          <van-button class="reset-button button-border-none" block square color="rgba(38,162,255,0.2)" @click="onResetDate">重置</van-button>
          <van-button class="button-border-none" block square type="info" @click="onConfirmDate">确认</van-button>
        </div>
      </van-dropdown-item>
      <div @click="sortNumber" class="dropdown-menu__item">
        <span :class="{ 'asc-order': !sort }">{{ sort ? '降序' : '升序' }}</span>
      </div>
    </van-dropdown-menu>
    <div class="body_com has_header">
      <scroller ref="scroller" :on-refresh="onRefresh" :on-infinite="onInfinite">
        <!--        <van-cell v-for="(item,index) in data" :key="index" v-if="item.employee_id==user_info.id" style="margin: 0.2rem 0;">
          <template slot="icon">
            <div class="rank-item">
              <icon :name="mapRankIconName[index]" v-if="index < 3 && !sort" class="rank-item__icon"></icon>
              <icon name="rank-first" v-if="item.rank == 1&& sort " class="rank-item__icon"></icon>
              <icon name="rank-second" v-if="item.rank == 2&& sort " class="rank-item__icon"></icon>
              <icon name="rank-third" v-if="item.rank == 3&& sort " class="rank-item__icon"></icon>
              <span v-if="item.rank > 3" class="rank-item__icon-label">{{ item.rank }}</span>
            </div>
          </template>
          <template slot="title">
            <div style="display: flex;">
              <userImage :user_name="item.name" :img_url="item.img_url" style="margin-right: 0.1rem"></userImage>
              <span style="line-height: 0.8rem">{{item.name}}</span>
            </div>
          </template>
          <template slot="right-icon">
            <span :class="item.point < 0?'text-red':'text-blue'" style=" line-height: 0.8rem;">{{item.point}}</span>
          </template>
        </van-cell> -->

        <van-cell v-for="(item, index) in data" :key="index" @click="openDetail(item)">
          <template slot="icon">
            <div class="rank-item">
              <icon :name="mapRankIconName[index]" v-if="index < 3 && !sort" class="rank-item__icon"></icon>
              <icon name="rank-first" v-if="item.rank == 1 && sort" class="rank-item__icon"></icon>
              <icon name="rank-second" v-if="item.rank == 2 && sort" class="rank-item__icon"></icon>
              <icon name="rank-third" v-if="item.rank == 3 && sort" class="rank-item__icon"></icon>
              <span v-if="item.rank > 3" class="rank-item__icon-label">{{ item.rank }}</span>
            </div>
          </template>
          <template slot="title">
            <div style="display: flex;">
              <userImage :user_name="item.name" :img_url="item.img_url" style="margin-right: 0.1rem"></userImage>
              <span style="line-height: 0.8rem"><Wxopendata type="userName" :openid="item.name"></Wxopendata></span>
            </div>
          </template>
          <template slot="right-icon">
            <span :class="item.point < 0 ? 'color_red' : 'text-blue'" style=" line-height: 0.8rem;">{{ item.point }}</span>
          </template>
        </van-cell>
        <noData :list="data" />
      </scroller>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import userImage from '@/components/common/user_image'
import Vue from 'vue'
import { Picker, DropdownMenu, DropdownItem, DatetimePicker } from 'vant'
import moment from 'moment'

Vue.use(Picker)
  .use(DropdownMenu)
  .use(DropdownItem)
  .use(DatetimePicker)

export default {
  name: 'my_ranking',
  components: { userImage },
  data () {
    const dateNow = new Date()
    const currYear = dateNow.getFullYear()
    return {
      page: 1,
      page_size: '20',
      sort: false,
      data: null,
      date: dateNow,
      dateType: 1,
      dateOption: [{ name: '年', value: 0 }, { name: '季度', value: 2 }, { name: '月', value: 1 }],
      departId: 0,
      year: currYear,
      loading: true,
      dateDropdownItemTitle: null,
      deptDropdownItemTitle: '部门',
      filterItemsTitle: '筛选',
      yearOption: this.getYearOption(currYear),
      mapDateDropdownItemTitle: { 0: '年', 1: '月', 2: '季度' },
      mapRankIconName: { 0: 'rank-first', 1: 'rank-second', 2: 'rank-third' },
      ruleId: null,
      sortQs: 'asc',
      title: '',
      items: []
      // user_info: this.$store.getters.user_info || (window.plus ? JSON.parse(plus.storage.getItem('user_info')) : JSON.parse(localStorage.getItem('user_info')))
    }
  },
  computed: {
    hasData () {
      return this.loading || (Array.isArray(this.data) && this.data.length > 0)
    }
  },
  methods: {
    // 打开明细列表
    openDetail (item) {
      var obj = {
        employee_id: item.employee_id,
        employee_img_url: item.img_url,
        employee_name: item.name,
        point: item.point
      }
      var params = this.getParams()
      obj.year = params.year// 年
      obj.rule_id = params.rule// 分类
      obj.quarter = params.quarter// 季度
      obj.month = params.month
      obj.item_id = this.items
      this.$router.push({ name: 'integralDetail', query: { item: JSON.stringify(obj) } })
    },
    sortNumber () {
      this.sort = !this.sort
      if (this.sort) {
        this.sortQs = 'desc'
      } else {
        this.sortQs = 'asc'
      }
      this.page = 1
      this.get_list(() => this.$toast.clear())
    },
    getYearOption (currYear) {
      const yearOption = []
      for (let i = currYear - 10; i <= currYear + 10; i++) {
        yearOption.push(i)
      }
      return yearOption
    },
    dateFilter (type, options) {
      if (type == 'month' && this.dateType == 2) {
        return options.filter(option => option < 5)
      }
      return options
    },
    formatter (type, val) {
      if (type == 'year') {
        return `${val}年`
      }
      return this.dateType == 2 ? `${val[1]}季度` : `${val}月`
    },
    getDateDropdownItemTitle () {
      if (this.dateType == 0) {
        return `${this.year}年`
      }
      return `${this.date.getMonth() + 1}${this.dateType == 1 ? '月' : '季度'}`
    },
    onYearChange (item, value) {
      this.year = value
    },
    onResetDate () {
      this.date = new Date()
      this.dateType = 1
    },
    onConfirmDate () {
      this.dateDropdownItemTitle = this.getDateDropdownItemTitle()
      this.$refs.dateDropdownItem.toggle()
      this.$refs.scroller.triggerPullToRefresh()
    },
    getParams () {
      const params = { group_id: this.group_id, sort: this.sortQs, page: this.page, page_size: this.page_size }
      if (this.dateType == 0) {
        params.date = this.year
        params.year = this.year
      } else if (this.dateType == 1) {
        params.date = moment(this.date).format('YYYYMM')
        params.month = moment(this.date).format('YYYY-MM')
      } else {
        params.date = moment(this.date).format('YYYYM')
        params.quarter = moment(this.date).format('YYYYM')
      }
      return params
    },
    get_list (done) {
      const params = this.getParams()
      request('get', '/api/integral/statistics/groups/rank', params).then(res => {
        if (res.data.code == 1) {
          const { list, items } = res.data.data
          this.items = items.length > 0 ? items : undefined
          if (this.page == 1) {
            this.data = list
          } else {
            this.data = this.data.concat(list)
          }
          this.$refs.scroller.finishInfinite(list.length != 20) // 停止上滚加载下一页，由于服务器端没有统一空数据和正常数据的格式，所以通过total字段来判定数据是否存在下一页
        } else {
          this.$refs.scroller.finishInfinite(true)
        }
        done()
      })
    },
    onRefresh (done) {
      this.page = 1
      this.get_list(done)
    },
    onInfinite (done) {
      this.page++
      this.$toast.loading({ message: '正在加载' })
      this.get_list(() => this.$toast.clear())
    },
    // 获取当前是第几季
    getJ () {
      var getYearWeek = function (a, b, c) {
        var date1 = new Date(a, parseInt(b) - 1, c),
          date2 = new Date(a, 0, 1),
          d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000)
        return Math.ceil((d + (date2.getDay() + 1 - 1)) / 7)
      }
      var today = new Date() // 获取当前时间
      var y = today.getFullYear()
      var m = today.getMonth() + 1
      var d = today.getDate()
      var week,
        quarter = ''
      var result = getYearWeek(y, m, d)
      if (m < 4) {
        quarter = 1
        week = result
      } else if (m < 7) {
        quarter = 2
        week = result - getYearWeek(y, 4, 1)
        var day = new Date(y, 4, 1)
        if (day.getDay() > 1) {
          week += 1
        }
      } else if (m < 10) {
        quarter = 3
        week = result - getYearWeek(y, 7, 1)
        var day = new Date(y, 7, 1)
        if (day.getDay() > 1) {
          week += 1
        }
      } else {
        quarter = 4
        week = result - getYearWeek(y, 10, 1)
        var day = new Date(y, 10, 1)
        if (day.getDay() > 1) {
          week += 1
        }
      }
      return quarter - 1
    }
  },
  mounted () {
    this.group_id = this.$route.query.group_id ? this.$route.query.group_id : 0
    this.title = this.$route.query.title ? this.$route.query.title : '我的排名详情'
    if (this.$route.query.date_interval == 3) {
      this.dateType = 0
    } else if (this.$route.query.date_interval == 2) {
      // 传进入如果是季度
      this.date = new Date(moment(new Date()).format('YYYY'), this.getJ())
      this.dateType = this.$route.query.date_interval
    } else {
      this.dateType = this.$route.query.date_interval
    }
    this.$nextTick(function () {
      this.dateDropdownItemTitle = this.getDateDropdownItemTitle()
    })
  }
}
</script>

<style scoped lang="less">
.text-blue {
  color: #26a2ff;
}
.openDetail {
  color: #909399;
  padding: 0.14rem 0.32rem;
}
.ranking_num span {
  font-size: 0.44rem;
  font-weight: 600;
  color: #26a2ff;
}
.body_com {
  height: calc(100% - 1.92rem);
  position: relative;
}

/deep/ .body_com .van-hairline--top-bottom:after {
  border: none;
}

/deep/ .body_com .van-hairline-unset--top-bottom:after {
  border: none;
}

.date-type__wrap {
  display: flex;
  padding: 0.24rem 0.32rem;
  flex-direction: row;
  justify-content: center;

  & .date-type__label {
    display: flex;
    width: 1.4rem;
    height: 0.52rem;
    font-size: 0.3rem;
    color: #fff;
    background: #26a2ff;
    border-top: 0.02rem solid #26a2ff;
    border-bottom: 0.02rem solid #26a2ff;
    border-left: 0.02rem solid #fff;
    align-items: center;
    justify-content: center;
    transition: color, background-color 100ms;

    &.active {
      color: #26a2ff;
      background: #fff;
      border-radius: 0.08rem;
      &:first-child {
        border-left: 0.02rem solid #26a2ff;
      }
    }

    &:first-child {
      // border-radius: 0.08rem 0 0 0.08rem;
    }

    &:last-child {
      border-right: 0.02rem solid #26a2ff;
      // border-radius: 0 0.08rem 0.08rem 0;
    }
  }
}

.date-picker__toolbar {
  display: flex;
  flex-direction: row;

  & .reset-button {
    color: #26a2ff !important;
  }

  & .button-border-none {
    border: transparent !important;
  }
}

.dropdown-menu__item {
  position: relative;
  display: flex;
  flex: 1;
  min-width: 0;
  font-size: 0.3rem;
  color: #323233;
  align-items: center;
  justify-content: center;
  cursor: pointer;

  & > span {
    position: relative;
    box-sizing: border-box;
    max-width: 100%;
    padding: 0 0.16rem;
    color: #323233;
    font-size: 0.3rem;
    line-height: 0.36rem;

    &:after {
      position: absolute;
      top: 50%;
      right: -0.08rem;
      margin-top: -0.1rem;
      border: 0.06rem solid;
      border-color: transparent transparent currentColor currentColor;
      transform: rotate(-45deg);
      opacity: 0.8;
      content: '';
    }

    &.asc-order:after {
      margin-top: -0.02rem;
      transform: rotate(135deg);
    }
  }
}

.rank-item__icon-wrap {
  display: flex;
  padding-right: 0.32rem;
  width: 0.64rem;
  align-items: center;
  justify-content: center;

  & .rank-item__icon {
    width: 0.64rem;
  }

  & .rank-item__icon-label {
    position: relative;
  }
}

.rank-item__name-wrap {
  display: flex;
  width: 100%;
  height: 100%;
  align-items: center;

  & .rank-item__name-icon {
    position: relative;
    display: flex;
    width: 0.96rem;
    height: 0.96rem;
    font-size: 0.3rem;
    color: #fff;
    background: #26a2ff;
    align-items: center;
    justify-content: center;
    border-radius: 100%;
  }

  & .rank-item__name {
    padding-left: 0.24rem;
  }
}

& /deep/ .rank-item__value {
  display: flex;
  color: #26a2ff;
  align-items: center;
  text-align: right;

  & .negative {
    color: #ff2d55;
  }
}
.filterItemsDiv {
  & .filterItemsTitle {
    padding: 0 0.13rem;
    color: #333;
    font-size: 0.3rem;
  }
  & .filterItemsContent {
    display: flex;
    padding-bottom: 0.24rem;
    & .sub__item {
      display: flex;
      margin: 0.24rem 0.13rem 0 0.13rem;
      width: 1.52rem;
      height: 0.72rem;
      background: #f5f7fa;
      border-radius: 0.04rem;
      align-items: center;
      justify-content: center;
      touch-action: none;
      &.selected {
        color: #26a2ff;
        background: #26a2ff33;
      }
      & span {
        font-size: 0.28rem;
      }
    }
  }
}
.rank-item {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  padding-right: 0.32rem;
  width: 0.64rem;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  & .rank-item__icon {
    width: 0.64rem;
  }
}
</style>
