<template>
  <div class="insight-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>组织建议</span>
          <div class="filters">
            <el-select v-model="scope" style="width: 120px; margin-right: 10px" @change="onScopeChange">
              <el-option label="周" value="week" />
              <el-option label="月" value="month" />
            </el-select>

            <el-date-picker
              v-if="scope === 'week'"
              v-model="weekStart"
              type="date"
              placeholder="选择周开始日期（周一）"
              style="width: 220px; margin-right: 10px"
              @change="loadInsight"
            />

            <el-date-picker
              v-else
              v-model="month"
              type="month"
              placeholder="选择月份"
              style="width: 180px; margin-right: 10px"
              @change="loadInsight"
            />

            <el-button type="primary" @click="loadInsight">刷新</el-button>
          </div>
        </div>
      </template>

      <el-skeleton animated :rows="8" v-if="loading" />
      <div v-else class="insight-content">
        <el-empty v-if="!insightText" :description="emptyText" />
        <div v-else class="insight-text">{{ insightText }}</div>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
defineOptions({ name: 'dailyreport-insight' });

import { ref, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useCool } from '/@/cool';
import { ElMessage } from 'element-plus';

const { service } = useCool();
const route = useRoute();

const scope = ref<'week' | 'month'>('week');
const weekStart = ref<any>(new Date());
const month = ref<any>(new Date());
const loading = ref(false);
const insightText = ref('');
const emptyText = ref('暂无建议，请调整时间范围后重试');

function onScopeChange() {
  loadInsight();
}

async function loadInsight() {
  try {
    loading.value = true;
    // 清空上次结果，避免残留
    insightText.value = '';
    const params: any = { scope: scope.value };
    if (scope.value === 'week' && weekStart.value) {
      const d = new Date(weekStart.value);
      params.startDate = formatYMDLocal(d);
    }
    if (scope.value === 'month' && month.value) {
      // 使用该月第一天作为 startDate（本地时区格式化，避免 UTC 偏移）
      const d = new Date(month.value);
      const first = new Date(d.getFullYear(), d.getMonth(), 1);
      params.startDate = formatYMDLocal(first);
    }
    const res = await service.dailyreport.report.getInsight(params);
    insightText.value = res.insightText || '';
    if (!insightText.value) {
      emptyText.value = scope.value === 'month'
        ? '未查询到该月份的月报数据，请核实后再尝试'
        : '暂无建议，请调整时间范围后重试';
    }
  } catch (err: any) {
    ElMessage.error(err.message || '加载组织建议失败');
    // 保证页面显示空状态提示
    insightText.value = '';
    emptyText.value = scope.value === 'month'
      ? '未查询到该月份的月报数据，请核实后再尝试'
      : '暂无建议，请调整时间范围后重试';
  } finally {
    loading.value = false;
  }
}

onMounted(() => {
  // 读取路由 query 作为初始值（便于从周报统计跳转携参）
  const q = route.query as any;
  if (q.scope && (q.scope === 'week' || q.scope === 'month')) {
    scope.value = q.scope;
  }
  if (q.start) {
    weekStart.value = new Date(q.start);
    month.value = new Date(q.start);
  }
  loadInsight();
});

// 监听路由参数变化，保持与入口跳转同步刷新
watch(
  () => route.query,
  (q: any) => {
    const qq = q as any;
    if (qq.scope && (qq.scope === 'week' || qq.scope === 'month')) {
      scope.value = qq.scope as any;
    }
    if (qq.start) {
      const d = new Date(qq.start as string);
      weekStart.value = d;
      month.value = d;
    }
    loadInsight();
  }
);

function formatYMDLocal(d: Date) {
  const Y = d.getFullYear();
  const M = String(d.getMonth() + 1).padStart(2, '0');
  const D = String(d.getDate()).padStart(2, '0');
  return `${Y}-${M}-${D}`;
}
</script>

<style lang="scss" scoped>
.insight-container {
  padding: 20px;

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

  .insight-content {
    .insight-text {
      white-space: pre-wrap;
      line-height: 1.6;
    }
  }
}
</style>
