<template>
  <div class="x-time-select" :class="[{ 'has-nav-arrows': navArrows }, wrapperClassObject]">
    <div class="time-select-container">
      <div v-if="type === 'range'" class="picker-wrapper">
        <span v-if="showCalendarIcon" class="left-calendar-icon"><a-icon type="calendar" /></span>
        <a-range-picker
          :value="dateRange"
          :placeholder="['开始日期', '结束日期']"
          :separator="rangeSeparator"
          :disabled="disabled"
          :allowClear="allowClear"
          :format="format"
          :showTime="showTime"
          @change="handleDateChange"
        />
      </div>
      <div v-if="type === 'date' && !navArrows" class="picker-wrapper">
        <span v-if="showCalendarIcon" class="left-calendar-icon"><a-icon type="calendar" /></span>
        <a-date-picker
          :value="dateRange[0]"
          :format="format"
          :disabled="disabled"
          :allowClear="allowClear"
          :showTime="showTime"
          @change="handleDateChange"
        />
      </div>
      <div v-if="type === 'date' && navArrows" class="picker-wrapper nav-arrows-wrapper">
        <span
          v-if="!disabled"
          class="nav-arrow nav-arrow-left"
          @mousedown.prevent.stop
          @click.stop="handleShiftDay(-1)"
        ><a-icon type="left" /></span>
        <a-date-picker
          :value="dateRange[0]"
          :format="format"
          :disabled="disabled"
          :allowClear="allowClear"
          :showTime="showTime"
          :suffixIcon="null"
          @change="handleDateChange"
        />
        <span
          v-if="!disabled"
          class="nav-arrow nav-arrow-right"
          @mousedown.prevent.stop
          @click.stop="handleShiftDay(1)"
        ><a-icon type="right" /></span>
      </div>

    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { getConfigByName } from '@vue2-client/services/api/common'

export default {
  name: 'XTimeSelect',
  inject: ['getComponentByName'],
  props: {
    queryParamsName: {
      type: String,
      default: null
    },
    value: {
      type: Array,
      default: () => []
    },
    defaultTime: {
      type: Array,
      default: () => []
    },
    disabled: {
      type: Boolean,
      default: false
    },
    allowClear: {
      type: Boolean,
      default: true
    },
    format: {
      type: String,
      default: 'YYYY-MM-DD'
    },
    navArrows: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      dateRange: [],
      type: 'range',
      showCalendarIcon: false
    }
  },
  computed: {
    // 与 XHDescriptions 一致的样式配置模式：通过 $attrs 映射布尔/尺寸类
    wrapperClassObject () {
      const attrs = this.$attrs || {}
      const classes = {}
      const booleanStyleKeys = [
        'yizhu-date'
      ]
      booleanStyleKeys.forEach(key => {
        const val = attrs[key]
        const truthy = val === true || val === '' || val === 'true'
        if (truthy) classes[`xtime-${key}`] = true
      })
      const size = attrs.size
      if (size && typeof size === 'string') classes[`xtime-size-${size}`] = true
      return classes
    },
    showTime () {
      // 根据format判断是否需要显示时间选择器
      return this.format && (this.format.includes('HH:mm') || this.format.includes('hh:mm'))
    },
    rangeSeparator () {
      return this.type === 'range' ? '-' : '至'
    }
  },
  watch: {
    value: {
      handler (newVal) {
        this.convertValueToMoment(newVal)
      },
      immediate: true,
      deep: true
    },
    defaultTime: {
      handler (newVal) {
        // 只有在没有传入value时才使用defaultTime
        if (!this.value || this.value.length === 0) {
          this.convertValueToMoment(newVal)
        }
      },
      immediate: true,
      deep: true
    },
    type () {
      this.convertValueToMoment(this.value)
    }

  },
  created () {
    this.getData(this.queryParamsName)
  },
  methods: {
    convertValueToMoment (value) {
      // 如果没有传入value或value为空，则使用defaultTime
      const timeToUse = (value && value.length > 0) ? value : this.defaultTime
      if (this.type === 'range' && timeToUse?.length === 2) {
        this.dateRange = [
          timeToUse[0] ? moment(timeToUse[0]) : null,
          timeToUse[1] ? moment(timeToUse[1]) : null
        ]
      } else if (this.type === 'date' && timeToUse?.length === 1) {
        this.dateRange = [timeToUse[0] ? moment(timeToUse[0]) : null]
      } else {
        this.dateRange = []
      }
    },
    handleDateChange (dates, dateStrings) {
      if (this.type === 'date') {
        // 单个日期选择器，dates是一个moment对象或null
        this.dateRange = [dates]
      } else {
        // 范围选择器，dates是一个数组
        this.dateRange = dates
      }
      this.$emit('change', dateStrings)
    },
    async getData (data) {
      if (data) {
        getConfigByName(data, 'af-his', res => {
          if (['date', 'range'].includes(res.type)) {
            this.type = res.type
          }
          // 处理format配置
          if (res.format !== undefined) {
            this.format = res.format
          }
          // 处理图标开关配置（默认关闭）
          this.showCalendarIcon = res && res.showCalendarIcon === true
          // 处理左右箭头开关配置（默认关闭）
          this.navArrows = !!(res && (res.navArrows === true || res.showNavArrows === true))
          // 处理defaultTime配置
          if (res.defaultTime !== undefined) {
            if (res.defaultTime === 'now') {
              // 如果配置为'now'，设置当前时间
              const now = moment().format(this.format)
              if (this.type === 'range') {
                this.defaultTime = [now, now]
              } else if (this.type === 'date') {
                this.defaultTime = [now]
              }
            } else if (Array.isArray(res.defaultTime)) {
              // 如果配置为数组，直接使用
              this.defaultTime = res.defaultTime
            }
          }
          this.convertValueToMoment(this.value)
        })
      }
    },
    handleShiftDay (delta) {
      if (this.type !== 'date') return
      const current = this.dateRange && this.dateRange[0] ? this.dateRange[0].clone() : moment()
      const unit = this.showTime ? 'day' : 'day'
      const next = current.add(delta, unit)
      this.dateRange = [next]
      this.$emit('change', next ? next.format(this.format) : '')
    }
  }
}
</script>

