<template>
  <div class="bi-super-datepick">
    <div class="bi-super-datepick-container">
      <el-popover
        v-model="popoverVisible"
        placement="bottom-start"
        trigger="click"
        popper-class="bi-super-datepick-popover"
      >
        <template #reference>
          <input
            :value="displayValue"
            readonly
            placeholder="选择日期范围"
            class="bi-super-datepick-input"
          />
        </template>
        <div class="bi-super-datepick-content">
          <div class="quick-select">
            <div
              v-for="(item, index) in quickOptions"
              :key="index"
              class="quick-select-item"
              :class="{ active: activeQuickOption === index }"
              @click="handleQuickSelect(item, index)"
            >
              {{ item.text }}
            </div>
          </div>
          <div class="calendar-wrapper">
            <div class="calendar-header">
              <i
                class="el-icon-arrow-left"
                @click="changeMonth(-1)"
              ></i>
              <span>{{ currentYearMonth }}</span>
              <i
                class="el-icon-arrow-right"
                @click="changeMonth(1)"
              ></i>
            </div>
            <div class="calendar-body">
              <div class="calendar-weeks">
                <span
                  v-for="week in weeks"
                  :key="week"
                >{{ week }}</span>
              </div>
              <div class="calendar-days">
                <div
                  v-for="(day, index) in days"
                  :key="index"
                  class="calendar-day"
                  :class="getDayClass(day)"
                  @click="handleDayClick(day)"
                >
                  {{ day.date }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-popover>
    </div>
  </div>
</template>

<script>
// import { utcDatePickerOptions } from './datePickerOption.js'
import moment from 'moment'

export default {
  name: 'BiSuperDate',
  props: {
    pickerOption: {
      type: Object,
      default: () => {
        return {}
      }
    },
    format: {
      type: String,
      default: 'yyyy-MM-dd'
    },
    valueFormat: {
      type: String,
      default: 'yyyy-MM-dd'
    },
    utc: {
      type: Number,
      default: 8
    },
    value: {
      type: [String, Array],
      default: ''
    }
  },
  data() {
    return {
      date: this.value,
      popoverVisible: false,
      activeQuickOption: -1,
      currentMonth: moment().utcOffset(this.utc),
      weeks: ['日', '一', '二', '三', '四', '五', '六'],
      quickOptions: [
        {
          text: '今天',
          onClick: () => {
            const end = moment().utcOffset(this.utc).format('YYYY-MM-DD')
            const start = moment().utcOffset(this.utc).format('YYYY-MM-DD')
            return [start, end]
          }
        },
        {
          text: '昨天',
          onClick: () => {
            const end = moment().utcOffset(this.utc).subtract(1, 'days').format('YYYY-MM-DD')
            const start = moment().utcOffset(this.utc).subtract(1, 'days').format('YYYY-MM-DD')
            return [start, end]
          }
        },
        {
          text: '近一周',
          onClick: () => {
            const end = moment().utcOffset(this.utc).format('YYYY-MM-DD')
            const start = moment().utcOffset(this.utc).subtract(7, 'days').format('YYYY-MM-DD')
            return [start, end]
          }
        },
        {
          text: '近一月',
          onClick: () => {
            const end = moment().utcOffset(this.utc).format('YYYY-MM-DD')
            const start = moment().utcOffset(this.utc).subtract(30, 'days').format('YYYY-MM-DD')
            return [start, end]
          }
        }
      ]
    }
  },
  computed: {
    displayValue() {
      if (Array.isArray(this.date) && this.date.length === 2) {
        return `${this.date[0]} 至 ${this.date[1]}`
      }
      return ''
    },
    currentYearMonth() {
      return this.currentMonth.format('YYYY年MM月')
    },
    days() {
      const firstDay = moment(this.currentMonth).startOf('month')
      const lastDay = moment(this.currentMonth).endOf('month')
      const days = []

      // 填充上个月的日期
      const firstDayWeek = firstDay.day()
      for (let i = firstDayWeek - 1; i >= 0; i--) {
        days.push({
          date: moment(firstDay)
            .subtract(i + 1, 'days')
            .date(),
          fullDate: moment(firstDay)
            .subtract(i + 1, 'days')
            .format('YYYY-MM-DD'),
          isCurrentMonth: false
        })
      }

      // 当前月的日期
      for (let i = 1; i <= lastDay.date(); i++) {
        days.push({
          date: i,
          fullDate: moment(this.currentMonth).date(i).format('YYYY-MM-DD'),
          isCurrentMonth: true
        })
      }

      // 填充下个月的日期
      const lastDayWeek = lastDay.day()
      for (let i = 1; i < 7 - lastDayWeek; i++) {
        days.push({
          date: i,
          fullDate: moment(lastDay).add(i, 'days').format('YYYY-MM-DD'),
          isCurrentMonth: false
        })
      }

      return days
    }
  },
  methods: {
    handleQuickSelect(item, index) {
      this.activeQuickOption = index
      const dateRange = item.onClick()
      this.date = dateRange
      this.$emit('input', dateRange)
      this.$emit('change', dateRange)
      this.popoverVisible = false
    },
    changeMonth(delta) {
      this.currentMonth = moment(this.currentMonth).add(delta, 'month')
    },
    handleDayClick(day) {
      if (!Array.isArray(this.date)) {
        this.date = []
      }

      if (this.date.length === 0 || this.date.length === 2) {
        this.date = [day.fullDate]
      } else {
        const start = moment(this.date[0])
        const end = moment(day.fullDate)

        if (end.isBefore(start)) {
          this.date = [day.fullDate, this.date[0]]
        } else {
          this.date = [this.date[0], day.fullDate]
        }

        this.$emit('input', this.date)
        this.$emit('change', this.date)
        this.popoverVisible = false
      }
    },
    getDayClass(day) {
      const classes = {
        'other-month': !day.isCurrentMonth,
        selected: Array.isArray(this.date) && this.date.includes(day.fullDate),
        'in-range': this.isInRange(day.fullDate)
      }
      return classes
    },
    isInRange(date) {
      if (!Array.isArray(this.date) || this.date.length !== 2) return false

      const current = moment(date)
      const start = moment(this.date[0])
      const end = moment(this.date[1])

      return current.isBetween(start, end, 'day', '[]')
    }
  }
}
</script>
<style lang="scss" scoped>
.bi-super-datepick {
  display: inline-block;

  &-container {
    position: relative;
  }

  &-input {
    width: 300px;
    height: 32px;
    line-height: 32px;
    padding: 0 12px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    cursor: pointer;

    &:hover {
      border-color: #409eff;
    }
  }

  &-content {
    padding: 12px;
  }

  .quick-select {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 12px;

    &-item {
      padding: 4px 8px;
      margin-right: 8px;
      margin-bottom: 8px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 12px;
      color: #606266;
      background-color: #f5f7fa;

      &:hover {
        color: #409eff;
        background-color: #ecf5ff;
      }

      &.active {
        color: #409eff;
        background-color: #ecf5ff;
      }
    }
  }

  .calendar-wrapper {
    .calendar-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 8px 12px;
      font-size: 14px;

      i {
        cursor: pointer;
        padding: 4px;

        &:hover {
          color: #409eff;
        }
      }
    }

    .calendar-weeks {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      text-align: center;
      border-bottom: 1px solid #ebeef5;
      padding: 8px 0;
      font-size: 12px;
      color: #606266;
    }

    .calendar-days {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      padding: 8px 0;

      .calendar-day {
        text-align: center;
        padding: 4px;
        font-size: 12px;
        cursor: pointer;

        &:hover {
          color: #409eff;
        }

        &.other-month {
          color: #c0c4cc;
        }

        &.selected {
          background-color: #409eff;
          color: #fff;
          border-radius: 4px;
        }

        &.in-range {
          background-color: #ecf5ff;
          color: #409eff;
        }
      }
    }
  }
}

.bi-super-datepick-popover {
  padding: 0;
  min-width: 320px;
}
</style>
