<template>
  <div :ref="refStr" class="custom-time-select screen-popper" id="custom-time-select">
    <div :class="['input-block', isSelectOption?'rote':'']">
      <div class="block" @click="isSelectOption=!isSelectOption" @mouseenter="handleMouseenter" @mouseleave="handleMouseleave">
        <el-input class="custom-time-input" v-model="value" :placeholder="placeholder" readonly>
          <template slot="suffix">
            <span @click.stop="handleClear" :class="[isClear&&isHover?'el-icon-circle-close':'el-icon-arrow-down']"></span>
          </template>
        </el-input>
      </div>
      <div class="options-block" v-if="isSelectOption">
        <div class="arrow"></div>
        <div @click="handleClick(option)" :class="['option', value==option?'active':'']" :key="i" v-for="(option, i) in options">
          <template v-if="option == '自定义'">
            <div style="position: relative">
              自定义
              <el-date-picker
                ref="picker"
                :default-value="defaultValue"
                style="position: absolute;opacity: 0;"
                v-model="pickerValue"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
                @change="changePicker">
              </el-date-picker>
            </div>
          </template>
          <template v-else>
            <span>{{option}}</span> <span v-if="value==option" class="el-icon-check"></span>
          </template>
        </div>
      </div>
    </div>
    <div v-if="isSelectOption" class="picker-block" ref="picker-block"></div>
  </div>
</template>

<script>
export default {
  props: {
    'placeholder': {
      type: String,
      default: '请选择',
    },
    'ref-str': {
      type: String,
      default: `timeselect${String(Math.random(0, 100)).slice(2)}`,
    },
    dateFrom: {
      type: String,
      default: ''
    },
    dateTo: {
      type: String,
      default: ''
    }
  },
  computed: {
    isClear() {
      if(!this.isSelectOption && this.value) {
        return true
      }else {
        return false
      }
    },
    pickerOptions() {
      // 用计算属性
      let _this = this
      // 此时 this指向的就是vue实例
      return {
        disabledDate(time) {
          if(_this.dateFrom){
            return time.getTime() < new Date(_this.dateFrom.replace(/-/g, '/')).getTime() - 8.64e6;//如果没有后面的-8.64e6就是不可以选择今天的
          }
          if(_this.dateTo){
            return time.getTime() > new Date(_this.dateTo.replace(/-/g, '/')).getTime();//如果没有后面的-8.64e7就是不可以选择今天的
          }
        }
      }
    },
  },
  watch: {
    refStr(refStr) {
      return refStr
    }
  },
  data() {
    return {
      value: '',
      options: ['近1年', '近2年', '近3年', '近5年', '自定义',],
      isSelectOption: false,
      isHover: false,
      pickerValue: [],
      defaultValue:new Date()
    }
  },
  mounted() {
    if(this.dateTo){
      this.defaultValue = new Date(this.dateTo)
    }
    this.handleAppClick()
  },
  methods: {
    // 时间格式化
    formatDate(timeStr) {
      let date = new Date(Number(timeStr))
      let year = date.getFullYear()
      let month = String(date.getMonth() + 1).padStart(2, 0)
      let day = String(date.getDate()).padStart(2, 0)
      return `${year}-${month}-${day}`
    },
    // 判断是否点击的为组件内部
    handleAppClick() {
      const app = document.getElementById('app')
      app.addEventListener('click', (e) => {
        const dom = this.$refs[this.refStr]
        const flag = dom && dom.contains(e.target)
        // const flag = document.getElementById('custom-time-select').contains(e.target)
        !flag ? this.isSelectOption = false : ''
        if(this.value == '自定义' && (!this.pickerValue || !this.pickerValue.length)) {
          this.value = ''
          this.$emit('input', '')
          this.$emit('handle-search')
        }
      }, true)
    },
    handleMouseenter() {
      this.isHover = true
    },
    handleMouseleave() {
      this.isHover = false
    },
    handleClear() {
      if(this.isClear && this.isHover) {
        this.value = ''
        this.pickerValue = []
        this.$emit('input', '')
        this.$emit('handle-search')
      }else {
        this.isSelectOption = true
      }
    },
    handleClick(value) {
      this.value = value
      if(value == '自定义') {
        this.value = '自定义'
        this.$refs.picker && this.$refs.picker.length && this.$refs.picker[0].focus()
        this.$nextTick(() => {
          this.$refs['picker-block'].appendChild(this.$refs.picker[0].popperElm)
        })
      }else {
        this.pickerValue = []
        this.isSelectOption = false
        let timeStr = []
        let startTime = ''
        let endTime = new Date()
        switch (value) {
          case '近1年':
            startTime = new Date().setFullYear(new Date().getFullYear() - 1)
            if(this.dateTo){
              startTime = new Date(this.dateTo).setFullYear(new Date(this.dateTo).getFullYear() - 1)
            }
            timeStr = [this.formatDate(startTime), this.formatDate(endTime)]
            break;
          case '近2年':
            startTime = new Date().setFullYear(new Date().getFullYear() - 2)
            if(this.dateTo){
              startTime = new Date(this.dateTo).setFullYear(new Date(this.dateTo).getFullYear() - 2)
            }
            timeStr = [this.formatDate(startTime), this.formatDate(endTime)]
            break;
          case '近3年':
            startTime = new Date().setFullYear(new Date().getFullYear() - 3)
            if(this.dateTo){
              startTime = new Date(this.dateTo).setFullYear(new Date(this.dateTo).getFullYear() - 3)
            }
            timeStr = [this.formatDate(startTime), this.formatDate(endTime)]
            break;
          case '近5年':
            startTime = new Date().setFullYear(new Date().getFullYear() - 5)
            if(this.dateTo){
              startTime = new Date(this.dateTo).setFullYear(new Date(this.dateTo).getFullYear() - 5)
            }
            timeStr = [this.formatDate(startTime), this.formatDate(endTime)]
            break;
          default:
            if(this.pickerValue && this.pickerValue.length) {
              timeStr = this.pickerValue
            }else {
              timeStr = []
              this.value = ''
            }
            break;
        }
        this.$emit('input', timeStr)
        this.$emit('handle-search')
      }
    },
    // 时间选择改变后的回调
    changePicker(value) {
      this.isSelectOption = false
      if(value && value.length) {
        // this.value = '自定义'
        this.value = String(this.pickerValue)
        this.$emit('input', this.pickerValue)
      }else {
        this.value = ''
        this.$emit('input', '')
      }
      this.$emit('handle-search')
    }
  }
}
</script>

