<template>
  <!-- 时间轴主容器 -->
  <div class="x-timeline" :class="wrapperClassObject">
    <!-- 时间轴导航栏 -->
    <div class="x-timeline-nav">
      <!-- 导航按钮：前一周、前一天 -->
      <a-button type="link" @click="goToPrevWeek">
        <a-icon type="vertical-right"/>
        <span v-if="config?.prevWeekText !== false">{{ config?.prevWeekText || '前一周' }}</span>
      </a-button>
      <a-button type="link" @click="goToPrevDay">
        <a-icon type="left"/>
        <span v-if="config?.prevDayText !== false">{{ config?.prevDayText || '前一天' }}</span>
      </a-button>
      <!-- 日期显示区域 -->
      <div class="timeline-dates">
        <div
          v-for="(date, index) in displayDates"
          :key="index"
          class="date-item"
          :class="{
            'ant-btn-primary': isCurrentDate(date),
            'date-weekend': isWeekend(date),
            'ant-btn-disabled': isDisabled(date)
          }"
          @click="selectDate(date)"
        >
          <div class="weekday">{{ getWeekDay(date) }}</div>
          <div class="date">{{ formatDate(date) }}</div>
        </div>
      </div>
      <!-- 导航按钮：后一天、后一周 -->
      <a-button type="link" @click="goToNextDay">
        <span v-if="config?.nextDayText !== false">{{ config?.nextDayText || '后一天' }}</span>
        <a-icon type="right"/>
      </a-button>
      <a-button type="link" @click="goToNextWeek">
        <span v-if="config?.nextWeekText !== false">{{ config?.nextWeekText || '后一周' }}</span>
        <a-icon type="vertical-left"/>
      </a-button>
    </div>
  </div>
</template>

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

// 设置 moment 为中文语言环境
moment.locale('zh-cn')

