<template>
  <div class="select-container" :class="{ 'custom-select-auto-container': !isDefault }">
    <el-select ref="selectSelector" v-model="activeLabel" :popper-append-to-body="false"
      @visible-change="onVisibleChange" @mouseenter.native="onSelectMouseEnter" @mouseleave.native="onSelectMouseLeave"
      :placeholder="placeholder" popper-class="select-custom">
      <template v-if="!isDefault" slot="prefix">
        <div class="select-prefix">
          <span class="select-prefix-value highlight-text" v-if="activeLabel">{{ activeLabel }}</span>
          <span class="select-prefix-value" v-else>{{ placeholder }}</span>
          <i class="iconfont icon-xiala" :class="{ 'is-reverse': isFocus }"></i>
        </div>
      </template>
      <template slot="empty">
        <div class="time-container">
          <div class="time-item" :class="{ 'active': item.value === activeValue || (item.disabled && isCustom) }"
            v-for="item in options" :key="item.label" :label="item.label" :value="item.value"
            @click="handleChange(item)">
            <el-popover v-if="item.disabled" class="custom-popover" :append-to-body="false" placement="right-end"
              :trigger="popoverTrigger" :offset="12" v-model="showPopover" @show="popShow" @hide="popHide"
              ref="customPopover">
              <div class="custom-time">
                <el-date-picker ref="timePick" class="time-pick" :append-to-body="false" v-model="p_time"
                  type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                  value-format="timestamp" align="center" @change="dateChange">
                </el-date-picker>
              </div>
              <div slot="reference" class="custom-label">
                <span>{{ item.label }}</span>
                <i class="el-icon-arrow-right"></i>
              </div>
            </el-popover>
            <span v-else>{{ item.label }}</span>
          </div>
        </div>
      </template>
    </el-select>
  </div>
