<template>
  <view class="px-30 py-30 bg-white">
    <view class="flex gap-x-20">
      <view class="flex items-center gap-x-20 flex-wrap">
        <view class="picker-wrap">
          <ie-picker ref="pickerRef" v-model="form.year" :list="yearList" placeholder="请选择" title="选择年份" :fontSize="14"
            icon="arrow-down" key-label="label" key-value="value" @change="handleYearChange">
            <template #default="{ label }">
              <text>{{ label }}年</text>
            </template>
          </ie-picker>
        </view>
        <view class="picker-wrap">
          <ie-picker ref="pickerRef" :disabled="!form.year" v-model="form.month" :list="monthList" placeholder="请选择"
            title="选择月份" :fontSize="14" icon="arrow-down" key-label="label" key-value="value"
            @change="handleMonthChange">
            <template #default="{ label }">
              <text>{{ label }}</text>
            </template>
          </ie-picker>
        </view>
        <view :class="['btn-wrap transition-all duration-200', calendarButtonClass]"
          @click="canOpenCalendar ? handleOpenCalendar() : null">
          <text class="text-[14px]">刷题日历</text>
          <uv-icon name="search" size="16" :color="canOpenCalendar ? 'white' : '#CCCCCC'" />
        </view>
      </view>
    </view>
    <view class="mt-30 flex h-280 gap-x-20">
      <view class="flex-1 h-full relative">
        <ie-echart :option="options1" />
        <div class="absolute top-0 left-0 w-full h-full flex flex-col items-center justify-center">
          <div class="text-40 text-fore-title font-bold">{{ statistics.total }}</div>
          <div class="text-22 text-fore-light">刷题总量</div>
        </div>
      </view>
      <view class="flex-1 h-full relative">
        <ie-echart :option="options2" />
        <div class="absolute top-0 left-0 w-full h-full flex flex-col items-center justify-center">
          <div class="text-40 text-fore-title font-bold">{{ statistics.rate }}%</div>
          <div class="text-22 text-fore-light">正确率</div>
        </div>
      </view>
    </view>
    <view class="mt-30 flex items-center">
      <text>已累计刷题</text>
      <text class="text-32 text-primary">{{ practiceDays }}</text>
      <text>天～</text>
    </view>
    <view v-if="(form.month) && displayMode !== 'year'" class="mt-30">
      <ie-table :tableColumns="tableColumns" :data="tableDate">
        <template #date="{ item }">
          <text class="font-bold">{{ item.date }}</text>
        </template>
        <template #questionNum="{ item }">
          <text class="font-bold">{{ item.questionNum }}</text>
        </template>
        <template #correctNum="{ item }">
          <text class="font-bold" :class="[item.info < 70 ? 'text-danger' : 'text-fore-title']">{{ item.info }}%</text>
        </template>
      </ie-table>
    </view>
    <ie-popup ref="calendarPopupRef" :showToolbar="false" v-if="canOpenCalendar">
      <view class="h-[420px]">
        <view class="h-108 flex items-center justify-center border-0 border-b border-solid border-border">
          <view :class="['w-38 h-38 rounded-full flex items-center justify-center transition-all duration-200', prevButtonClass]" @click="canGoPrev && !loading ? handlePrev() : null">
            <uv-icon name="arrow-left" size="12" :color="canGoPrev && !loading ? '#808080' : '#CCCCCC'" />
          </view>
          <view class="mx-40 text-30 text-fore-title font-bold">
            <text>{{ calendarTitle }}</text>
          </view>
          <view :class="['w-38 h-38 rounded-full flex items-center justify-center transition-all duration-200', nextButtonClass]" @click="canGoNext && !loading ? handleNext() : null">
            <uv-icon name="arrow-right" size="12" :color="canGoNext && !loading ? '#808080' : '#CCCCCC'" />
          </view>
        </view>
        <view class="relative">
          <view class="px-40 py-20 flex items-center justify-between">
            <view class=" text-28">
              <text>{{ calendarSubTitle }}</text>
              <text class="text-32 text-primary font-bold">{{ practiceDays }}</text>
              <text>天～</text>
            </view>
            <!-- <uv-icon name="question-circle" size="18" color="#31a0fc" /> -->
          </view>

          <uni-calendar ref="calendarRef" :insert="true" :lunar="false" :readonly="true" :showMonth="false"
            :sundayFirst="false" :highlightToday="false" :showToolbar="false" :displayMode="displayMode"
            :selected="selected" :date="currentDate" @change-week="handleCalendarWeekChange"
            @monthSwitch="handleCalendarMonthSwitch">
            <template #calendar-item="{ weeks }">
              <view class="calendar-item" :class="{
                'calendar-item--week-mode-disabled': weeks.isWeekModeDisabled,
                'uni-calendar-item--disable': !weeks.isCurrentMonth,
                'calendar-item--valid': weeks.extraInfo && weeks.extraInfo.info >= 70,
                'calendar-item--invalid': weeks.extraInfo && weeks.extraInfo.info < 70
              }">
                <view class="date">{{ weeks.date }}</view>
                <view class="info">
                  <text v-if="weeks.extraInfo && weeks.extraInfo.info">{{ weeks.extraInfo.info }}%</text>
                </view>
              </view>
            </template>
          </uni-calendar>
          <!-- Loading 覆盖层 -->
          <view v-if="loading" class="calendar-loading-overlay">
            <uv-loading-icon mode="circle" size="32" color="#31a0fc" />
          </view>
        </view>
      </view>
    </ie-popup>
  </view>
