<template>
  <view class="card history-card">
    <view class="history-header">
      <text class="history-title">📊 历史标的池回顾</text>
    </view>
    
    <!-- 日期区间选择 -->
    <view class="date-range-row">
      <view class="date-input" @click="openStartDatePicker">
        <text class="date-text">{{ formatDateDisplay(startDate) }}</text>
        <text class="date-icon">📅</text>
      </view>
      
      <text class="date-separator">至</text>
      
      <view class="date-input" @click="openEndDatePicker">
        <text class="date-text">{{ formatDateDisplay(endDate) }}</text>
        <text class="date-icon">📅</text>
      </view>
    </view>
    
    <!-- 查询按钮 -->
    <view class="history-search-button-full" @click="onSearch">
      <text class="search-button-text">🔍 查询历史数据</text>
    </view>
    
    <text class="history-tip">选择时间区间，查询该期间的入池样本及表现。</text>
    
    <!-- 自定义日期选择弹窗 -->
    <view v-if="showDatePicker" class="date-picker-mask" @click="closeDatePicker">
      <view class="date-picker-popup" @click.stop>
        <view class="picker-header">
          <text class="picker-cancel" @click="closeDatePicker">取消</text>
          <text class="picker-title">{{ currentPickerType === 'start' ? '选择开始日期' : '选择结束日期' }}</text>
          <text class="picker-confirm" @click="confirmDate">确定</text>
        </view>
        
        <!-- 年月选择 -->
        <view class="month-selector">
          <view class="month-nav" @click="prevMonth">
            <text class="nav-arrow">‹</text>
          </view>
          <text class="current-month">{{ tempYear }}年{{ tempMonth }}月</text>
          <view class="month-nav" @click="nextMonth">
            <text class="nav-arrow">›</text>
          </view>
        </view>
        
        <!-- 星期标题 -->
        <view class="weekday-row">
          <text class="weekday-item" v-for="day in weekDays" :key="day">{{ day }}</text>
        </view>
        
        <!-- 日期网格 -->
        <view class="days-grid">
          <view 
            v-for="(day, index) in calendarDays" 
            :key="index"
            :class="['day-item', { 
              'empty': !day, 
              'selected': day && isSelected(day),
              'today': day && isToday(day)
            }]"
            @click="day && selectDay(day)"
          >
            <text v-if="day" class="day-text">{{ day }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { isLoggedIn as checkLoginStatus } from '../utils/auth.js'

const props = defineProps({
  poolType: { type: Number, default: 1 },
  canSearch: { type: Boolean, default: false }
})

const emit = defineEmits(['dateChange'])

// 获取默认日期（当前月份的第一天和最后一天）
const getDefaultDates = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const lastDay = new Date(year, now.getMonth() + 1, 0).getDate()
  return {
    start: `${year}-${month}-01`,
    end: `${year}-${month}-${lastDay}`
  }
}

const defaultDates = getDefaultDates()
const startDate = ref(defaultDates.start)
const endDate = ref(defaultDates.end)

// 日期选择器状态
const showDatePicker = ref(false)
const currentPickerType = ref('start') // 'start' | 'end'
const tempYear = ref(new Date().getFullYear())
const tempMonth = ref(new Date().getMonth() + 1)
const tempSelectedDay = ref(1)

const weekDays = ['日', '一', '二', '三', '四', '五', '六']

// 计算当月日历
const calendarDays = computed(() => {
  const days = []
  const firstDay = new Date(tempYear.value, tempMonth.value - 1, 1).getDay()
  const daysInMonth = new Date(tempYear.value, tempMonth.value, 0).getDate()
  
  // 填充空白
  for (let i = 0; i < firstDay; i++) {
    days.push(null)
  }
  // 填充日期
  for (let i = 1; i <= daysInMonth; i++) {
    days.push(i)
  }
  return days
})

// 格式化日期显示
const formatDateDisplay = (dateStr) => {
  if (!dateStr) return '请选择'
  const [year, month, day] = dateStr.split('-')
  return `${year}/${month}/${day}`
}

// 通知父组件日期变化
const emitDateChange = () => {
  emit('dateChange', {
    startDate: startDate.value,
    endDate: endDate.value,
    poolType: props.poolType
  })
}

// 打开开始日期选择器
const openStartDatePicker = () => {
  currentPickerType.value = 'start'
  const [year, month, day] = startDate.value.split('-').map(Number)
  tempYear.value = year
  tempMonth.value = month
  tempSelectedDay.value = day
  showDatePicker.value = true
}

// 打开结束日期选择器
const openEndDatePicker = () => {
  currentPickerType.value = 'end'
  const [year, month, day] = endDate.value.split('-').map(Number)
  tempYear.value = year
  tempMonth.value = month
  tempSelectedDay.value = day
  showDatePicker.value = true
}

// 关闭日期选择器
const closeDatePicker = () => {
  showDatePicker.value = false
}

// 上一月
const prevMonth = () => {
  if (tempMonth.value === 1) {
    tempMonth.value = 12
    tempYear.value--
  } else {
    tempMonth.value--
  }
}

