<template>
  <div class="selector-content" v-if="selectorType === 'card'" key="s-content">
    暂不提供时间选择的card组件
  </div>
  <div
    class="selector-content"
    v-else-if="selectorType === 'line'"
    key="s-content"
  >
    <div class="select-group-container">
      <div
        v-for="(item, index) in timeSelectList"
        :key="index"
        class="j-button-item bgc"
        :class="{
          active: item.selected
        }"
        @click="clickTimeButton(item)"
      >
        {{ item.name }}
      </div>
    </div>
    <div
      class="date-time-container"
      :class="{ active: state.exact === 'exact' }"
    >
      <el-date-picker
        v-model="dateTimePickerState.start"
        class="date-time-item left"
        :type="dateTimePickerConf.type"
        :editable="dateTimePickerConf.editable"
        :align="dateTimePickerConf.align"
        :prefix-icon="dateTimePickerConf.prefixIcon"
        :format="dateTimePickerConf.format"
        :placeholder="dateTimePickerState.startPlaceHolder"
        :picker-options="startPickerOptions"
        :append-to-body="false"
        @change="startDatePickerChange"
      >
      </el-date-picker>
      <el-date-picker
        v-model="dateTimePickerState.end"
        class="date-time-item right"
        :type="dateTimePickerConf.type"
        :editable="dateTimePickerConf.editable"
        :align="dateTimePickerConf.align"
        :prefix-icon="dateTimePickerConf.prefixIcon"
        :format="dateTimePickerConf.format"
        :placeholder="dateTimePickerState.endPlaceHolder"
        :picker-options="endPickerOptions"
        :append-to-body="false"
        @change="endDatePickerChange"
      >
      </el-date-picker>
    </div>
  </div>
</template>