</template>
<script>
import { Select, Option, Popover, Button, Input, DatePicker } from 'element-ui'
import { dateFormatter } from '@/utils/'
export default {
  name: 'timeDropdown',
  components: {
    [Select.name]: Select,
    [Option.name]: Option,
    [Popover.name]: Popover,
    [Button.name]: Button,
    [Input.name]: Input,
    [DatePicker.name]: DatePicker
  },
  props: {
    /**
     * select 回显的输入框是否使用默认样式
     * true：自带输入框
     * false: 回显框为根据回显内容自适应宽度，下拉箭头为实心三角箭头
    */
    isDefault: {
      type: Boolean,
      default: false
    },
    /**
     * 下拉框展开方式
     * hover: 鼠标悬浮 click: 点击
    */
    trigger: {
      type: String,
      default: 'click'
    },
    placeholder: {
      type: String,
      default: '成立时间'
    },
    /**
     * 自定义popover展开方式
     * hover: 鼠标悬浮 click: 点击
    */
    popoverTrigger: {
      type: String,
      default: 'hover'
    },
    value: {
      type: String,
      default: ''
    },
    // 下拉数据
    selectData: {
      type: Array,
      default: () => {
        return [
          {
            label: '全部',
            value: ''
          },
          {
            label: '近1年内',
            value: '-1y'
          },
          {
            label: '1-3年',
            value: '1y-3y'
          },
          {
            label: '3-5年',
            value: '3y-5y'
          },
          {
            label: '5-10年',
            value: '5y-10y'
          },
          {
            label: '10年以上',
            value: '10y-'
          },
          {
            value: '0',
            label: '自定义',
            disabled: true
          }
        ]
      }
    }
  },
  // events => change
  // 自定义时间传入参数格式为 开始时间戳-结束时间戳（输出同理，时间戳为毫秒级）
  data() {
    return {
      isFocus: false,
      options: this.selectData,
      activeValue: this.value,
      isCustom: false, // 当前是否是自定义选项
      p_time: '',
      time: {
        start: '',
        end: ''
      },
      showPopover: false,
      timer: null
    }
  },
  computed: {
    activeLabel() {
      const time = this.activeValue
      if (time) {
        if (this.options.find(v => v.value === time)) {
          let label = this.options.find(v => v.value === time).label
          if (label === '自定义') {
            let start = time.split('-')[0]
            let end = time.split('-')[1]
            return dateFormatter(Number(start), 'yyyy-MM-dd') + '-' + dateFormatter(Number(end), 'yyyy-MM-dd')
          } else {
            return label || ''
          }
        } else {
          let start = time.split('-')[0]
          let end = time.split('-')[1]
          return dateFormatter(Number(start), 'yyyy-MM-dd') + '-' + dateFormatter(Number(end), 'yyyy-MM-dd')
        }
      } else {
        return ''
      }
    }
  },
  watch: {
    isFocus() {
      this.$nextTick(() => {
        if (this.showPopover) {
          setTimeout(() => {
            // popover在下拉框展示时需要重新计算位置，通过先将popover弹框透明度将为0等位置计算完成后再恢复
            this.$refs.customPopover[0].updatePopper()
            const $popover = this.$root.$el.querySelector('.custom-popover > .el-popover')
            $popover.style.opacity = '1'
            if (this.$refs.timePick) {
              this.$refs.timePick[0].focus()
            }
          }, 300)
        }
      })
    },
    value(val) {
      if (val) {
        this.setState(val)
      }
    }
  },
  methods: {
    popShow() {
      if (this.$refs.timePick) {
        this.$refs.timePick[0].focus()
      }
    },
    popHide() {
      // if (this.$refs.timePick) {
      //   this.$refs.timePick[0].blur()
      // }
    },
    onVisibleChange(flag) {
      this.isFocus = flag
      if (flag) {
        this.setState(this.activeValue)
      }
    },
    onSelectMouseEnter(e) {
      if (this.trigger !== 'hover') return
      if (!this.timer) {
        this.timer = setTimeout(() => {
          this.$refs.selectSelector.visible = true
        }, 100)
      }
    },
    onSelectMouseLeave(e) {
      if (this.trigger !== 'hover') return
      clearTimeout(this.timer)
      this.timer = null
      setTimeout(() => {
        this.$refs.selectSelector.blur()
      }, 300)
    },
    dateChange(val) {
      if (!val || val.length === 0) return
      let start = val[0]
      let end = val[1]
      this.activeValue = `${start}-${end}`
      this.time.start = start
      this.time.end = end
      this.options.forEach(item => {
        if (item.label === '自定义') {
          item.value = `${start}-${end}`
        }
      })
      this.isCustom = true
      this.$refs.selectSelector.toggleMenu()
      this.$refs.customPopover[0].doClose()
      this.$emit('change', this.getState())
    },
    handleChange(item) {
      if (item.label !== '自定义') {
        this.activeValue = item.value
        this.isCustom = false
        this.p_time = ''
        this.time.start = ''
        this.time.end = ''
        this.$refs.selectSelector.toggleMenu()
        this.$refs.customPopover[0].doClose()
        this.$emit('change', this.getState())
      } else {
        this.isCustom = true
      }
    },
    getState() {
      return this.activeValue
    },
    getAllstate() {
      return {
        label: this.activeLabel,
        value: this.activeValue,
        isCustom: this.isCustom
      }
    },
    setState(data) {
      this.isCustom = false
      if (data) {
        const valueArr = this.options.filter(v => !v.disabled).map(t => t.value)
        if (valueArr.includes(data)) {
          this.activeValue = data
        } else {
          const timeArr = data.split('-')
          const start = Number(timeArr[0])
          const end = Number(timeArr[1])
          this.isCustom = true
          this.time.start = start
          this.time.end = end
          this.activeValue = data
          this.p_time = [start, end]
          this.showPopover = true
          this.$nextTick(() => {
            const $popover = this.$root.$el.querySelector('.custom-popover > .el-popover')
            $popover.style.opacity = '0'
          })
        }
      } else {
        this.activeValue = data
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.select-container {
  .el-date-editor.time-pick {
    color: transparent !important;
    border-color: transparent !important;
    background-color: transparent !important;
  }

  .time-pick {
    ::v-deep {

      .el-range-input,
      .el-input__icon,
      .el-range-separator {
        display: none;
      }

      .el-picker-panel.el-date-range-picker.el-popper {
        // position: relative !important;
        border: 1px solid $color_main;
        top: -48px !important;
      }
    }

  }

  ::v-deep {
    .popper__arrow {
      display: none;
    }

    .el-input__inner {
      color: $color_main;
    }

    .el-select-dropdown {
      border-radius: 5px;
      margin-top: 0 !important;
      border: 0;
      background: transparent !important;
    }
  }

  /* 需要自定义select输入框的样式 */
  &.custom-select-auto-container {
    .select-prefix {
      display: flex;
      align-items: center;
      width: 100%;
      padding: 0 0 0 10px;
      height: 28px;
      line-height: 28px;
      background: #fff;
      color: #1d1d1d;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
      text-align: left;
      cursor: pointer;

      .select-prefix-value {
        display: inline-block;
        margin-right: 2px;
        flex: 1;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }

      .icon-xiala {
        display: inline-block;
        font-size: 16px;
        flex-shrink: 0;
        transform: rotate(0deg);
        transition: transform .5s;

        &.is-reverse {
          transform: rotate(180deg);
        }
      }
    }

    ::v-deep {
      .el-select {
        height: 24px;
        text-align: start;
        min-width: 50px;
      }

      .select-custom {
        // top: 16px !important;
        border-color: $color_main;
      }

      .el-input {
        width: auto;
      }

      .el-input__prefix {
        display: inline-block;
        position: relative;
        box-sizing: border-box;
        color: #606266;
        font-size: inherit;
        height: 24px;
        line-height: normal;
        transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
        left: 0;
      }

      .el-input__inner {
        position: absolute;
        padding: 0;
        height: 24px;
        line-height: 24px;
      }

      .el-input__suffix {
        display: none;
      }
    }
  }

  /* 下拉框自定义样式 */
  .time-container {
    min-width: 140px;
    padding: 8px 0;
    border: 1px solid $color_main;
    background: #fff;
    border-radius: 5px;
    margin-top: 2px;

    .time-item {
      padding: 4px 16px;
      font-size: 14px;
      line-height: 22px;
      color: #1d1d1d;
      text-align: left;
      cursor: pointer;

      &:hover {
        background: #ECECEC;
      }

      &.active {
        color: $color_main;
      }

      span {
        display: inline-block;
        width: 100%;
      }
    }

    .custom-label {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .el-icon-arrow-right {
        margin-right: -8px;
      }
    }

    .custom-popover {
      .custom-time {
        padding: 20px;
        margin-left: 4px;
        // border: 1px solid $color_main;
        // background: #fff;
        border-radius: 4px;
        position: relative;

        &-item {
          display: flex;
          align-items: center;
          margin-bottom: 12px;
        }

        &-button {
          display: flex;
          justify-content: flex-end;

          .el-button {
            width: 60px;
            height: 28px;
            padding: 0;
          }
        }
      }

      ::v-deep {
        .el-popover {
          margin-left: 16px;
          border-color: $color_main;
          padding: 0;
          border: 0;
          background: transparent;
          box-shadow: 0px 0px 0px transparent;
        }

        .time-input {
          width: 88px;
          height: 24px;
          margin: 0 4px;

          .el-input__inner {
            height: 100%;
            padding: 0 8px;
          }
        }
      }
    }
  }
}
</style>
