<template>
  <div class="calendar-wrapper" :style="config.styles?.wrapper">
    <!-- 顶部标题栏 -->
    <div v-if="config.header.show" class="header-bar" :style="config.styles?.header">
      <div class="left">
        <svg v-if="config.header.showIcon" class="calendar-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <rect
            x="3"
            y="4"
            width="18"
            height="18"
            rx="2"
            ry="2"
            stroke="#0057FE"
            stroke-width="2"/>
          <line
            x1="16"
            y1="2"
            x2="16"
            y2="6"
            stroke="#0057FE"
            stroke-width="2"/>
          <line
            x1="8"
            y1="2"
            x2="8"
            y2="6"
            stroke="#0057FE"
            stroke-width="2"/>
          <line
            x1="3"
            y1="10"
            x2="21"
            y2="10"
            stroke="#0057FE"
            stroke-width="2"/>
        </svg>
        <input type="text" :value="config.header.title" class="title-input" :style="config.styles?.titleInput"/>
      </div>
      <div class="right">
        <a-button v-if="config.header.showBackToToday" type="link" @click="backToToday">{{
          config.header.backToTodayText
        }}
        </a-button>
        <a-button v-if="config.header.showMonth" type="link" :disabled="!config.header.monthClickable">{{
          todayMonth
        }}
        </a-button>
        <a-button v-if="config.header.showDay" type="link" :disabled="!config.header.dayClickable">{{
          todayDay
        }}
        </a-button>
      </div>
    </div>

    <!-- 日历内容 -->
    <div class="calendar-content" :style="config.styles?.calendarContent">
      <!-- 子标题栏 -->
      <div v-if="config.subHeader.show" class="sub-header" :style="config.styles?.subHeader">
        <div class="title">
          <span class="current-date" :style="config.styles?.currentDate">{{ currentDateText }}</span>
          <span class="year" :style="config.styles?.year">{{ currentYearText }}</span>
        </div>
        <div class="actions">
          <span
            v-for="(action, index) in config.actions"
            :key="index"
            class="action-item"
            :style="config.styles?.actionItem"
            @click="handleAction(action)">
            {{ action.text }}
          </span>
          <a-button v-if="config.subHeader.showNavigation" type="link" @click="prevMonth">
            {{ config.subHeader.prevMonthText }}
          </a-button>
          <a-button v-if="config.subHeader.showNavigation" type="link" @click="nextMonth">
            {{ config.subHeader.nextMonthText }}
          </a-button>
        </div>
      </div>

      <a-calendar
        ref="calendar"
        :value="currentDate"
        :fullscreen="config.calendar.fullscreen"
        @select="handleSelect"
      />
    </div>
  </div>
</template>

<script>
import { Calendar, Button } from 'ant-design-vue'
import moment from 'moment'
import 'moment/locale/zh-cn'
import { getConfigByName } from '@vue2-client/services/api/common'

// 设置中文
moment.locale('zh-cn')

// 默认配置
const defaultConfig = {
  header: {
    show: true,
    title: '我的日程',
    showIcon: true,
    showBackToToday: true,
    backToTodayText: '返回当天',
    showMonth: true,
    showDay: true,
    monthClickable: false,
    dayClickable: false
  },
  subHeader: {
    show: true,
    showNavigation: true,
    prevMonthText: '←',
    nextMonthText: '→'
  },
  calendar: {
    fullscreen: false,
    locale: 'zh-cn'
  },
  // 操作按钮
  actions: [
    {
      text: '+ 新增日程',
      type: 'add',
      handler: 'handleAdd'
    }
  ],
  // 自定义样式
  styles: {
    wrapper: {},
    header: {},
    titleInput: {},
    subHeader: {},
    currentDate: {},
    year: {},
    actionItem: {},
    calendarContent: {}
  },
  // 事件配置
  events: {
    select: 'select',
    backToToday: 'back-to-today',
    action: 'action',
    add: 'add',
    monthChange: 'month-change',
    init: 'init'
  }
}

