/**
* @author: HXF
* @date: 2022/4/11 17:26
* @Description: 时间选择组件
* @params: selectType => 类型： a默认（不启用选择年月）
*/
<template>
  <el-form-item
    label="时间"
    prop="timeRange"
    style="margin-top: 2px"
  >
    <div class="time-wrap">
      <el-date-picker
        v-if="yomType == 'c'"
        v-model.trim="timeRange1"
        :picker-options="dayPicker"
        :type="dayType[yomType]"
        value-format="yyyy-MM-dd"
        :clearable="false"
        @change="dayChange"
      />
      <el-date-picker
        v-else
        v-model.trim="timeRange"
        :picker-options="dayPicker"
        :type="dayType[yomType]"
        range-separator="至"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        :value-format="valueFor"
        :clearable="false"
        @change="dayChange"
      />
      <!-- 删除@change="dayChange" 防止二次触发 -->
      <el-select v-cloak v-if="selectType != 'a'" v-model.trim="yomType" class="time-wrap-select" placeholder="请选择">
        <el-option v-for="item in public_yom" :key="item.id" :value="item.id" :label="item.name" />
      </el-select>

      <div v-cloak class="time-btn">
        <el-radio-group v-model.trim="checktime" @change="handelDay">
          <el-radio-button v-for="(item,index) in listObj[yomType]" :id="`selectType${index}`" :ref="`selectType${index}`" :key="item" v-trigger :label="item" />
        </el-radio-group>
      </div>

    </div>
  </el-form-item>
</template>

<script>
import '@/utils/date.js'
export default {
  directives: {
    trigger: {
      inserted(el, binging, vnode) {
        const that = vnode.context
        if (that.defaultTime == '本月' && that.yomType != 'c' && that.yomType != 'b') {
          el.id == 'selectType2' ? el.click() : null // 只点击第三个的
        } else {
          el.id == 'selectType0' ? el.click() : null // 只点击第一个的
        }
      }
    }
  },
  props: {
    selectType: {
      type: String,
      default: 'a'
    },
    listObj: {
      type: Object,
      default() {
        return {
          a: ['今天', '昨天', '本月', '上月', '本年'],
          b: ['本月', '近1月', '上月', '近3月', '近1年'],
          c: ['本年', '去年']
        }
      }
    },
    defaultTime: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      timeRange: [new Date(), new Date()],
      timeRange1: new Date(),
      yomType: 'a',
      valueFor: 'yyyy-MM-dd',
      public_yom: [
        {
          id: 'b',
          name: '按月'
        },
        {
          id: 'c',
          name: '按年'
        }
      ],
      dayType: {
        a: 'daterange',
        b: 'monthrange',
        c: 'year'
      },
      checktime: '',
      timeObj: {}
    }
  },
  watch: {
    yomType(val, old) {
      // 通过监听 实现默认加载第一项
      this.reset(true)
    }
  },
  created() {
    this.getTimeObj()
    this.timeRange1 = ''
    this.timeRange = []
  },
  methods: {
    // 重置默认选择第一项
    reset(flag) {
      // wulin 新增监听  如果是重置按钮触发  则恢复按月选择
      if (this.yomType == 'c' && !flag) this.yomType = 'b'

      let current = ''
      if (this.defaultTime == '本月' && this.yomType != 'c') { current = '本月' } else if (this.defaultTime == '本月' && this.yomType == 'c') { current = '本年' } else { current = this.listObj[this.yomType][0] }
      this.checktime = current
      this.handelDay(current)
    },
    handelDay(e) {
      // console.log(this.checktime, 'checktime=========', e)
      // this.checktime = e || ''
      if (this.yomType == 'c') {
        this.timeRange1 = this.getDateRange(e)
      } else {
        this.timeRange = this.getDateRange(e)
      }
      this.dayChange(e)
    },
    getTimeObj() { // 获取时间
      const day = new Date()
      var today = day.format(this.valueFor)
      var yesterday = new Date(new Date().setDate(new Date().getDate() - 1)).format(this.valueFor)
      var monthFirstDay = new Date(new Date().setDate(1)).format(this.valueFor)
      var lastmonth1 = new Date(new Date(new Date().setMonth(new Date().getMonth() - 1)).setDate(1)).format(this.valueFor)
      var lastmonth2 = new Date(new Date().setDate(0)).format(this.valueFor)
      var benYear = new Date(day.setMonth(0, 1)).format(this.valueFor)
      var endYear = new Date(day.setMonth(11, 31)).format(this.valueFor)
      var threeMonth = new Date(new Date(new Date().setMonth(new Date().getMonth() - 3)).setDate(1)).format(this.valueFor)
      var twMonth = new Date(new Date(new Date().setMonth(new Date().getMonth() - 12)).setDate(1)).format(this.valueFor)
      this.timeObj = {
        '今天': [today, today],
        '昨天': [yesterday, yesterday],
        '本月': [monthFirstDay, today],
        '上月': [lastmonth1, lastmonth2],
        '本年': [benYear, endYear],
        '近1月': [lastmonth1, today],
        '近3月': [threeMonth, today],
        '近1年': [twMonth, today]
      }
    },
    dayChange(val) {
      console.log(val)
      // 返回都为[date1,date2]格式
      if (this.yomType == 'b' && val instanceof Array) {
        console.log('触发')
        this.timeRange[1] = new Date(new Date(new Date(this.timeRange[1]).setMonth(new Date(this.timeRange[1]).getMonth() + 1)).setDate(0)).format(this.valueFor)
      }
      let needTimeRange = this.timeRange
      if (this.yomType == 'c') {
        if (this.timeRange1) {
          const date = new Date(this.timeRange1)
          var benYear = new Date(date.setMonth(0, 1)).format(this.valueFor)
          var endYear = new Date(date.setMonth(11, 31)).format(this.valueFor)
          needTimeRange = [benYear, endYear]
        }
      }

      // if (val && val instanceof Object) {
      //   for (var x in this.timeObj) {
      //     console.log(x, val, this.timeObj[x], this.timeObj[x] == val, '[x]==============')
      //     if (this.timeObj[x] == val) {
      //       this.checktime = x
      //       return
      //     }
      //   }
      // }

      // console.log(this.checktime, 'this.checktime==============', val)

      if (this.timeRange1 || this.yomType != 'c') {
        // console.log(this.yomType)
        // console.log("=====",needTimeRange)
        this.$emit('getCurrentDate', needTimeRange)
      }
    },
    getDateRange(type) {
      const day = new Date()
      var year = day.getFullYear()
      // 如果按年，时间选择器接收String 而不是[]
      if (this.yomType == 'c') {
        return new Date(new Date().setFullYear(year = type == '去年' ? year - 1 : year)).format(this.valueFor)
      }
      return this.timeObj[type]
    }
  }
}
</script>

<style lang="scss" scoped>
[v-cloak]{
  display: none !important;
}
.time-wrap{
  display: flex;
  &-select{
    width: 80px;
    margin: 0 20px 0 10px;
  }
  .time-btn{
    margin: -2px 0 0 10px
  }
}
</style>