// 下一月
const nextMonth = () => {
  if (tempMonth.value === 12) {
    tempMonth.value = 1
    tempYear.value++
  } else {
    tempMonth.value++
  }
}

// 选择日期
const selectDay = (day) => {
  tempSelectedDay.value = day
}

// 判断是否选中
const isSelected = (day) => {
  return day === tempSelectedDay.value
}

// 判断是否今天
const isToday = (day) => {
  const today = new Date()
  return tempYear.value === today.getFullYear() && 
         tempMonth.value === today.getMonth() + 1 && 
         day === today.getDate()
}

// 确认选择
const confirmDate = () => {
  const dateStr = `${tempYear.value}-${String(tempMonth.value).padStart(2, '0')}-${String(tempSelectedDay.value).padStart(2, '0')}`
  
  if (currentPickerType.value === 'start') {
    startDate.value = dateStr
  } else {
    endDate.value = dateStr
  }
  
  showDatePicker.value = false
  emitDateChange()
}

const onSearch = () => {
  if (!startDate.value || !endDate.value) {
    uni.showToast({ title: '请选择开始和结束日期', icon: 'none' })
    return
  }

  if (startDate.value > endDate.value) {
    uni.showToast({ title: '开始日期不能晚于结束日期', icon: 'none' })
    return
  }

  // 检查登录状态
  if (!checkLoginStatus()) {
    uni.showModal({
      title: '登录提示',
      content: '此功能需要登录后使用，是否前往登录？',
      confirmText: '去登录',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({ url: '/pages/login/login' })
        }
      }
    })
    return
  }

  // 跳转到历史查询结果页面
  uni.navigateTo({
    url: `/pages/history/history?startDate=${startDate.value}&endDate=${endDate.value}&poolType=${props.poolType}`
  })
}

// 组件挂载时通知父组件默认日期
onMounted(() => {
  emitDateChange()
})
</script>

<style scoped>
.card {
  background: #ffffff;
  border-radius: 24rpx;
  box-shadow: 0 16rpx 40rpx rgba(37, 52, 94, 0.08);
  margin-bottom: 32rpx;
}

.history-card {
  padding: 32rpx;
}

.history-header {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}

.history-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #222222;
}

.date-range-row {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 24rpx;
}

.date-separator {
  font-size: 26rpx;
  color: #666a7f;
  padding: 0 8rpx;
}

.date-input {
  flex: 1;
  background: #f7f8fc;
  border-radius: 12rpx;
  padding: 24rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.date-text {
  font-size: 26rpx;
  color: #222222;
}

.date-icon {
  font-size: 24rpx;
}

.history-search-button-full {
  width: 100%;
  background: linear-gradient(135deg, #5d55e8, #7568ff);
  border-radius: 16rpx;
  padding: 28rpx 0;
  text-align: center;
  margin-top: 12rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 8rpx 20rpx rgba(93, 85, 232, 0.3);
}

.search-button-text {
  font-size: 28rpx;
  font-weight: 600;
  color: #ffffff;
}

.history-tip {
  font-size: 24rpx;
  color: #9ca2b5;
  line-height: 1.6;
}

/* 日期选择器弹窗 */
.date-picker-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.date-picker-popup {
  width: 100%;
  background: #ffffff;
  border-radius: 32rpx 32rpx 0 0;
  padding: 32rpx;
  padding-bottom: calc(32rpx + env(safe-area-inset-bottom));
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;
}

.picker-cancel {
  font-size: 28rpx;
  color: #999999;
  padding: 16rpx;
}

.picker-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #222222;
}

.picker-confirm {
  font-size: 28rpx;
  color: #5d55e8;
  font-weight: 600;
  padding: 16rpx;
}

.month-selector {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 24rpx;
  gap: 48rpx;
}

.month-nav {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f7f8fc;
  border-radius: 50%;
}

.nav-arrow {
  font-size: 36rpx;
  color: #5d55e8;
  font-weight: bold;
}

.current-month {
  font-size: 32rpx;
  font-weight: 600;
  color: #222222;
  min-width: 200rpx;
  text-align: center;
}

.weekday-row {
  display: flex;
  margin-bottom: 16rpx;
}

.weekday-item {
  flex: 1;
  text-align: center;
  font-size: 24rpx;
  color: #999999;
  padding: 16rpx 0;
}

.days-grid {
  display: flex;
  flex-wrap: wrap;
}

.day-item {
  width: 14.28%;
  aspect-ratio: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.day-item.empty {
  background: transparent;
}

.day-text {
  width: 72rpx;
  height: 72rpx;
  line-height: 72rpx;
  text-align: center;
  font-size: 28rpx;
  color: #222222;
  border-radius: 50%;
}

.day-item.selected .day-text {
  background: linear-gradient(135deg, #5d55e8, #7568ff);
  color: #ffffff;
  font-weight: 600;
}

.day-item.today .day-text {
  border: 2rpx solid #5d55e8;
}

.day-item.today.selected .day-text {
  border: none;
}
</style>
