<template>
  <view class="content">
    <view class="calendar-header">
      <view class="header-content">
        <view class="title-section">
          <text class="calendar-title">{{ calendarTitle }}</text>
        </view>
        <view class="nav-buttons">
          <view class="nav-btn" @click="getPrev()">
            <uni-icons type="arrow-left" size="20" color="#ffffff"></uni-icons>
            <text class="nav-text">上月</text>
          </view>
          <view class="nav-btn" @click="getNext()">
            <text class="nav-text">下月</text>
            <uni-icons type="arrow-right" size="20" color="#ffffff"></uni-icons>
          </view>
        </view>
      </view>
    </view>
    
    <div class="calendar-wrapper">
      <div v-show="type !== '3'" ref="fullcalendar" class="calendar-view" />
    </div>
    
    <view class="events-section">
      <view class="section-title">
        <text class="title-text">{{ currentDateTitle }}</text>
      </view>
      <view class="events-list">
        <view v-for="(item, index) in currentInfoList" :key="index">
          <view class="event-card" @click="enterDetails(item)">
            <view class="event-icon" :style="{ background: getEventColor(item.type) }">
              <uni-icons :type="getEventIcon(item.type)" size="16" color="#fff"></uni-icons>
            </view>
            <view class="event-content">
              <text class="event-title">{{ item.title }}</text>
            </view>
            <uni-icons type="arrow-right" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
        <view v-if="currentInfoList.length === 0" class="empty-state">
          <uni-icons type="calendar" size="60" color="#ddd"></uni-icons>
          <text class="empty-text">暂无事项</text>
        </view>
      </view>
    </view>
  </view>
  <!-- 悬停按钮刷新-->
  <refresh></refresh>
</template>

