<script setup lang="ts">
/**
 * AI 复盘报告页面
 * - SSE 流式生成复盘报告
 * - 自动存 draft 防丢失
 * - 历史报告查看/编辑/存档/删除
 */
import { ref, nextTick, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import request from '@/api/request'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()

// 时间范围：默认本月
const now = new Date()
const firstDay = new Date(now.getFullYear(), now.getMonth(), 1)
const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0)
const fmt = (d: Date) => d.toISOString().split('T')[0]

const dateRange = ref<[string, string]>([fmt(firstDay), fmt(lastDay)])

const loading = ref(false)
const reportContent = ref('')
const isFinished = ref(false)
const confirmLoading = ref(false)
const isConfirmed = ref(false)
const isEditing = ref(false)
const reportContainerRef = ref<HTMLDivElement>()
const currentReportId = ref('')

// --- 历史报告 ---
const historyReports = ref<any[]>([])
const loadingHistory = ref(false)

const fetchHistory = async () => {
    loadingHistory.value = true
    try {
        const res: any = await request.get('/api/reports/history', { params: { size: 50 } })
        historyReports.value = res?.items || []
    } catch { }
    finally { loadingHistory.value = false }
}

onMounted(() => { fetchHistory() })

// 加载历史报告到显示区
const loadHistoryReport = (report: any) => {
    reportContent.value = report.content_md || ''
    currentReportId.value = report.id
    isFinished.value = true
    isConfirmed.value = report.status === 'confirmed'
    isEditing.value = false
    dateRange.value = [report.period_start, report.period_end]
}

// 进入编辑模式
const enterEdit = () => {
    isEditing.value = true
    isConfirmed.value = false
}

const deleteHistoryReport = (report: any) => {
    ElMessageBox.confirm('确定要删除这份复盘报告吗？', '删除确认', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
    }).then(async () => {
        await request.delete(`/api/reports/${report.id}`)
        ElMessage.success('已删除')
        if (currentReportId.value === report.id) {
            reportContent.value = ''
            currentReportId.value = ''
            isFinished.value = false
        }
        fetchHistory()
    }).catch(() => {})
}

// 生成报告
const handleGenerate = async () => {
    if (!dateRange.value?.[0] || !dateRange.value?.[1]) {
        ElMessage.warning('请选择时间范围')
        return
    }

    loading.value = true
    reportContent.value = ''
    isFinished.value = false
    isConfirmed.value = false
    isEditing.value = false
    currentReportId.value = ''

    try {
        const token = userStore.token || localStorage.getItem('crm_token') || ''
        const res = await fetch('/api/reports/generate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`,
            },
            body: JSON.stringify({
                start_date: dateRange.value[0],
                end_date: dateRange.value[1],
            }),
        })

        if (!res.ok) {
            ElMessage.error(`请求失败: ${res.status}`)
            loading.value = false
            return
        }

        const reader = res.body?.getReader()
        if (!reader) {
            ElMessage.error('无法读取 SSE 流')
            loading.value = false
            return
        }

        const decoder = new TextDecoder()
        let buffer = ''

        while (true) {
            const { done, value } = await reader.read()
            if (done) break

            buffer += decoder.decode(value, { stream: true })

            while (buffer.includes('\n\n')) {
                const [eventBlock, rest] = buffer.split('\n\n', 2)
                buffer = rest || ''

                const dataLine = eventBlock.split('\n').find(l => l.startsWith('data: '))
                if (!dataLine) continue

                try {
                    const event = JSON.parse(dataLine.slice(6))
                    if (event.type === 'text') {
                        reportContent.value += event.content
                        await nextTick()
                        if (reportContainerRef.value) {
                            reportContainerRef.value.scrollTop = reportContainerRef.value.scrollHeight
                        }
                    } else if (event.type === 'done') {
                        isFinished.value = true
                    }
                } catch { }
            }
        }

        isFinished.value = true

        // 自动存为 draft
        if (reportContent.value.trim()) {
            try {
                const draftRes: any = await request.post('/api/reports/confirm', {
                    start_date: dateRange.value[0],
                    end_date: dateRange.value[1],
                    content_md: reportContent.value,
                    report_type: 'monthly',
                })
                if (draftRes?.id) currentReportId.value = draftRes.id
                fetchHistory()
            } catch { }
        }
    } catch (err: any) {
        ElMessage.error(`生成失败: ${err.message || err}`)
    } finally {
        loading.value = false
    }
}

// 确认存档 / 重新存档
const handleConfirm = async () => {
    if (!reportContent.value.trim()) {
        ElMessage.warning('无报告内容可存档')
        return
    }
    confirmLoading.value = true
    try {
        if (currentReportId.value) {
            await request.put(`/api/reports/${currentReportId.value}`, {
                content_md: reportContent.value,
                status: 'confirmed',
            })
        } else {
            const res: any = await request.post('/api/reports/confirm', {
                start_date: dateRange.value[0],
                end_date: dateRange.value[1],
                content_md: reportContent.value,
                report_type: 'monthly',
            })
            if (res?.id) currentReportId.value = res.id
        }
        ElMessage.success('复盘报告已确认存档')
        isConfirmed.value = true
        isEditing.value = false
        fetchHistory()
    } catch { }
    finally { confirmLoading.value = false }
}
</script>