<style lang="scss">
  .custom-time-select {
    width: 120px;
    height: 34px;

    .input-block {
      width: 100%;
      height: 100%;
      margin: 0;
      cursor: pointer;

      .block {
        width: 100%;
        height: 100%;

        >.custom-time-input.el-input {
          width: 100%;
          height: 100%;
          >input {
            width: 100%;
            height: 100%;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            border-radius: 2px;
          }
        }
      }

      .el-input__suffix {
        transform: rotateZ(0);
        width: 25px;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      &.rote {
        .el-input__suffix {
          transform: rotateZ(180deg);
        }
      }
    }

    .options-block {
      position: absolute;
      margin-top: 12px;
      min-width: 120px;
      font-size: 14px;
      color: #666666;
      background-color: #fff;
      border: 1px solid #E4E7ED;
      padding: 6px 0;
      border-radius: 4px;
      z-index: 10;

      .option {
        padding: 0 24px 0 16px;
        box-sizing: border-box;
        height: 36px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        >span {
          display: inline-block;
        }

        &.active {
          background-color: #F2F7FF;
          color: #0381FA;
        }

        &:hover {
          background-color: #F5F7FA;
        }
      }
    }

    .picker-block {
      position: relative;

      &::after {
        content:"";
        display:block;
        visibility:hidden;
        clear:both;
      }

      .el-picker-panel.el-date-range-picker.el-popper {
        left: 0 !important;
        top: 205px !important;
      }

      .popper__arrow {
        left: 30px !important;
      }
    }
  }
</style>