<script>
import { DatePicker } from 'element-ui'
import { dateFormatter } from '@/utils/'
import moment from 'moment'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')
const timeSelectMap = {
  default: [
    {
      name: '全部',
      value: 'all',
      selected: true
    },
    {
      name: '最近7天',
      value: 'lately7',
      selected: false
    },
    {
      name: '最近30天',
      value: 'lately30',
      selected: false
    },
    {
      name: '去年',
      value: 'lastYear',
      selected: false
    }
  ],
  sub: [
    {
      name: '全部',
      value: 'all',
      selected: true
    },
    {
      name: '今天',
      value: 'today',
      selected: false
    },
    {
      name: '昨天',
      value: 'yesterday',
      selected: false
    },
    {
      name: '最近一周',
      value: 'lately7',
      selected: false
    },
    {
      name: '最近一月',
      value: 'lately30',
      selected: false
    }
  ],
  more: [
    {
      name: '近3个月',
      value: 'lately90',
      selected: true
    },
    {
      name: '近半年',
      value: 'lately180',
      selected: false
    },
    {
      name: '今年全年',
      value: 'thisYear',
      selected: false
    },
    {
      name: '去年至今',
      value: 'sinceLastYear',
      selected: false
    },
    {
      name: '前年至今',
      value: 'sinceYearBeforeLast',
      selected: false
    }
  ],
  allAndlately90: [
    {
      name: '全部',
      value: 'all',
      selected: true
    },
    {
      name: '最近3个月',
      value: 'lately90',
      selected: false
    }
  ],
  bidSearch: [
    {
      name: '最近7天',
      value: 'lately7',
      selected: false
    },
    {
      name: '最近30天',
      value: 'lately30',
      selected: false
    },
    {
      name: '最近1年',
      value: 'sinceLastYear',
      selected: true
    },
    {
      name: '最近3年',
      value: 'sinceLastThreeYear',
      selected: false
    },
    {
      name: '最近5年',
      value: 'sinceLastFiveYear',
      selected: false
    }
  ]
}
export default {
  name: 'time-selector-content',
  components: {
    [DatePicker.name]: DatePicker
  },
  props: {
    selectorType: {
      type: String,
      default: 'card' // card/line
    },
    selectorTime: {
      type: String,
      default: 'default' // default/sub/more/bidSearch
    },
    defaultSelectedKey: {
      type: String,
      default: 'all' // all/lately30/lately90...
    }
  },
  data() {
    return {
      debug: false,
      timeSelectList: timeSelectMap[this.selectorTime],
      dateTimePickerConf: {
        type: 'date',
        editable: false,
        align: 'center',
        prefixIcon: 'clear-icon',
        format: 'yyyy-MM-dd'
      },
      dateTimePickerState: {
        start: '',
        end: '',
        startPlaceHolder: '', // 开始日期
        endPlaceHolder: '' // 结束日期
      },
      startPickerOptions: {
        disabledDate: (time) => {
          const { end } = this.dateTimePickerState
          if (end) {
            return time.getTime() > +new Date(end)
          }
        }
      },
      endPickerOptions: {
        disabledDate: (time) => {
          const { start } = this.dateTimePickerState
          if (start) {
            return time.getTime() < +new Date(start)
          }
        }
      }
    }
  },
  computed: {
    state() {
      return this.getState()
    }
  },
  created() {
    this.calcLastTime()
  },
  methods: {
    dateFormatter,
    calcLastTime() {
      if (this.selectorTime === 'more') {
        const renameList = [
          'thisYear', // 今年全年
          'sinceLastYear', // 去年至今
          'sinceYearBeforeLast' // 前年至今
        ]
        const thisYear = new Date().getFullYear()
        this.timeSelectList.forEach((item) => {
          if (renameList.indexOf(item.value) !== -1) {
            if (item.value === renameList[0]) {
              item.name = `${thisYear}年全年`
            } else if (item.value === renameList[1]) {
              item.name = `${thisYear - 1}年至今`
            } else if (item.value === renameList[2]) {
              item.name = `${thisYear - 2}年至今`
            }
          }
        })
      }
    },
    setState(data) {
      // {
      //   start: 1620230400000, // 2021-5-6
      //   end: 1620489600000, // 2021-5-9
      //   exact: 'all'
      // }
      if (!data || Object.keys(data).length === 0) {
        this.setTimeSelectListState(this.defaultSelectedKey)
      } else {
        switch (data.exact) {
          case 'all':
          case 'today':
          case 'yesterday':
          case 'lately7':
          case 'lately30':
          case 'lately90':
          case 'lately180':
          case 'thisYear':
          case 'sinceLastYear':
          case 'sinceLastThreeYear':
          case 'sinceLastFiveYear':
          case 'sinceYearBeforeLast':
          case 'lastYear': {
            this.setTimeSelectListState(data.exact)
            this.clearDateTimePicker()
            break
          }
          case 'exact': {
            if (!data.start || !data.end) break
            if (data.start < data.end) {
              this.timeSelectList.forEach((v) => (v.selected = false))
              this.dateTimePickerState.start = new Date(data.start)
              this.dateTimePickerState.end = new Date(data.end)
            }
            break
          }
          default: {
            console.warn('exact值为空')
          }
        }
      }
    },
    getState() {
      // timeState.exact: all/lately7/lately30/lastYear/exact5种状态
      // 为true时候表示精确筛选，从时间选择器中获取值(其他为根据当前时间计算出的值)
      const timeState = {
        start: 0,
        end: 0,
        exact: 'exact'
      }
      const durations = {
        hour1: 60 * 60 * 1000,
        day1: 60 * 60 * 1000 * 24 * 1,
        day7: 60 * 60 * 1000 * 24 * 7,
        day30: 60 * 60 * 1000 * 24 * 30
      }
      const selectButton = this.timeSelectList.find((item) => item.selected)
      if (selectButton) {
        timeState.exact = selectButton.value
        Object.assign(timeState, this.calcNotExactTime(timeState.exact))
      } else {
        timeState.exact = 'exact'
        if (this.dateTimePickerState.start) {
          timeState.start = this.dateTimePickerState.start.getTime()
        }
        if (this.dateTimePickerState.end) {
          // 结束时间为当天23:59:59
          timeState.end =
            this.dateTimePickerState.end.getTime() + (durations.day1 - 1000)
        }
      }
      return timeState
    },
    onChange() {
      const state = this.getState()
      if (this.debug) {
        state.startFormatted = this.dateFormatter(state.start)
        state.endFormatted = this.dateFormatter(state.end)

        console.table({
          start: state.startFormatted,
          end: state.endFormatted
        })
      }
      this.$emit('onChange', state)
    },
    setTimeSelectListState(value, callback) {
      this.timeSelectList.forEach((item) => {
        item.selected = item.value === value
        callback && callback(item)
      })
    },
    clearDateTimePicker() {
      this.dateTimePickerState.start = ''
      this.dateTimePickerState.end = ''
    },
    // 计算lately7/lately30/lastYear等的开始和结束时间
    // endTime传入一个时间戳
    calcNotExactTime(exact = 'lately7', endTime = Date.now()) {
      const t = {
        start: 0,
        end: +new Date(endTime)
      }
      const durations = {
        hour1: 60 * 60 * 1000,
        day1: 60 * 60 * 1000 * 24 * 1,
        day7: 60 * 60 * 1000 * 24 * 7,
        day30: 60 * 60 * 1000 * 24 * 30
      }
      switch (exact) {
        case 'today': {
          t.start = moment().startOf('day').format('x')
          t.end = moment().endOf('day').format('x')
          break
        }
        case 'yesterday': {
          t.start = moment().startOf('day').format('x') - durations.day1
          t.end = moment().endOf('day').format('x') - durations.day1
          break
        }
        case 'lately7': {
          t.start = t.end - durations.day7
          break
        }
        case 'lately30': {
          t.start = t.end - durations.day30
          break
        }
        case 'lately90': {
          // 近90天
          t.start = t.end - durations.day30 * 3
          break
        }
        case 'lately180': {
          // 180天
          t.start = t.end - durations.day30 * 6
          break
        }
        case 'thisYear': {
          // 今年全年
          const year = new Date(t.end).getFullYear()
          t.start = +new Date(`${year}`)
          t.end = +new Date(`${year + 1}`) - durations.hour1 * 8 - 1
          break
        }
        case 'lastYear': {
          // 去年全年
          const year = new Date(t.end).getFullYear()
          const lastYear = year - 1
          t.start = +new Date(`${lastYear}`)
          t.end = +new Date(`${year}`) - durations.hour1 * 8 - 1
          break
        }
        case 'sinceLastYear': {
          // 去年至今
          const year = new Date(t.end).getFullYear()
          const lastYear = year - 1
          t.start = +new Date(`${lastYear}`)
          break
        }
        case 'sinceLastThreeYear': {
          // 去年至今
          const year = new Date(t.end).getFullYear()
          const lastYear = year - 3
          t.start = +new Date(`${lastYear}`)
          break
        }
        case 'sinceLastFiveYear': {
          // 去年至今
          const year = new Date(t.end).getFullYear()
          const lastYear = year - 5
          t.start = +new Date(`${lastYear}`)
          break
        }
        case 'sinceYearBeforeLast': {
          // 前年至今
          const year = new Date(t.end).getFullYear()
          t.start = +new Date(`${year - 2}`)
          break
        }
        default: {
          t.start = 0
          t.end = 0
          break
        }
      }
      return t
    },
    clickTimeButton(item) {
      if (item.selected) return
      this.timeSelectList.forEach((v) => (v.selected = false))
      item.selected = true

      this.onChange()
    },
    startDatePickerChange(start) {
      const { end } = this.dateTimePickerState
      if (start && end) {
        // start和end都有值
        this.setTimeSelectListState()
        this.onChange()
      } else if (!start && !end) {
        // start和end都没值
        this.setTimeSelectListState(this.defaultSelectedKey)
        this.onChange()
      }
    },
    endDatePickerChange(end) {
      const { start } = this.dateTimePickerState
      if (start && end) {
        // start和end都有值
        this.setTimeSelectListState()
        this.onChange()
      } else if (!start && !end) {
        // start和end都没值
        this.setTimeSelectListState(this.defaultSelectedKey)
        this.onChange()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.selector-content,
.select-group-container {
  display: flex;
  align-items: center;
}
.selector-content {
  flex-wrap: wrap;
}
.select-group-container {
  margin-right: 24px;
}
.date-time-container {
  display: flex;
  padding: 6px;
  background-color: #f4f5f7;
  border-radius: 4px;
  &.active {
    background-color: #2cb7ca;
    .date-time-item {
      &.left::after {
        background-color: #e0e0e0;
      }
    }
  }
  .clear-icon {
    display: none;
  }
  .date-time-item {
    position: relative;
    width: 160px;
    height: 28px;
    line-height: 28px;
    text-align: center;
    &.left {
      margin-right: 30px;
      &::after {
        content: '';
        position: absolute;
        width: 12px;
        height: 2px;
        top: 50%;
        right: -10px;
        transform: translate(100%, -50%);
        background-color: #1d1d1d;
      }
    }
    ::v-deep {
      .el-input__inner {
        padding: 0;
        height: 100%;
        text-align: center;
        cursor: pointer;
      }
      .el-input__suffix {
        display: flex;
        align-items: center;
      }
    }
  }
}
</style>