<template>
  <div class="report-page">
    <!-- 顶部操作栏 -->
    <el-card shadow="never" class="action-card">
      <div class="action-bar">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="width: 280px"
        />
        <el-button type="primary" size="large" @click="handleGenerate" :loading="loading">
          {{ loading ? 'AI 正在生成...' : '生成复盘报告' }}
        </el-button>
      </div>
    </el-card>

    <!-- 报告内容区域 -->
    <el-card shadow="never" class="report-card" v-if="reportContent">
      <template #header>
        <div class="card-header">
          <span>AI 智能复盘报告</span>
          <div class="header-actions" v-if="isFinished">
            <template v-if="isEditing">
              <el-button type="success" @click="handleConfirm" :loading="confirmLoading">保存并存档</el-button>
              <el-button @click="isEditing = false">取消编辑</el-button>
            </template>
            <template v-else>
              <el-button v-if="!isConfirmed" type="success" @click="handleConfirm" :loading="confirmLoading">确认存档</el-button>
              <el-button type="warning" plain @click="enterEdit">编辑</el-button>
              <el-tag v-if="isConfirmed" type="success" effect="dark" style="margin-left: 8px">已存档</el-tag>
            </template>
          </div>
        </div>
      </template>

      <!-- 编辑模式：textarea -->
      <el-input
        v-if="isEditing"
        v-model="reportContent"
        type="textarea"
        :autosize="{ minRows: 10, maxRows: 30 }"
        placeholder="编辑复盘报告内容..."
        class="report-editor"
      />

      <!-- 查看模式：格式化显示 -->
      <div v-else ref="reportContainerRef" class="report-body">
        <template v-for="(paragraph, index) in reportContent.split('\n')" :key="index">
          <p v-if="paragraph.trim()" class="report-paragraph">{{ paragraph }}</p>
          <br v-else-if="index > 0" />
        </template>
        <span v-if="loading" class="typing-cursor">▊</span>
      </div>
    </el-card>

    <!-- 空状态 -->
    <el-empty
      v-if="!reportContent && !loading"
      description="选择时间范围，点击按钮生成 AI 复盘报告"
      class="empty-state"
    />

    <!-- 历史报告列表 -->
    <el-card shadow="never" class="history-card" v-if="historyReports.length > 0 || loadingHistory">
      <template #header>
        <div class="card-header">
          <span>📋 历史复盘报告</span>
          <el-tag type="info" size="small">共 {{ historyReports.length }} 份</el-tag>
        </div>
      </template>
      <div v-loading="loadingHistory">
        <div v-for="report in historyReports" :key="report.id" class="history-item"
          :class="{ active: currentReportId === report.id }">
          <div class="history-info" @click="loadHistoryReport(report)">
            <span class="history-period">{{ report.period_start }} ~ {{ report.period_end }}</span>
            <el-tag :type="report.status === 'confirmed' ? 'success' : 'warning'" size="small" effect="plain">
              {{ report.status === 'confirmed' ? '已确认' : '草稿' }}
            </el-tag>
            <span class="history-time">{{ report.created_at?.slice(0, 16)?.replace('T', ' ') }}</span>
          </div>
          <el-button :icon="Delete" type="danger" link size="small" @click.stop="deleteHistoryReport(report)" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.report-page { display: flex; flex-direction: column; gap: 20px; }
.action-card { border: none; border-radius: 8px; }
.action-bar { display: flex; align-items: center; gap: 16px; justify-content: flex-end; }
.report-card { border: none; border-radius: 8px; }
.card-header { display: flex; justify-content: space-between; align-items: center; font-weight: bold; font-size: 16px; }
.header-actions { display: flex; align-items: center; gap: 8px; }
.report-body { line-height: 1.8; color: #333; font-size: 15px; max-height: calc(100vh - 350px); overflow-y: auto; padding-right: 8px; }
.report-paragraph { margin-bottom: 8px; }
.report-editor :deep(.el-textarea__inner) { font-size: 15px; line-height: 1.8; font-family: inherit; }
.typing-cursor { animation: blink 1s step-end infinite; color: #409eff; }
@keyframes blink { 50% { opacity: 0; } }
.empty-state { margin-top: 40px; background: white; padding: 40px; border-radius: 8px; }
.history-card { border: none; border-radius: 8px; }
.history-item { display: flex; justify-content: space-between; align-items: center; padding: 10px 12px; border-bottom: 1px solid #f0f0f0; cursor: pointer; transition: background 0.2s; border-radius: 4px; }
.history-item:hover { background: #f5f7fa; }
.history-item.active { background: #ecf5ff; border-left: 3px solid #409eff; }
.history-item:last-child { border-bottom: none; }
.history-info { display: flex; align-items: center; gap: 12px; flex: 1; }
.history-period { font-weight: 500; color: #303133; font-size: 14px; }
.history-time { color: #909399; font-size: 12px; }
</style>