<script>
import { reactive, toRefs, ref, onMounted, getCurrentInstance } from 'vue'
import { Calendar } from '@fullcalendar/core'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import listPlugin from '@fullcalendar/list'
import interactionPlugin from '@fullcalendar/interaction'
import dayjs from 'dayjs'
import { getAccountCalendarInfo } from '@/api/invest/accountAnalysis.js'
import calendar from '@/utils/calendar.js'
export default {
  name: 'PlanManagement',
  components: {},
  setup() {
    const { proxy } = getCurrentInstance()
    const state = reactive({
      calendarTitle: new Date().getFullYear() + '年' + Number(new Date().getMonth() + 1) + '月', // 日历头部显示文字
      currentDateTitle: '', // 当前选中日期标题
      dialogVisiable: false,
      loading: false,
      type: '1',
      dialogType: '',
      detailInfo: {},
      Tcalendar: null,
      drawerVisiable: false,
      drawerType: '',
      fullcalendar: ref(),
      nowDate: new Date(),
      infoList: [], // 日历显示的列信息
      currentInfoList: [] // 当前
    })
    onMounted(() => {
      initCalendar()
      getCalendarList()
      // 初始化当前日期标题
      updateCurrentDateTitle(dayjs().format('YYYY-MM-DD'))
    })
    const initCalendar = () => {
      state.Tcalendar = new Calendar(state.fullcalendar, {
        plugins: [dayGridPlugin, timeGridPlugin, listPlugin, interactionPlugin],
        initialView: 'dayGridMonth',
        height: 'auto',
        contentHeight: 'auto',
        locale: 'zh-cn',
        handleWindowResize: true,
        editable: false,
        droppable: false,
        dayMaxEventRows: 0,
        moreLinkText: function(num) {
          return '+' + num;
        },
        displayEventTime: false,
        displayEventEnd: false,
        allDaySlot: true,
        longPressDelay: 0,
        selectLongPressDelay: 0,
        slotMinTime: '00:00:00',
        slotMaxTime: '00:00:00',
        eventOrder: 'type,color,start',
        eventDurationEditable: false,
        eventResizableFromStart: false,
        selectable: true,
        firstDay: 1,
        showNonCurrentDates: true,
        fixedWeekCount: false,
        unselectAuto: true,
        unselectCancel: '.el-drawer',
        headerToolbar: false,
        buttonText: {
          today: '回到今天',
          month: '月',
          week: '周',
          list: '列',
          day: '日'
        },
        allDayText: '全天',
        events: state.infoList,
        eventContent: function () {
          return { html: '' };
        },
        dayCellContent: function(arg) {
          const dateNum = arg.dayNumberText.replace('日', '')
          try {
            const lunar = calendar.solar2lunar(arg.date.getFullYear(), arg.date.getMonth() + 1, arg.date.getDate())
            if (!lunar || !lunar.IDayCn) {
              return {
                html: `<div class="date-cell"><div class="solar-date">${dateNum}</div></div>`
              }
            }
            const lunarText = lunar.IDayCn === '初一' ? lunar.IMonthCn : lunar.IDayCn
            return {
              html: `<div class="date-cell">
                      <div class="solar-date">${dateNum}</div>
                      <div class="lunar-date">${lunarText}</div>
                     </div>`
            }
          } catch (e) {
            return {
              html: `<div class="date-cell"><div class="solar-date">${dateNum}</div></div>`
            }
          }
        },
        moreLinkClick: function() {
          return false;
        },
        dateClick: function(info) {
          const date = dayjs(info.dateStr).format('YYYY-MM-DD');
          state.currentInfoList = [];
          state.infoList.forEach(item => {
            if(date === item.start){
              state.currentInfoList.push(item);
            }
          });
          updateCurrentDateTitle(date);
        },
        select: function (info) {
          handleSelectDate(info)
        }
      });
      state.Tcalendar.render();
    };

    const getEventColor = (type) => {
      const colors = {
        1: '#5b6cdb',  // 信用卡账单日 - 深紫色
        2: '#9c27b0',  // 类型2 - 深紫红色
        3: '#d32f2f',  // 类型3 - 深红色
        4: '#2d8f3c',  // 贷款已还 - 深绿色（已完成/成功）
        5: '#e64545',  // 日常支出 - 深红色（支出）
        6: '#f59a23',  // 投资收益 - 深橙金色（收益）
        7: '#1677cc',  // POS机刷卡 - 深蓝色
        8: '#0fa9a9'   // 工资收入 - 深青色（收入）
      };
      return colors[type] || '#8c8c8c';
    };

    const getEventIcon = (type) => {
      const icons = {
        1: 'wallet',         // 信用卡账单日 - 钱包图标
        4: 'checkmarkempty', // 贷款已还 - 对勾图标（已完成）
        5: 'cart',           // 日常支出 - 购物车图标
        6: 'star',           // 投资收益 - 星星图标（收益/增值）
        7: 'scan',           // POS机刷卡 - 扫描图标
        8: 'wallet'          // 工资收入 - 钱包图标（收入）
      };
      return icons[type] || 'calendar';
    };
    // 上一月、周、日
    const getPrev = () => {
      state.Tcalendar.prev()
      state.calendarTitle = state.Tcalendar.view.title
      getCalendarList()
    }
    // 下一月、周、日
    const getNext = () => {
      state.Tcalendar.next()
      state.calendarTitle = state.Tcalendar.view.title
      getCalendarList()
    }
    // 回到今天
    const morLinkFunction = (jsEvent) => {
      return jsEvent.shortText;
    }
    const getCalendarList = () => {
      const currentEnd = dayjs(state.Tcalendar.view.currentEnd).add(-1, 'day')
      const params = {
        startTime: dayjs(state.Tcalendar.view.currentStart).format('YYYY-MM-DD'),
        endTime: dayjs(currentEnd).format('YYYY-MM-DD'),
        type: state.type
      }
      state.loading = true
      state.Tcalendar.getEventSources().forEach((item) => {
        item.remove()
      })

      getAccountCalendarInfo(params).then((res) => {
        state.loading = false
        if (res) {
          state.infoList = res.data
          state.Tcalendar.addEventSource(state.infoList)
          // 数据加载完成后更新1号的事项
          updateFirstDayEvents()
        }
      })
    }

    // 更新当前日期标题
    const updateCurrentDateTitle = (dateStr) => {
      const date = dayjs(dateStr)
      const today = dayjs()
      
      if (date.format('YYYY-MM-DD') === today.format('YYYY-MM-DD')) {
        state.currentDateTitle = '今日事项 (' + date.format('MM月DD日') + ')'
      } else {
        state.currentDateTitle = date.format('YYYY年MM月DD日') + ' 事项'
      }
    }

    // 更新为合适的日期事项：当月显示今天，其他月份显示1号
    const updateFirstDayEvents = () => {
      // 获取当前视图的年月
      const currentStart = state.Tcalendar.view.currentStart
      const viewYear = currentStart.getFullYear()
      const viewMonth = currentStart.getMonth() + 1
      
      // 获取今天的年月
      const today = new Date()
      const todayYear = today.getFullYear()
      const todayMonth = today.getMonth() + 1
      
      let targetDate
      
      // 如果是当前月份，显示今天的数据；否则显示1号的数据
      if (viewYear === todayYear && viewMonth === todayMonth) {
        targetDate = dayjs().format('YYYY-MM-DD')
      } else {
        const month = String(viewMonth).padStart(2, '0')
        targetDate = `${viewYear}-${month}-01`
      }
      
      // 筛选目标日期的事项
      state.currentInfoList = []
      state.infoList.forEach(item => {
        if(targetDate === item.start){
          state.currentInfoList.push(item)
        }
      })
      
      // 更新日期标题
      updateCurrentDateTitle(targetDate)
    }

    const enterDetails = (info) => {
      const date = info.start
  const type = info.type
  const accountId = info.accountId
  const billDatePeriod = info.billDatePeriod
  //信用卡账单日
  if (type === 1) {
    const _id = accountId
    uni.navigateTo({ url: `/pages/calendar/list?accountId=${_id}&billDatePeriod=${billDatePeriod}` })
  }
  //贷款已还
  if (type === 4) {
    const _id = accountId
    const billDatePeriod = date+'~'+date
    uni.navigateTo({ url: `/pages/calendar/list?accountId=${_id}&billDatePeriod=${billDatePeriod}&dealType=1&dealCategory=9` })
  }
  //日常支出
  if (type === 5) {
    const billDatePeriod =  date+'~'+date
    uni.navigateTo({ url: `/pages/calendar/list?billDatePeriod=${billDatePeriod}&dealType=2&dealCategory=1` })
  }

  //投资收益
  if (type === 6) {
    const billDatePeriod =  date+'~'+date
    uni.navigateTo({ url: `/pages/calendar/list?billDatePeriod=${billDatePeriod}&dealCategory=2` })
  }
  //POS机刷卡
  if (type === 7) {
    const billDatePeriod =  date+'~'+date
    uni.navigateTo({ url: `/pages/calendar/list?billDatePeriod=${billDatePeriod}&dealType=2&dealCategory=5` })
  }

  //工资收入
  if (type === 8) {
    const billDatePeriod =  date+'~'+date
    uni.navigateTo({ url: `/pages/calendar/list?billDatePeriod=${billDatePeriod}&dealCategory=11` })

  }
    }
    // 点击计划查看
const handleClick = (info) => {
  const date = info.event.startStr
  const type = info.event._def.extendedProps.type
  const accountId = info.event._def.extendedProps.accountId
  const billDatePeriod = info.event._def.extendedProps.billDatePeriod
  //信用卡账单日
  if (type === 1) {
    const _id = accountId
    uni.navigateTo({ url: `/pages/calendar/list?accountId=${_id}&billDatePeriod=${billDatePeriod}` })
  }
  //贷款已还
  if (type === 4) {
    const _id = accountId
    const billDatePeriod = date+'~'+date
    uni.navigateTo({ url: `/pages/calendar/list?accountId=${_id}&billDatePeriod=${billDatePeriod}&dealType=1&dealCategory=9` })
  }
  //日常支出
  if (type === 5) {
    const billDatePeriod =  date+'~'+date
    uni.navigateTo({ url: `/pages/calendar/list?billDatePeriod=${billDatePeriod}&dealType=2&dealCategory=1` })
  }

  //投资收益
  if (type === 6) {
    const billDatePeriod =  date+'~'+date
    uni.navigateTo({ url: `/pages/calendar/list?billDatePeriod=${billDatePeriod}&dealCategory=2` })
  }
  //POS机刷卡
  if (type === 7) {
    const billDatePeriod =  date+'~'+date
    uni.navigateTo({ url: `/pages/calendar/list?billDatePeriod=${billDatePeriod}&dealType=2&dealCategory=5` })
  }

  //工资收入
  if (type === 8) {
    const billDatePeriod =  date+'~'+date
    uni.navigateTo({ url: `/pages/calendar/list?billDatePeriod=${billDatePeriod}&dealCategory=11` })

  }
}
// 拖拽触发
const handleSelectDate = (info) => {
  const selectDate = info.startStr
  state.currentInfoList = []
  state.infoList.forEach(item => {
    if(selectDate == item.start){
      state.currentInfoList.push(item)
    }
  })
  // 更新日期标题
  updateCurrentDateTitle(selectDate)
}

    return {
      ...toRefs(state),
      getPrev,
      handleSelectDate,
      enterDetails,
      handleClick,
      getNext,
      morLinkFunction,
      getCalendarList,
      getEventColor,
      getEventIcon,
      updateFirstDayEvents,
      updateCurrentDateTitle
    }
  }
}
</script>
<style lang="scss" scoped>
.content {
  background-color: #f5f7fa;
}