export default {
  name: 'XTimeline',
  components: {},
  props: {
    // 当前选中日期，默认为空（不选中）
    modelValue: {
      type: String,
      default: ''
    },
    // 配置参数名称，用于获取时间轴配置
    queryParamsName: {
      type: String,
      default: ''
    }
  },

  // 定义组件事件
  emits: ['update:modelValue', 'change', 'prev-week', 'next-week', 'prev-day', 'next-day', 'init'],

  data () {
    return {
      currentDate: this.modelValue, // 当前选中日期
      baseDate: moment().format('YYYY-MM-DD'), // 基准日期，默认今天，用于计算显示范围
      config: null,
      disabledDates: [] // 禁用日期列表
    }
  },
  computed: {
    // 动态样式开关（与 XHDescriptions 思路一致）：布尔开关 + size 派生类
    wrapperClassObject () {
      const attrs = this.$attrs || {}
      const classes = {}

      const booleanStyleKeys = [
        'compact',
        'bordered',
        'highlight-weekend',
        'dark-theme',
        'style1'
      ]
      booleanStyleKeys.forEach(key => {
        const val = attrs[key]
        const truthy = val === true || val === '' || val === 'true'
        if (truthy) classes[`xtimeline-${key}`] = true
      })
      const size = attrs.size
      if (size && typeof size === 'string') classes[`xtimeline-size-${size}`] = true
      return classes
    },
    // 计算需要显示的日期范围，固定显示周一到周日
    displayDates () {
      const dates = []
      // 计算当前日期所在周的周一
      const currentDay = moment(this.baseDate)
      const dayOfWeek = currentDay.day() || 7 // 获取星期几，将周日的0转换为7
      const mondayOfWeek = currentDay.clone().subtract(dayOfWeek - 1, 'day') // 减去相应的天数得到周一

      // 从周一开始，生成一周的日期
      dates.push(mondayOfWeek.format('YYYY-MM-DD')) // 周一
      for (let i = 1; i <= 6; i++) {
        dates.push(mondayOfWeek.clone().add(i, 'day').format('YYYY-MM-DD'))
      }

      return dates
    }
  },

  watch: {
    // 监听外部传入的选中日期变化
    modelValue: {
      handler (newVal) {
        this.currentDate = newVal
        if (newVal) {
          this.baseDate = newVal
        }
      },
      immediate: true
    },
    // 监听配置参数名称变化
    queryParamsName: {
      handler (newValue) {
        this.getData(newValue)
      },
      immediate: true
    }
  },

  created () {
    // 组件创建时获取配置
    this.getData(this.queryParamsName)
  },

  methods: {
    // 获取时间轴配置数据
    async getData (data) {
      getConfigByName(data, 'af-his', res => {
        this.config = res
        // 触发初始化事件，传递配置和默认日期
        this.$emit('init', this.baseDate)
        if (res.defaultValue) {
          // 如果有默认值，则设置当前选中日期和基准日期
          this.currentDate = res.defaultValue
          this.baseDate = res.defaultValue
          this.$emit('update:modelValue', res.defaultValue)
        } else {
          // 如果没有默认值，则设置今天日期为基准日期
          this.modelValue = this.baseDate
        }

        // 执行配置中指定的业务逻辑
        if (res.logicName) {
          runLogic(res.logicName, res.parameter, 'af-his').then(result => {
            if (result) {
              this.handleLogicResult(result)
            }
          })
        }
      })
    },

    // 处理业务逻辑返回结果
    handleLogicResult (result) {
      if (result.disabledDates) {
        this.disabledDates = result.disabledDates
      }
      if (result.currentDate) {
        this.currentDate = result.currentDate
        this.baseDate = result.currentDate
        this.$emit('update:modelValue', result.currentDate)
      }
    },

    // 格式化日期显示
    formatDate (date) {
      const format = this.config?.dateFormat || 'MM/DD'
      return moment(date).format(format)
    },

    // 获取星期显示
    getWeekDay (date) {
      const format = this.config?.weekFormat || '周dd'
      return moment(date).format(format)
    },

    // 判断是否为周末
    isWeekend (date) {
      if (!this.config?.highlightWeekend) return false
      const day = moment(date).day()
      return day === 0 || day === 6
    },

    // 判断日期是否禁用
    isDisabled (date) {
      if (this.config?.minDate && moment(date).isBefore(this.config.minDate)) {
        return true
      }
      if (this.config?.maxDate && moment(date).isAfter(this.config.maxDate)) {
        return true
      }
      return this.disabledDates.includes(date)
    },

    // 判断是否为当前选中日期
    isCurrentDate (date) {
      if (!this.currentDate) return false
      return moment(date).format('YYYY-MM-DD') === moment(this.currentDate).format('YYYY-MM-DD')
    },

    // 选择日期
    selectDate (date) {
      if (this.isDisabled(date)) return
      this.currentDate = date
      this.$emit('update:modelValue', date)
      this.$emit('change', date)
    },

    // 前一天
    goToPrevDay () {
      const newDate = moment(this.currentDate).subtract(1, 'day')
      if (this.config?.minDate && newDate.isBefore(this.config.minDate)) {
        return
      }
      // 更新基准日期
      this.baseDate = newDate.format('YYYY-MM-DD')
      // 同时选中新的日期
      this.currentDate = this.baseDate
      this.$emit('update:modelValue', this.currentDate)
      // 触发前一天事件
      this.$emit('prev-day', this.baseDate)
      // 触发变更事件
      this.$emit('change', this.currentDate)
    },

    // 后一天
    goToNextDay () {
      const newDate = moment(this.currentDate).add(1, 'day')
      if (this.config?.maxDate && newDate.isAfter(this.config.maxDate)) {
        return
      }
      // 更新基准日期
      this.baseDate = newDate.format('YYYY-MM-DD')
      // 同时选中新的日期
      this.currentDate = this.baseDate
      this.$emit('update:modelValue', this.currentDate)
      // 触发后一天事件
      this.$emit('next-day', this.baseDate)
      // 触发变更事件
      this.$emit('change', this.currentDate)
    },

    // 前一周
    goToPrevWeek () {
      // 计算当前日期所在周的周一
      const currentDay = moment(this.baseDate)
      const dayOfWeek = currentDay.day() || 7 // 获取星期几，将周日的0转换为7
      const mondayOfWeek = currentDay.clone().subtract(dayOfWeek - 1, 'day') // 减去相应的天数得到周一

      // 前一周的周一
      const newDate = mondayOfWeek.subtract(7, 'day')

      if (this.config?.minDate && newDate.isBefore(this.config.minDate)) {
        return
      }
      this.baseDate = newDate.format('YYYY-MM-DD')
      this.$emit('prev-week', this.baseDate)
    },

    // 后一周
    goToNextWeek () {
      // 计算当前日期所在周的周一
      const currentDay = moment(this.baseDate)
      const dayOfWeek = currentDay.day() || 7 // 获取星期几，将周日的0转换为7
      const mondayOfWeek = currentDay.clone().subtract(dayOfWeek - 1, 'day') // 减去相应的天数得到周一
      // 后一周的周一
      const newDate = mondayOfWeek.add(7, 'day')
      if (this.config?.maxDate && newDate.isAfter(this.config.maxDate)) {
        return
      }
      this.baseDate = newDate.format('YYYY-MM-DD')
      this.$emit('next-week', this.baseDate)
    }
  }
}
</script>