</template>
<script lang="ts" setup>
import { TableColumnConfig } from '@/types';
import ieEchart from './ie-echart/ie-echart.vue';
import { useCalendar } from '@/composables/useCalendar';

const props = defineProps<{
  recordId?: number;
}>();
// 使用 useCalendar composable
const {
  selected,
  statistics,
  currentDate,
  yearList,
  displayMode,
  currentMonthRange,
  canGoPrev,
  canGoNext,
  loading,
  currentYear,
  currentMonth,
  goToPrevMonth,
  goToNextMonth,
  goToYear,
  goToYearMonth,
  initializeFormData,
  init: initCalendar
} = useCalendar();

// 表单数据 - 与日历同步
const form = ref({
  year: '',
  month: '',
})
// 月份列表（不能超过当前月份）
const monthList = computed(() => {
  const today = new Date();
  const currentYearToday = today.getFullYear();
  const currentMonthToday = today.getMonth() + 1;
  const selectedYear = parseInt(form.value.year) || currentYear.value;

  const months = [];
  const maxMonth = selectedYear === currentYearToday ? currentMonthToday : 12;

  for (let i = 1; i <= maxMonth; i++) {
    months.push({
      label: `${i}月`,
      value: i.toString()
    });
  }
  return months;
});


// 检查是否可以选择日历
const canOpenCalendar = computed(() => {
  // 必须选择年份
  if (!form.value.year) {
    return false;
  }

  // 如果是month模式，必须选择月份
  if (displayMode.value === 'month') {
    return !!form.value.month;
  }

  // 如果是year模式，不能打开日历（年份模式不显示记录表）
  return false;
});

// 导航按钮样式计算属性
const prevButtonClass = computed(() => {
  return {
    'btn-enable': canGoPrev.value && !loading.value,
    'btn-disabled': !canGoPrev.value || loading.value,
    'opacity-50': loading.value
  };
});

const nextButtonClass = computed(() => {
  return {
    'btn-enable': canGoNext.value && !loading.value,
    'btn-disabled': !canGoNext.value || loading.value,
    'opacity-50': loading.value
  };
});

const calendarButtonClass = computed(() => {
  return {
    'opacity-50 cursor-not-allowed': !canOpenCalendar.value,
    'cursor-pointer': canOpenCalendar.value
  };
});

// 图表配置
const options1 = computed(() => {
  return {
    title: {
      show: false,
      text: statistics.value.total.toString(),
      subtext: '{a|刷题总量}',
      left: 'center',
      top: '34%',
      textStyle: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#222'
      },
      subtextStyle: {
        fontSize: 12,
        color: '#666',
        lineHeight: 12,
        rich: {
          a: {
            color: '#B3B3B3',
            padding: [0, 0, 10, 0]
          },
        }
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['60%', '80%'],
        startAngle: 90,
        silent: true,
        label: { show: false },
        data: [
          {
            value: 45,
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 1,
                y2: 1,
                colorStops: [
                  { offset: 0, color: '#FEC048' },
                  { offset: 1, color: '#F9942F' }
                ]
              }
            }
          },
          {
            value: 55,
            itemStyle: { color: '#FFF5DE' }
          }
        ]
      }
    ]
  };
});

const options2 = computed(() => {
  const accuracy = statistics.value.rate;
  return {
    title: {
      show: false,
      text: `${accuracy}%`,
      subtext: '{a|正确率}',
      left: 'center',
      top: '34%',
      textStyle: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#222'
      },
      subtextStyle: {
        fontSize: 12,
        color: '#666',
        lineHeight: 12,
        rich: {
          a: {
            color: '#B3B3B3',
            padding: [0, 0, 10, 0]
          },
        }
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['60%', '80%'],
        startAngle: 90,
        silent: true,
        label: { show: false },
        data: [
          {
            value: accuracy,
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 1,
                y2: 1,
                colorStops: [
                  { offset: 0, color: '#70C8FD' },
                  { offset: 1, color: '#31A0FC' }
                ]
              }
            }
          },
          {
            value: 100 - accuracy,
            itemStyle: { color: '#EBF9FF' }
          }
        ]
      }
    ]
  };
});