.calendar-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 16rpx 32rpx;
  box-shadow: 0 2rpx 12rpx rgba(102, 126, 234, 0.3);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  display: flex;
  align-items: center;
}

.calendar-title {
  font-size: 34rpx;
  font-weight: 700;
  color: #ffffff;
}

.nav-buttons {
  display: flex;
  gap: 24rpx;
}

.nav-btn {
  display: flex;
  align-items: center;
  gap: 6rpx;
  padding: 10rpx 16rpx;
  background: rgba(255, 255, 255, 0.25);
  border-radius: 20rpx;
  backdrop-filter: blur(10rpx);
}

.nav-btn:active {
  background: rgba(255, 255, 255, 0.35);
}

.nav-text {
  font-size: 26rpx;
  color: #ffffff;
  font-weight: 500;
}

.calendar-wrapper {
  padding: 12rpx;
  background: #ffffff;
  margin: 12rpx 16rpx 0;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
  overflow: visible;
  flex-shrink: 0;
}

.calendar-view {
  min-height: 320rpx;
  overflow: visible;
}

.events-section {
  margin: 6rpx 16rpx 10rpx;
  background: #ffffff;
  border-radius: 16rpx;
  padding: 20rpx 16rpx 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
  min-height: 400rpx;
}

.events-list {
  /* 不设置 overflow，让它自然显示 */
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
  padding-left: 16rpx;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    left: 0;
    width: 6rpx;
    height: 24rpx;
    background: linear-gradient(135deg, #667eea, #764ba2);
    border-radius: 3rpx;
  }
}