export default {
  name: 'XCalendar',
  components: {
    ACalendar: Calendar,
    AButton: Button
  },
  props: {
    // 接收配置
    configName: {
      type: String,
      default: ''
    }
  },
  data () {
    const today = moment()
    return {
      currentDate: moment(),
      todayMonth: today.month() + 1,
      todayDay: today.date(),
      // 合并默认配置和传入的配置
      mergedConfig: {}
    }
  },
  created () {
    this.getData(this.configName)
  },
  computed: {
    // 使用计算属性访问合并后的配置
    config () {
      return this.mergedConfig
    },
    currentDateText () {
      const month = this.currentDate.month() + 1
      const day = this.currentDate.date()
      return `${this.numberToChinese(month)}月${this.numberToChinese(day)}日`
    },
    currentYearText () {
      return this.currentDate.format('YYYY')
    }
  },
  methods: {
    // 获取配置
    getData (config) {
      console.warn(config)
      getConfigByName(config, 'af-his', res => {
        // 深度合并配置
        this.mergedConfig = this.mergeConfig(defaultConfig, res)
        this.$emit(this.mergedConfig.events.init, this.currentDate)
      })
    },
    // 深度合并配置
    mergeConfig (defaultConfig, userConfig) {
      const result = { ...defaultConfig }

      for (const key in userConfig) {
        if (typeof userConfig[key] === 'object' && userConfig[key] !== null &&
          typeof defaultConfig[key] === 'object' && defaultConfig[key] !== null) {
          result[key] = this.mergeConfig(defaultConfig[key], userConfig[key])
        } else if (userConfig[key] !== undefined) {
          result[key] = userConfig[key]
        }
      }

      return result
    },
    numberToChinese (num) {
      const chineseNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
      if (num <= 10) return chineseNums[num]
      if (num < 20) return '十' + (num % 10 === 0 ? '' : chineseNums[num % 10])
      return chineseNums[Math.floor(num / 10)] + '十' + (num % 10 === 0 ? '' : chineseNums[num % 10])
    },
    handleSelect (date) {
      this.currentDate = date
      // 触发选择事件，使用配置的事件名
      this.$emit(this.config.events.select, date)
    },
    prevMonth () {
      // 使用moment API直接操作日期
      this.currentDate = moment(this.currentDate).subtract(1, 'month')
      // 触发月份变化事件
      this.$emit(this.config.events.monthChange, this.currentDate)
    },
    nextMonth () {
      // 使用moment API直接操作日期
      this.currentDate = moment(this.currentDate).add(1, 'month')
      // 触发月份变化事件
      this.$emit(this.config.events.monthChange, this.currentDate)
    },
    backToToday () {
      // 返回当天
      this.currentDate = moment()
      // 触发返回今天事件
      this.$emit(this.config.events.backToToday, this.currentDate)
    },
    // 处理操作按钮点击
    handleAction (action) {
      // 检查是否有注册的处理方法
      if (action.type && typeof this[`handle${action.type.charAt(0).toUpperCase() + action.type.slice(1)}`] === 'function') {
        // 调用对应的处理方法
        this[`handle${action.type.charAt(0).toUpperCase() + action.type.slice(1)}`](action)
      } else if (action.handler && typeof this.$parent[action.handler] === 'function') {
        // 调用父组件的方法
        this.$parent[action.handler](this.currentDate, action)
      }
      // 触发点击事件
      this.$emit(this.config.events.action, this.currentDate)
    },
    // 默认的新增处理方法
    handleAdd (action) {
      this.$emit(this.config.events.add, this.currentDate)
    }
  },
  watch: {
    // 监听配置参数名称变化
    queryParamsName: {
      handler (newValue) {
        this.getData(newValue)
      },
      deep: true,
    }
  }
}
</script>

<style scoped lang="less">
.calendar-wrapper {
  background: #fff;
  border-radius: 8px;
  padding: 3px;
}

/* 顶部标题栏样式 */
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  border-bottom: 2px solid #0057FE;
  margin-bottom: 16px;
}

.header-bar .left {
  display: flex;
  align-items: center;
}

.calendar-icon {
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 8px;
}

.title-input {
  border: none;
  font-size: 16px;
  font-weight: 500;
  outline: none;
  color: #000;
  background-color: transparent;
  width: 200px;
}

.header-bar .right {
  display: flex;
}

.sub-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.title {
  display: flex;
  gap: 8px;
  align-items: baseline;
}

.current-date {
  font-size: 24px;
  font-weight: 500;
}

.year {
  color: #999;
  font-size: 16px;
}

.actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.action-item {
  color: #666;
  cursor: pointer;
}

.calendar-content {
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  padding: 16px;

  :deep(.ant-fullcalendar-header) {
    display: none;
  }

  :deep(.ant-fullcalendar) {
    border: none;
    border-radius: 0;
  }

  :deep(.ant-fullcalendar-calendar-body) {
    padding: 8px 12px;
  }

  :deep(.ant-fullcalendar-column-header) {
    text-align: center;
    padding: 12px 0;

    .ant-fullcalendar-column-header-inner {
      display: inline-block;
      font-weight: normal;
    }
  }

  :deep(.ant-fullcalendar-cell) {
    padding: 4px 0;
  }

  :deep(.ant-fullcalendar-date) {
    height: 24px;
    margin: 0 4px;
    padding: 4px;
    border-radius: 2px;
    border: none;
    width: auto;
    text-align: center;
  }

  :deep(.ant-fullcalendar-selected-day .ant-fullcalendar-value) {
    background: #000;
    color: #fff;
    border-radius: 50%;
  }
}
</style>
