<script>
import XFormCol from '@vue2-client/base-client/components/common/XFormCol'
import moment from 'moment'

export default {
  name: 'XFormDatePicker',
  components: { XFormCol },
  data () {
    return {
      yearShowOne: false,
    }
  },
  props: {
    value: {
      type: [String, Array],
      default: undefined,
    },
    attr: {
      type: Object,
      default: () => ({
        type: 'datePicker',
        model: undefined,
        prop: undefined,
        flex: undefined,
      }),
    },
    mode: {
      type: String,
      default: '新增',
    },
    showLabel: {
      type: Boolean,
      default: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
    // 是否启用时间弹出到最外层
    enablePopupToBody: {
      type: Boolean,
      default: false
    },
    getCalendarContainer: {
      type: Function,
      default: (triggerNode) => triggerNode.parentNode,
    },
  },
  model: {
    prop: 'value',
    event: 'change',
  },
  mounted () {
  },
  computed: {
    localValue: {
      get () {
        try {
          if (
            ['monthPicker', 'yearPicker'].includes(this.attr.type) &&
            this.attr.queryType === 'BETWEEN' &&
            this.mode === '查询'
          ) {
            if (this.value && this.value.length) {
              return this.value[0]
            }
          }
        } catch (e) {
        }
        return this.value
      },
      set (val) {
        if (this.attr.queryType === 'BETWEEN' && this.mode === '查询') {
          if (this.attr.type === 'monthPicker') {
            // 使用 moment 获取这个月的 第一天和最后一天
            const start = moment(val).startOf('month').format(this.formatType)
            const end = moment(val).endOf('month').format(this.formatType)
            this.$emit('change', [start, end])
          } else if (this.attr.type === 'yearPicker') {
            // 使用 moment 获取当年的 第一天和最后一天
            const start = moment(val).startOf('year').format(this.formatType)
            const end = moment(val).endOf('year').format(this.formatType)
            this.$emit('change', [start, end])
          } else {
            this.$emit('change', val)
          }
        } else {
          this.$emit('change', val)
        }
        this.yearShowOne = false
      },
    },
    // 时间范围选择器的开始时间
    timeRangeStartValue: {
      get () {
        return Array.isArray(this.value) && this.value.length > 0 ? this.value[0] : undefined
      },
      set (val) {
        const end = (Array.isArray(this.value) && this.value.length > 1) ? this.value[1] : ''
        this.$emit('change', [val || '', end])
      },
    },
    // 时间范围选择器的结束时间
    timeRangeEndValue: {
      get () {
        return Array.isArray(this.value) && this.value.length > 1 ? this.value[1] : undefined
      },
      set (val) {
        const start = (Array.isArray(this.value) && this.value.length > 0) ? this.value[0] : ''
        this.$emit('change', [start, val || ''])
      },
    },
    // 格式化类型
    formatType () {
      let defaultFormat = 'YYYY-MM-DD HH:mm:ss'
      if (['datePicker', 'rangePicker'].includes(this.attr.type)) {
        if (
          this.mode === '查询' &&
          this.attr.queryType &&
          this.attr.queryType !== 'BETWEEN'
        ) {
          defaultFormat = 'YYYY-MM-DD'
        } else if (!this.attr.queryType) {
          defaultFormat = 'YYYY-MM-DD'
        }
      } else if (['monthRangePicker', 'monthPicker'].includes(this.attr.type)) {
        defaultFormat = 'YYYY-MM'
      } else if (['yearRangePicker', 'yearPicker'].includes(this.attr.type)) {
        defaultFormat = 'YYYY'
      } else if (['timePicker', 'timeRangePicker'].includes(this.attr.type)) {
        defaultFormat = 'HH:mm:ss'
      }
      return (
        (this.mode === '查询' && this.attr.queryValueFormat
          ? this.attr.queryValueFormat
          : this.attr.formValueFormat) || defaultFormat
      )
    },
    ranges () {
      const 本周 = [moment().startOf('week'), moment().endOf('week')]
      const 本月 = [moment().startOf('month'), moment().endOf('month')]
      const 本年 = [moment().startOf('year'), moment().endOf('year')]

      if (['datePicker', 'rangePicker'].includes(this.attr.type)) {
        return {
          本周,
          本月,
          本年,
        }
      } else if (this.attr.type === 'monthRangePicker') {
        return {
          本月,
          本年,
        }
      } else {
        return {
          本年,
        }
      }
    },
    placeholder () {
      const placeholders = {
        datePicker: ['开始日期', '结束日期'],
        rangePicker: ['开始日期', '结束日期'],
        monthRangePicker: ['开始月份', '结束月份'],
        yearRangePicker: ['开始年份', '结束年份'],
        timeRangePicker: ['开始时间', '结束时间'],
      }
      return placeholders[this.attr.type] || ['开始', '结束']
    },
    showMode () {
      const modes = {
        datePicker: ['date', 'date'],
        rangePicker: ['date', 'date'],
        monthRangePicker: ['month', 'month'],
        yearRangePicker: ['year', 'year'],
      }
      return modes[this.attr.type] || ['date', 'date']
    },
    showTime () {
      if (this.formatType === 'YYYY-MM-DD HH:mm:ss') {
        if (this.attr.name.indexOf('开始') > -1 || this.attr.name.indexOf('起始') > -1) {
          return { defaultValue: moment('00:00:00', 'HH:mm:ss') }
        } else {
          return { defaultValue: moment('23:59:59', 'HH:mm:ss') }
        }
      } else {
        return false
      }
    },
    otherattr () {
      if (['yearRangePicker', 'monthRangePicker'].includes(this.attr.type)) {
        return {
          mode: this.showMode
        }
      }
      return {}
    },
    // 日期范围限制函数
    disabledDate () {
      // 查询模式下不进行范围限制
      if (this.mode === '查询') {
        return undefined
      }

      const dateRangeOption = this.attr.dateRangeOption
      if (!dateRangeOption || !dateRangeOption.type) {
        return undefined
      }

      const { type, beforeDays, afterDays } = dateRangeOption
      const today = moment().startOf('day')

      return (current) => {
        // 根据组件类型处理不同的时间粒度
        let currentDate, comparisonDate

        if (['monthPicker', 'monthRangePicker'].includes(this.attr.type)) {
          // 月份选择器：比较月份
          currentDate = moment(current).startOf('month')
          comparisonDate = moment(today).startOf('month')
        } else if (['yearPicker', 'yearRangePicker'].includes(this.attr.type)) {
          // 年份选择器：比较年份
          currentDate = moment(current).startOf('year')
          comparisonDate = moment(today).startOf('year')
        } else {
          // 日期选择器：比较日期
          currentDate = moment(current).startOf('day')
          comparisonDate = today
        }

        switch (type) {
          case 'afterToday':
            // 只能选择今天及以后的日期/月份/年份
            return currentDate.isBefore(comparisonDate)
          case 'beforeToday':
            // 只能选择今天及以前的日期/月份/年份
            return currentDate.isAfter(comparisonDate)
          case 'custom':
            // 自定义范围：beforeDays（今天前多少天）、afterDays（今天后多少天）
            if (beforeDays && beforeDays > 0) {
              let minDate
              if (['monthPicker', 'monthRangePicker'].includes(this.attr.type)) {
                minDate = moment(comparisonDate).subtract(beforeDays, 'months')
              } else if (['yearPicker', 'yearRangePicker'].includes(this.attr.type)) {
                minDate = moment(comparisonDate).subtract(beforeDays, 'years')
              } else {
                minDate = moment(comparisonDate).subtract(beforeDays, 'days')
              }
              if (currentDate.isBefore(minDate)) {
                return true
              }
            }
            if (afterDays && afterDays > 0) {
              let maxDate
              if (['monthPicker', 'monthRangePicker'].includes(this.attr.type)) {
                maxDate = moment(comparisonDate).add(afterDays, 'months')
              } else if (['yearPicker', 'yearRangePicker'].includes(this.attr.type)) {
                maxDate = moment(comparisonDate).add(afterDays, 'years')
              } else {
                maxDate = moment(comparisonDate).add(afterDays, 'days')
              }
              if (currentDate.isAfter(maxDate)) {
                return true
              }
            }
            return false
          default:
            return false
        }
      }
    }
  },
  methods: {
    moment,
    openChange (status) {
      this.yearShowOne = status
    },
    RangePanelChange (value, mode) {
      if (value.length === 0) {
        return
      }
      this.localValue = [
        moment(value[0]).format(this.formatType),
        moment(value[1]).format(this.formatType),
      ]
    },
    getBodyContainer (triggerNode) {
      return document.body
    }
  },
}
</script>

<template>
  <!-- 单日选择器 -->
  <a-date-picker
    v-if="
      (['datePicker'].includes(attr.type) &&
        (attr?.queryType !== 'BETWEEN' || mode !== '查询')) ||
        (['rangePicker'].includes(attr.type) && mode !== '查询')
    "
    :getCalendarContainer="enablePopupToBody? undefined :getCalendarContainer"
    :getPopupContainer="enablePopupToBody? getBodyContainer : undefined"
    v-model="localValue"
    :disabled="disabled || readOnly"
    :disabledDate="disabledDate"
    style="width: 100%"
    :showToday="true"
    placeholder="请选择日期"
    :show-time="showTime"
    :format="formatType"
    :valueFormat="formatType"
  />
  <!-- 月份选择器 -->
  <a-month-picker
    v-else-if="
      attr.type === 'monthPicker' ||
        (attr.type === 'monthRangePicker' && mode !== '查询')
    "
    :getCalendarContainer="enablePopupToBody? undefined :getCalendarContainer"
    :getPopupContainer="enablePopupToBody? getBodyContainer : undefined"
    v-model="localValue"
    :disabled="disabled || readOnly"
    :disabledDate="disabledDate"
    :show-time="true"
    placeholder="请选择月份"
    :valueFormat="formatType"
    style="width: 100%"
  />
  <!--   年份选择器   -->
  <a-date-picker
    v-else-if="
      attr.type === 'yearPicker' ||
        (attr.type === 'yearRangePicker' && mode !== '查询')
    "
    :getCalendarContainer="enablePopupToBody? undefined :getCalendarContainer"
    :getPopupContainer="enablePopupToBody? getBodyContainer : undefined"
    v-model="localValue"
    :disabled="disabled || readOnly"
    :disabledDate="disabledDate"
    format="YYYY"
    :valueFormat="formatType"
    :open="yearShowOne"
    mode="year"
    placeholder="请选择年份"
    @openChange="openChange"
    @panelChange="
      (value, mode) => {
        localValue = moment(value).format(formatType);
      }
    "
    style="width: 100%"
  />
  <!-- 时间选择器 -->
  <a-time-picker
    v-else-if="attr.type === 'timePicker'"
    :getCalendarContainer="enablePopupToBody? undefined :getCalendarContainer"
    :getPopupContainer="enablePopupToBody? getBodyContainer : undefined"
    v-model="localValue"
    :disabled="disabled || readOnly"
    style="width: 100%"
    placeholder="请选择时间"
    :format="formatType"
    :valueFormat="formatType"
  />
  <!-- 时间范围选择器 -->
  <div
    v-else-if="attr.type === 'timeRangePicker'"
    style="display: flex; align-items: center; gap: 8px; width: 100%">
    <a-time-picker
      :getCalendarContainer="enablePopupToBody? undefined :getCalendarContainer"
      :getPopupContainer="enablePopupToBody? getBodyContainer : undefined"
      v-model="timeRangeStartValue"
      :disabled="disabled || readOnly"
      style="flex: 1"
      :placeholder="placeholder[0]"
      :format="formatType"
      :valueFormat="formatType"
    />
    <span style="color: rgba(0, 0, 0, 0.45)"> - </span>
    <a-time-picker
      :getCalendarContainer="enablePopupToBody? undefined :getCalendarContainer"
      :getPopupContainer="enablePopupToBody? getBodyContainer : undefined"
      v-model="timeRangeEndValue"
      :disabled="disabled || readOnly"
      style="flex: 1"
      :placeholder="placeholder[1]"
      :format="formatType"
      :valueFormat="formatType"
    />
  </div>
  <!-- 单日范围选择器 / 月份范围选择器/ 年份范围选择器  -->
  <a-range-picker
    v-else-if="
      (attr.type === 'datePicker' &&
        mode === '查询' &&
        attr.queryType === 'BETWEEN') ||
        (attr.type === 'rangePicker' && mode === '查询') ||
        ['yearRangePicker', 'monthRangePicker'].includes(attr.type)
    "
    v-model="localValue"
    :disabled="disabled"
    :disabledDate="disabledDate"
    :placeholder="placeholder"
    :show-time="
      ['yearRangePicker', 'monthRangePicker'].includes(attr.type)
        ? false
        : {
          defaultValue: [
            moment('00:00:00', 'HH:mm:ss'),
            moment('23:59:59', 'HH:mm:ss'),
          ],
        }
    "
    :ranges="ranges"
    style="width: 100%"
    :format="formatType"
    @panelChange="RangePanelChange"
    @change="RangePanelChange"
    v-bind="otherattr"
  />
</template>

<style scoped lang="less"></style>