<style scoped lang="less">
.x-timeline {
  width: 100%;
  border: 1px solid #f0f0f0;
  border-radius: 2px;
}

.x-timeline-nav {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  width: 100%;
  justify-content: space-between;
}

.timeline-dates {
  display: flex;
  flex: 1;
  justify-content: space-around;
  align-items: center;
  margin: 0 16px;
}

.date-item {
  padding: 8px 12px;
  text-align: center;
  cursor: pointer;
  border-radius: 2px;
  flex: 1;
  margin: 0 8px;
  transition: all 0.3s;
}

/* 非选中日期的悬浮效果 */
.date-item:hover:not(.ant-btn-disabled):not(.ant-btn-primary) {
  background: #e6f7ff;
  color: #1890ff;
}

/* 选中日期不需要悬浮效果 */
.date-item.ant-btn-primary:hover {
  background: #1890ff;
}

.date-item.ant-btn-primary {
  background: #0075FE !important;
  color: #fff;
}

.date-item.ant-btn-primary .weekday,
.date-item.ant-btn-primary .date {
  color: #ffffff !important;
}

/* 非选中日期悬浮时的字体颜色 */
.date-item:hover:not(.ant-btn-disabled):not(.ant-btn-primary) .weekday,
.date-item:hover:not(.ant-btn-disabled):not(.ant-btn-primary) .date {
  color: #1890ff;
}

.date-item.date-weekend:not(.ant-btn-disabled):not(.ant-btn-primary) {
  color: #ff4d4f;
}

.date-item.ant-btn-disabled {
  color: rgba(0, 0, 0, 0.25);
  background: #f5f5f5;
  cursor: not-allowed;
}

.weekday {
  font-size: 12px;
  margin-bottom: 8px;
  color: rgba(0, 0, 0, 0.45);
}

.date {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.85);
}

/* Style1 样式配置 */
.xtimeline-style1 {
  padding: 0px 0px;

  .x-timeline-nav {
    padding: 0px;
    width: 140px;
    height: 56px;

    .timeline-dates {
      margin: 0px;
      width: 980px;

      line-height: normal;
      font-weight: 700;
      letter-spacing: 0em;

    }

    .ant-btn {
      border-radius: 6px;
      border: 1px solid #CDCFD4;
      font-weight: bold;
      letter-spacing: 0em;
      font-size: 16px;
      font-family: "Source Han Sans";
      line-height: normal;
      opacity: 1;
      box-sizing: border-box;
      height: 56px;
      width: 112px;
      min-width: 112px;
      background: #FFFFFF;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .ant-btn .anticon {
      color: #94979E;
    }
  }

  .date-item {
    border-radius: 6px;
    border: 1px solid #CDCFD4;
    margin: 0px;
    padding: 0;
    width: 140px;
    opacity: 1;
    box-sizing: border-box;
    height: 56px;
    flex: 0 0 140px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;

    .date {
      font-family: Inter;
      font-size: 14px;
      font-weight: normal;
      line-height: 17px;
      height: 17px;
      opacity: 1;
      display: block;
      letter-spacing: 0px;
      font-feature-settings: "kern" on;
      color: #313131;
      width: auto;
      text-align: center;
    }

    .weekday {
      font-family: Inter;
      font-size: 18px;
      font-weight: bold;
      line-height: 17px;
      display: block;
      letter-spacing: 0px;
      font-feature-settings: "kern" on;
      color: #313131;
      margin: 0 !important;
      width: auto;
      text-align: center;
    }

    .date-item.ant-btn-primary .weekday,
    .date-item.ant-btn-primary .date {
      color: #ffffff !important;
    }
  }

  :deep(.ant-card-body) {
    padding: 16px 8px 0px;
  }
}
</style>
