<template>
  <div class="sjp-timeselect">
      <div class="sjp-time-content">
          <Tabs :active-key="activeKey" @on-click="tabClick">
            <Tab-pane label="周数据" :key="0"></Tab-pane>
            <Tab-pane label="月数据" :key="1"></Tab-pane>
        </Tabs>
          <div class="timedata">
            <div class="yeardata">
              <div class="year-item" :class="activeYear == item ? 'activeYear' : ''" v-for="(item, index) of yearList" :key="index" @click="getYear(item)" > 
                <div>{{item}}年</div>
                <div class="year-bar"></div>
              </div>
            </div>
            <div class="allmonth" >
              <div  class="monthweek" 
               id="scrollItem">
                <div class="monthweek-item" @click="clickDate(item)" :id="item.isYear ? 'id'+item.year : item.isActive ? 'active' : ''" v-for="(item, index) of renderList" :key="index" :style="{'color': item.isYear ? '#999' : item.isActive ? '#8000A2' : '#333'}"  >{{item.text}}</div>
              </div>
            </div>
          </div>
      </div>
  </div>
</template>

<script>

export default {
  name: 'timeselect',
  components: {  },
  props:['comeStartDate', 'comEndDate'],
  data() {
    return {
      activeKey: '0',
      monthList:[],
      yearList:[],
      weekList: [],
      activeYear: '',
      renderList: [],
      preId: '',
      isPreventScroll: false,
      startDate: '',
      endDate:'',
      yearTop:[],
    }
  },
  created() {
     // 需要根据当前日期默认选中。并且切换到相应的数据上
    let year;
    let flag = 0; // 默认为0
    if(this.comeStartDate && this.comEndDate){
      let startArr = this.comeStartDate.split('.')
      let endArr = this.comEndDate.split('.')
      year = startArr[0]
      flag = (endArr[2] - startArr[2] ) > 7 ? 'month' : 'week'
    } else {
      year = new Date().getFullYear()
    }
    // 默认为当前第一年
      // 当前年
    this.activeYear =  year
    this.activeKey =  flag,
    this.startDate =  this.comeStartDate, 
    this.endDate =  this.comEndDate
    this.generateYear()
    this.generateWeek()
    this.generateMonth()
    // 默认渲染周数据
    this.renderList =  flag === 0 ? this.weekList : this.monthList
  },
  methods:{
      /**
       * 生成滚动对比的数据
       */
      generateYearTop(){
        let yearTop = []
        let year = new Date().getFullYear()
        for(let i = 0; i <= year - 2018; i++){
          let dom = document.getElementById("id"+ (year - i))
          let scrollTop = dom.offsetTop - 51
          yearTop.push({
            year: year - i,
            scrollTop: scrollTop
          })
        }
        this.yearTop = yearTop
      },
      // 生成周数据
    generateWeek(){
      // 从2018年4月开始生成 第17周
      // 月份是从0开始算的
      let weekList = []
      // 从2018年 4月 30号开始
      let targetYear = 2018
      let targetMonth = 3 // 从4月份开始， date 日期对应的是3
      let targetDay = 29
      let count = 17; // 下一周为第17周
      let currentDate,currentYear,currentMonth,currentDay,
      nextDate,nextYear,nextMonth,nextDay,nextTimeStamp = 0;
      let currentTimeStamp = new Date() - 1
      while(nextTimeStamp <= currentTimeStamp){
        targetDay++; // 周一
        currentDate = new Date(targetYear, targetMonth, targetDay)
        currentYear = currentDate.getFullYear()
        currentMonth = currentDate.getMonth()
        currentDay = currentDate.getDate()

        // 下一周的周1和上一周的周日恰好是两个不同的年
        
        if(nextYear !== currentYear && weekList.length > 0){
          count = 1; // 数量重置为1
          weekList.unshift({
            text: currentYear + '年',
            year:currentYear,
            isYear: true
          })
        }

        // 天数增加7天
        targetDay += 6 // 周日
        nextDate = new Date(targetYear, targetMonth, targetDay, 23, 59,59)
        nextYear = nextDate.getFullYear()
        nextMonth = nextDate.getMonth()
        nextDay = nextDate.getDate()
        nextTimeStamp =  nextDate - 1 // 获取周日晚上的时间戳
        let isActive = false
        const start = (currentMonth + 1 )+ '.' + currentDay
        const end =  (nextMonth + 1) + '.' + nextDay
        if( this.startDate === `${currentYear}.${start}` && this.endDate === `${nextYear}.${end}`){
          isActive = true
        }

        weekList.unshift({
          text: '第' + count +'周 （' + (currentMonth + 1) +'月'+ currentDay + '日 - '+ (nextMonth + 1) +'月'+ nextDay +'日）',
          start: start,
          end:end,
          currentYear: currentYear,
          nextYear: nextYear,
          isActive: isActive,
          isYear: false
        })
        count++;
        // 周内直接跨年
        if(nextYear !== currentYear){
          // 表示了进行跨年
          count = 1; // 数量重置为1
          weekList.unshift({
            text: currentYear + '年',
            year: currentYear,
            isYear: true
          })
        }
      }
      // 第一周进行本周化
      weekList[0].text = '本周（' + (currentMonth + 1) +'月'+ currentDay + '日 - '+ (nextMonth + 1) +'月'+ nextDay +'日）',
      // 添加今年的值
      weekList.unshift({
        text: currentYear + '年',
        year:currentYear,
        isYear: true
      })
        this.weekList = weekList
    },
    /**
     * 生成年数据
     */
    generateYear(){
      let yearList = []
      let nowYear = new Date().getFullYear()
      let targetYear = 2018
      while(nowYear >= targetYear){
        yearList.push(nowYear)
        nowYear--;
      }
      this.yearList = yearList
    },

    clickDate(item){
      // 如果点击的是年的话，没有这个字段，就阻止
      if(!item.start){
        return
      }
      let startDate = `${item.currentYear}.${item.start}`
      let endDate = `${item.nextYear}.${item.end}`
      this.$emit('clickDate',startDate, endDate)
    },
    // 月数据
    generateMonth(){
      // 从2018年5月开始生成
      // 月份是从0开始算的
      let nowMonth = new Date().getMonth();
      let nowYear = new Date().getFullYear()
      let targetYear = 2018
      let targetMonth = 4 // 从5月分开始， date 上是4
      let monthList = []

      // 添加首年
      monthList.push({
        year: nowYear,
        text: nowYear + '年',
        isYear: true,
        month: '' ,
      })
      let isfirst = true
      // 当年份大于目标年， 或者年份等于目标年，但是月份大于目标月
      while(nowYear > targetYear || nowMonth >= targetMonth ){
    
        let text = nowMonth + 1 + '月'
        let isActive = false
        const start = (nowMonth + 1 )+ '.' + 1
        const end =  (nowMonth + 1) + '.' + new Date(nowYear,nowMonth + 1, -1 ).getDate()
        if( this.startDate === `${nowYear}.${start}` && this.endDate === `${nowYear}.${end}`){
          isActive = true
        }

          monthList.push({
            year: nowYear,
            isYear: false,
            month: nowMonth + 1,
            text: isfirst ? text + ' (本月)' : text,
            start,
            isActive,
            end,
            currentYear: nowYear,
            nextYear: nowYear,
          })

          isfirst = false
          nowMonth--;
          if(nowMonth < 0){
            nowMonth = 11;
            nowYear--;
            // 添加年
            monthList.push({
              year: nowYear,
              isYear: true,
              text: nowYear + '年',
              month: '' 
            })
          }
      }
      this.monthList = monthList
    },
    // 获取当前选中年份
    getYear(item){
      let activeYear = item
      let id = 'id'+ activeYear
      if(id !== this.preId){
        this.scrollTo(id)
        this.activeYear = activeYear
        this.preId = id
        this.isPreventScroll = true
      }
    },
    // 滚动到指定位置
    scrollTo(toViewid){
        const dom = document.getElementById(toViewid)
        if(!dom) return
        const parentDom = document.getElementById('scrollItem')
        // top值给的是当前节点，距离页面上角的距离
        parentDom.scrollTop = dom.offsetTop - 52

      },
      /**
     * tab点击
     */
    tabClick(idx){
      this.activeKey = idx
      let year = new Date().getFullYear()
        this.activeYear =  year,
        this.preId =  'id'+ year
      // 滚动到最初始的位置
      document.getElementById('scrollItem').scrollTop = 0
      // 改变渲染的数据列表
      this.renderList =  this.activeKey === 0 ? this.weekList : this.monthList
      // 渲染完节点数据之后再生成yearTop数据
      this.generateYearTop()
    }
  },
  mounted(){
    // 渲染完节点数据之后再生成yearTop数据
      this.generateYearTop();
      this.scrollTo('active');
     //监听屏幕滚动 判断上下滚动
    document.getElementById('scrollItem').addEventListener('scroll',  (ev) => {
      // 点击tab的时候会触发一次滚动，
      if(this.isPreventScroll){
        this.isPreventScroll = false
        return;
      }
      const yearTop = this.yearTop;
      for(let i = yearTop.length - 1; i >= 0; i--) {
        let item = yearTop[i]
          if(ev.target.scrollTop > item.scrollTop) {
            if(this.activeYear !== item.year){
                this.activeYear = item.year
            }
            break;
          }
      }
    })
  }
}
</script>

<style lang="less" scoped>
  .sjp-timeselect{
    .sjp-time-content{
      position: relative;
      .timedata{
        display: flex;
        flex-direction: row;
      }
      .yeardata{
        background: #f2f3f4;
        width: 120px;
        height: 500px;
        overflow: auto;
        position: relative;
      }
      .year-item{
        height: 48px;
        padding-left: 15px;
        font-size: 16px;
        font-weight: 500;
        text-align: left;
        color: #333333;
        line-height: 48px;
        position: relative;
      }
      .activeYear{
        background: #fff;
      }
      .activeYear .year-bar{
        width: 3px;
        height: 22px;
        position: absolute;
        background: #8000a2;
        left: 0px;
        top: 13px;
      }
      .monthweek{
        overflow-y: auto;
        width: 400px;
        height: 500px;
        padding-left: 24px;
        overflow-y: scroll;
      }
      .monthweek-item{
        height: 48px;
        font-size: 16px;
        font-weight: 400;
        color: #333333;
        line-height: 48px;
      }
    }
  }
 
</style>