<style scoped lang="less">
.x-time-select {
  position: relative;
  width: 100%;
  box-sizing: border-box;
  display: block;
}

.time-select-container {
  display: flex;
  align-items: center;
}

.picker-wrapper {
  flex: 1;
  position: relative;
}

.nav-arrows-wrapper {
  position: relative;
}

.nav-arrow {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  color: #848484;
  cursor: pointer;
  user-select: none;
  z-index: 3;
}
.nav-arrow:hover {
  color: #515151;
}
.nav-arrow-left {
  left: 6px;
}
.nav-arrow-right {
  right: 6px;
}

.x-time-select :deep(.ant-picker-range),
.x-time-select :deep(.ant-picker) {
  width: 100%;
  height: 32px;
  border-radius: 7px;
  background: #FFFFFF;
  border: 1px solid #E5E9F0;
  box-sizing: border-box;
  opacity: 1;
}
.x-time-select.has-nav-arrows :deep(.ant-picker-suffix) {
  display: none; /* 仅箭头模式隐藏后缀图标容器 */
}
.x-time-select :deep(.ant-calendar-picker) {
  width: 100%;
  display: block;
}
.x-time-select :deep(.ant-calendar-picker-input) {
  width: 100%;
  height: 32px;
  border-radius: 7px;
  background: #FFFFFF;
  border: 1px solid #E5E9F0;
  box-sizing: border-box;
  opacity: 1;
}

.x-time-select :deep(.ant-input) {
  width: 100%;
}

/* 左侧日历图标 */
.left-calendar-icon {
  position: absolute;
  left: 10px;
  top: 1.8px;
  width: 18.2px;
  height: 91%;
  opacity: 1;
  color: #848484;
  z-index: 2;
  pointer-events: none;
  display: inline-flex;
  align-items: center;
}

/* 为日期输入增加左内边距，避免与图标重叠（兼容 ant 不同版本） */
.x-time-select :deep(.ant-picker-input > input) {
  padding-left: 19px;
  padding-right: 19px;
  font-family: 'Source Han Sans';
  font-weight: normal;
  line-height: normal;
  text-align: center;
  color: #313131;
}
.x-time-select :deep(.ant-calendar-picker-input) {
  padding-left: 19px;
  padding-right: 19px;
  font-family: 'Source Han Sans';
  font-size: 16px;
  font-weight: normal;
  line-height: normal;
  text-align: center;
  color: #313131;
}
.x-time-select.has-nav-arrows :deep(.ant-calendar-picker-icon),
.x-time-select.has-nav-arrows :deep(.ant-calendar-picker-clear),
.x-time-select.has-nav-arrows :deep(.anticon-calendar) {
  display: none; /* 仅箭头模式隐藏旧版图标节点 */
}

.x-time-select.xtime-yizhu-date {
  margin: 2px 11px 2px 24px;
  width: 234px;
  height: 32px;
  border-radius: 7px;
  opacity: 1;
  background: #FFFFFF;
  box-sizing: border-box;
  border: 1px solid #E5E9F0;
}
/* 箭头模式下，让输入有左右内边距以避让箭头 */
.x-time-select.has-nav-arrows :deep(.ant-picker-input > input) {
  padding-left: 30px;
  padding-right: 30px;
}
</style>