.title-bar {
  display: none;
}

.title-text {
  font-size: 26rpx;
  font-weight: 600;
  color: #333;
}

.event-card {
  display: flex;
  align-items: center;
  padding: 4rpx 10rpx;
  background: #f8f9fa;
  border-radius: 10rpx;
  margin-bottom: 10rpx;
  transition: all 0.3s;
}

.event-card:active {
  background: #e9ecef;
  transform: scale(0.98);
}

.event-icon {
  width: 44rpx;
  height: 44rpx;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
  
  :deep(.uni-icons) {
    display: flex !important;
    align-items: center;
    justify-content: center;
  }
}

.event-content {
  flex: 1;
  min-width: 0;
}

.event-title {
  font-size: 26rpx;
  font-weight: 500;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50rpx 0;
}

.empty-text {
  margin-top: 12rpx;
  font-size: 22rpx;
  color: #999;
}

/* FullCalendar 样式优化 */
:deep(.fc) {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

:deep(.fc-theme-standard td),
:deep(.fc-theme-standard th) {
  border-color: #e9ecef;
}

:deep(.fc-col-header-cell) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 6rpx 0;
  font-weight: 600;
  color: #ffffff;
  font-size: 22rpx;
  border: none;
}

:deep(.fc-col-header-cell-cushion) {
  color: #ffffff;
}

:deep(.fc-daygrid-day) {
  cursor: pointer;
}

:deep(.fc-daygrid-day:hover) {
  background: #f8f9fa;
}

:deep(.fc-daygrid-day-frame) {
  min-height: 35px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

:deep(.fc-scrollgrid) {
  border: none !important;
}

:deep(.fc-scrollgrid-section) {
  overflow: visible !important;
}

:deep(.fc-day-today) {
  background: rgba(102, 126, 234, 0.15) !important;
  border: 2rpx solid rgba(102, 126, 234, 0.4) !important;
}

:deep(.fc-daygrid-day-number) {
  padding: 2rpx;
  font-size: 26rpx;
  font-weight: 600;
  color: #333;
}

:deep(.date-cell) {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 0;
  height: 100%;
}

:deep(.solar-date) {
  font-size: 22rpx;
  font-weight: 600;
  color: #333;
  line-height: 1;
}

:deep(.lunar-date) {
  font-size: 16rpx;
  color: #999;
  line-height: 1;
  margin-top: 2rpx;
  transform: scale(0.9);
}

:deep(.fc-day-today .solar-date) {
  color: #667eea;
}

:deep(.fc-day-today .lunar-date) {
  color: #667eea;
  opacity: 0.8;
}

:deep(.fc-day-other .solar-date) {
  color: #adb5bd !important;
}

:deep(.fc-day-other .lunar-date) {
  color: #ced4da !important;
}

:deep(.fc-daygrid-day-top) {
  flex-direction: row;
  margin-bottom: 2rpx;
}

:deep(.fc-daygrid-day-events) {
  margin: 0;
  padding: 0;
}

:deep(.fc-event) {
  display: none !important;
}

:deep(.fc-daygrid-more-link) {
  color: #ff4757;
  background: transparent;
  border: none;
  border-radius: 0;
  padding: 0 2rpx;
  font-size: 20rpx;
  font-weight: 700;
  margin: 0;
  display: inline-block;
  box-shadow: none;
  line-height: 1;
  pointer-events: none;
  cursor: default;
}

:deep(.fc-daygrid-more-link:hover) {
  color: #ff4757;
  background: transparent;
  text-decoration: none;
  transform: none;
}

:deep(.fc-popover) {
  display: none !important;
}

:deep(.fc-day-other) {
  background: #f8f9fa !important;
}

:deep(.fc-day-other .fc-daygrid-day-number) {
  color: #adb5bd !important;
}

:deep(.plan_title) {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.fc-daygrid-event-dot) {
  display: none;
}

:deep(.fc-more-link) {
  color: #667eea;
  font-size: 22rpx;
  font-weight: 500;
}
</style>