// 表格配置
const tableColumns = ref<TableColumnConfig[]>([
  {
    prop: 'date',
    label: '日期',
    flex: 1,
    slot: 'date'
  },
  {
    prop: 'questionNum',
    label: '题量',
    flex: 1,
    slot: 'questionNum'
  },
  {
    prop: 'correctNum',
    label: '正确率',
    flex: 1,
    slot: 'correctNum'
  }
]);

// 表格数据（从 selected 数据转换）
const tableDate = computed(() => {
  return statistics.value.list;
});

// 练习天数统计
const practiceDays = computed(() => {
  return statistics.value.studyDays;
});

// 日历标题
const calendarTitle = computed(() => {
  const year = currentMonthRange.value?.startDate?.split('-')[0] || new Date().getFullYear();
  const month = currentMonthRange.value?.startDate?.split('-')[1] || new Date().getMonth() + 1;
  return `${year}年-${month}月`;
});

// 日历副标题
const calendarSubTitle = computed(() => {
  const month = currentMonthRange.value?.startDate?.split('-')[1] || new Date().getMonth() + 1;
  return `本月(${month}月)已累计刷题`;
});

// 导航方法
const handlePrev = async () => {
  if (loading.value) return; // 加载中时禁止操作
  uni.$ie.showLoading();
  await goToPrevMonth();
  uni.$ie.hideLoading();
};

const handleNext = async () => {
  if (loading.value) return; // 加载中时禁止操作
  uni.$ie.showLoading();
  await goToNextMonth();
  uni.$ie.hideLoading();
};

// 表单处理 - 与日历同步
const handleYearChange = async () => {
  // 年份切换时清空月份和周
  form.value.month = '';

  // 年份切换时请求年度数据，但不显示记录表
  if (form.value.year) {
    const year = parseInt(form.value.year);
    // 请求年度数据来更新统计信息
    await goToYear(year);
  }
};

const handleMonthChange = async () => {
  if (form.value.year && form.value.month) {
    // 切换到月份模式并跳转到指定年月
    await goToYearMonth(parseInt(form.value.year), parseInt(form.value.month));
  }
};
// 监听日历状态变化，同步到表单
watch([currentYear, currentMonth, displayMode], ([year, month, mode]) => {
  form.value.year = year.toString();
  // 只有在非年份模式下才同步月份，年份模式下保持用户选择
  if (mode !== 'year') {
    form.value.month = month.toString();
  }
}, { immediate: true });

// 初始化默认选中当前时间
const initializeDefaultSelection = () => {
  const formData = initializeFormData();
  form.value.year = formData.year;
  form.value.month = formData.month;
};

// 监听日历组件内部事件，确保数据同步
const handleCalendarWeekChange = (event: any) => {

};

const handleCalendarMonthSwitch = (event: any) => {
  // 更新外部状态以保持同步
  if (event.year && event.month) {
    // 通过 goToYearMonth 方法来更新状态
    goToYearMonth(event.year, event.month);
  }
};

const calendarRef = ref();
const calendarPopupRef = ref();

const handleOpenCalendar = () => {
  if (canOpenCalendar.value && calendarPopupRef.value) {
    calendarPopupRef.value.open();
  }
};

// 初始化
onMounted(async () => {
  // 先初始化默认选中
  initializeDefaultSelection();
  // 显示全屏loading
  uni.$ie.showLoading();
  try {
    // 初始化日历
    await initCalendar(props.recordId);
  } finally {
    // 隐藏loading
    uni.$ie.hideLoading();
  }
});
</script>
<style lang="scss" scoped>
.picker-wrap {
  @apply flex items-center px-12 w-fit border border-solid border-border rounded-4 h-56 min-w-140;
}

.btn-wrap {
  @apply flex items-center gap-x-10 bg-primary text-white text-26 px-10 h-56 rounded-4;
}

.btn-enable {
  @apply bg-[#EEF4FA] cursor-pointer;
}

.btn-disabled {
  @apply bg-[#F5F5F5] cursor-not-allowed;
}

.calendar-item {
  @apply rounded-5 text-center w-64 h-56 mx-auto py-8;

  .date {
    color: #222;
    font-size: 30rpx;
    line-height: 30rpx;
  }

  .info {
    font-size: 20rpx;
    line-height: 20rpx;
    margin-top: 4rpx;
  }
}

.uni-calendar-item--disable {
  opacity: 0;
}

.calendar-item--week-mode-disabled {
  .date {
    color: #cccccc;
  }
}

.calendar-item--valid {
  --valid-color: #22C55E;
  background-color: #F0FDF4;
  border: 1px solid var(--valid-color);

  .info {
    color: var(--valid-color);
  }
}

.calendar-item--invalid {
  --invalid-color: #FF5B5C;
  background-color: #FEEDE9;
  border: 1px solid var(--invalid-color);

  .info {
    color: var(--invalid-color);
  }
}

.calendar-loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}
</style>