<template>
  <div class="home-page">
    <!-- 欢迎区 -->
    <div class="welcome-section">
      <h1>{{ greeting }}，{{ username }}！<span class="gradient-text">智能报告，洞察未来。</span></h1>
      <p>今天是个创作的好日子，开始您的智能报告之旅吧</p>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="stats-row">
      <el-col :span="6">
        <div class="stat-card card" @click="router.push('/generations')">
          <div class="stat-icon blue">📄</div>
          <div class="stat-value">{{ stats.reportCount }}</div>
          <div class="stat-label">生成任务</div>
          <div class="stat-trend">报告生成记录</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card card" @click="router.push('/templates')">
          <div class="stat-icon purple">🎨</div>
          <div class="stat-value">{{ stats.templateCount }}</div>
          <div class="stat-label">可用模板</div>
          <div class="stat-trend">包含公开模板</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card card">
          <div class="stat-icon green">📊</div>
          <div class="stat-value">{{ stats.variableCount }}</div>
          <div class="stat-label">定义变量</div>
          <div class="stat-trend">模板变量总数</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card card">
          <div class="stat-icon orange">📁</div>
          <div class="stat-value">{{ stats.sourceFileCount }}</div>
          <div class="stat-label">来源文件</div>
          <div class="stat-trend">数据来源定义</div>
        </div>
      </el-col>
    </el-row>

    <!-- AI 对话入口 -->
    <div class="ai-card card">
      <div class="ai-welcome">
        <div class="ai-avatar">🤖</div>
        <div class="ai-title">你好！我是灵越AI助手，可以帮你：</div>
        <ul class="ai-list">
          <li>快速生成各类报告</li>
          <li>分析和解读数据</li>
          <li>回答业务相关问题</li>
        </ul>
        <div class="ai-tip">试试输入："帮我生成一份智慧园区建设项目可行性研究报告"</div>
      </div>
      <el-input
        v-model="aiInput"
        placeholder="输入您的需求，或 @知识库 引用资料..."
        size="large"
        class="ai-input"
      >
        <template #suffix>
          <el-button type="primary" :icon="Promotion" circle @click="handleAiSubmit" />
        </template>
      </el-input>
      <div class="thinking-modes">
        <el-radio-group v-model="thinkingMode" size="small">
          <el-radio-button label="deep">🧠 深度思考</el-radio-button>
          <el-radio-button label="quick">⚡ 快速回答</el-radio-button>
          <el-radio-button label="search">🌐 联网搜索</el-radio-button>
          <el-radio-button label="data">📊 数据分析</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 推荐模板 -->
    <div class="section">
      <div class="section-header">
        <h2>📋 推荐模板</h2>
        <el-button type="primary" link @click="router.push('/templates')">
          查看全部 →
        </el-button>
      </div>
      <el-row :gutter="16">
        <el-col :span="8" v-for="tpl in recommendTemplates" :key="tpl.id">
          <div class="tpl-card card" @click="useTemplate(tpl)">
            <div class="tpl-preview">{{ tpl.icon }}</div>
            <div class="tpl-info">
              <div class="tpl-name">{{ tpl.name }}</div>
              <div class="tpl-meta">
                <span>📊 {{ tpl.useCount }}次</span>
                <span>⭐ {{ tpl.rating }}</span>
              </div>
              <div class="tpl-tags">
                <span class="tpl-tag" v-if="tpl.isOfficial">官方</span>
                <span class="tpl-tag hot" v-if="tpl.isHot">热门</span>
              </div>
              <el-button type="primary" size="small" class="tpl-btn">
                使用此模板
              </el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 快捷操作 -->
    <el-row :gutter="16" class="quick-actions">
      <el-col :span="12">
        <div class="quick-action" @click="showUploadDialog = true">
          <div class="quick-action-icon">📤</div>
          <div>
            <div class="quick-action-title">上传新模板</div>
            <div class="quick-action-desc">从 Word 文档创建模板</div>
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="quick-action" @click="showCreateDialog = true">
          <div class="quick-action-icon">🛠️</div>
          <div>
            <div class="quick-action-title">创建新模板</div>
            <div class="quick-action-desc">从空白开始创建</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 创建模板对话框 -->
    <el-dialog v-model="showCreateDialog" title="创建新模板" width="500">
      <el-form :model="newTemplate" label-width="80px">
        <el-form-item label="模板名称" required>
          <el-input v-model="newTemplate.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="newTemplate.description"
            type="textarea"
            :rows="3"
            placeholder="请输入模板描述（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="handleCreateTemplate" :loading="creating">创建</el-button>
      </template>
    </el-dialog>

    <!-- 上传模板对话框 -->
    <el-dialog v-model="showUploadDialog" title="上传新模板" width="600">
      <el-form :model="uploadTemplate" label-width="80px">
        <el-form-item label="模板名称" required>
          <el-input v-model="uploadTemplate.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="uploadTemplate.description"
            type="textarea"
            :rows="2"
            placeholder="请输入模板描述（可选）"
          />
        </el-form-item>
        <el-form-item label="基础文档" required>
          <el-upload
            class="upload-area"
            drag
            action="/api/v1/parse/upload"
            :data="uploadData"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :show-file-list="true"
            :limit="1"
            accept=".doc,.docx,.pdf"
          >
            <div v-if="uploadTemplate.baseDocumentId" class="upload-success">
              <el-icon size="40" color="#52c41a"><CircleCheckFilled /></el-icon>
              <div>文档已上传</div>
            </div>
            <template v-else>
              <el-icon class="el-icon--upload" size="40"><UploadFilled /></el-icon>
              <div class="el-upload__text">
                拖拽文件到此处，或<em>点击上传</em>
              </div>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                支持 Word (.doc, .docx) 和 PDF 格式，上传后可标记变量
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showUploadDialog = false">取消</el-button>
        <el-button type="primary" @click="handleUploadTemplate" :loading="uploading">
          创建模板
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Promotion, UploadFilled, CircleCheckFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useTemplateStore } from '@/stores/template'
import { useTaskCenterStore } from '@/stores/taskCenter'
import { templateApi, parseApi } from '@/api'

const router = useRouter()
const templateStore = useTemplateStore()
const taskCenterStore = useTaskCenterStore()

const aiInput = ref('')
const thinkingMode = ref('deep')
const showUploadDialog = ref(false)
const showCreateDialog = ref(false)

// 用户信息
const username = computed(() => localStorage.getItem('username') || '用户')
const userId = computed(() => localStorage.getItem('userId') || '')

// 上传时附带的数据
const uploadData = computed(() => ({
  userId: userId.value
}))

// 问候语
const greeting = computed(() => {
  const hour = new Date().getHours()
  if (hour < 6) return '夜深了'
  if (hour < 9) return '早上好'
  if (hour < 12) return '上午好'
  if (hour < 14) return '中午好'
  if (hour < 18) return '下午好'
  return '晚上好'
})

const stats = reactive({
  reportCount: 0,
  templateCount: 0,
  variableCount: 0,
  sourceFileCount: 0
})

const newTemplate = reactive({
  name: '',
  description: ''
})
const creating = ref(false)

const uploadTemplate = reactive({
  name: '',
  description: '',
  baseDocumentId: ''
})
const uploading = ref(false)

// 推荐模板数据（从 API 获取）
const recommendTemplates = ref([])

const templateIcons = ['📊', '🏢', '📅', '💼', '📋', '📈', '🎯', '📝']

onMounted(async () => {
  try {
    // 获取统计数据
    const statsData = await templateApi.getStats()
    stats.reportCount = statsData.reportCount || 0
    stats.templateCount = statsData.templateCount || 0
    stats.variableCount = statsData.variableCount || 0
    stats.sourceFileCount = statsData.sourceFileCount || 0
    
    // 获取模板列表
    await templateStore.fetchTemplates()
    // 取前3个模板作为推荐
    recommendTemplates.value = templateStore.templates.slice(0, 3).map((t, i) => ({
      ...t,
      icon: templateIcons[i % templateIcons.length],
      useCount: t.useCount || Math.floor(Math.random() * 200),
      rating: 4.5 + Math.random() * 0.5,
      isOfficial: t.isPublic,
      isHot: i < 2
    }))
  } catch (error) {
    console.error('获取数据失败:', error)
  }
})

function handleAiSubmit() {
  if (!aiInput.value.trim()) {
    ElMessage.warning('请输入您的需求')
    return
  }
  ElMessage.info('AI 功能开发中...')
}

function useTemplate(tpl) {
  router.push(`/editor/${tpl.id}`)
}

async function handleCreateTemplate() {
  if (!newTemplate.name) {
    ElMessage.warning('请输入模板名称')
    return
  }

  creating.value = true
  try {
    const template = await templateStore.createTemplate({
      name: newTemplate.name,
      description: newTemplate.description || ''
    })
    showCreateDialog.value = false
    // 重置表单
    Object.assign(newTemplate, { name: '', description: '' })
    ElMessage.success('模板创建成功')
    router.push(`/editor/${template.id}`)
  } catch (error) {
    ElMessage.error('创建失败: ' + error.message)
  } finally {
    creating.value = false
  }
}

function beforeUpload(file) {
  // 检查用户是否已登录
  if (!userId.value) {
    ElMessage.warning('请先登录后再上传文件')
    router.push('/login')
    return false
  }
  
  // 检查文件类型（使用扩展名判断，更可靠）
  const fileName = file.name.toLowerCase()
  const allowedExtensions = ['.doc', '.docx', '.pdf']
  const hasValidExtension = allowedExtensions.some(ext => fileName.endsWith(ext))
  if (!hasValidExtension) {
    ElMessage.error('仅支持 Word (.doc, .docx) 和 PDF 格式')
    return false
  }
  
  // 检查文件大小（最大 100MB）
  const maxSize = 100 * 1024 * 1024
  if (file.size > maxSize) {
    ElMessage.error('文件大小不能超过 100MB')
    return false
  }
  
  return true
}

function handleUploadSuccess(response) {
  if (response.code === 200) {
    uploadTemplate.baseDocumentId = response.data.documentId
    ElMessage.success('文档上传成功')
  } else {
    ElMessage.error('上传失败: ' + (response.msg || '未知错误'))
  }
}

function handleUploadError(error) {
  ElMessage.error('上传失败: ' + error.message)
}

async function handleUploadTemplate() {
  if (!uploadTemplate.name) {
    ElMessage.warning('请输入模板名称')
    return
  }
  if (!uploadTemplate.baseDocumentId) {
    ElMessage.warning('请上传基础文档')
    return
  }

  uploading.value = true
  try {
    const documentId = uploadTemplate.baseDocumentId
    await templateStore.createTemplate({
      name: uploadTemplate.name,
      description: uploadTemplate.description || '',
      baseDocumentId: documentId
    })
    showUploadDialog.value = false
    // 重置表单
    Object.assign(uploadTemplate, { name: '', description: '', baseDocumentId: '' })
    
    // 触发文档解析
    try {
      await parseApi.startParse(documentId)
      ElMessage.success('模板创建成功，正在解析文档，请在任务中心查看进度')
      // 打开任务中心并追踪此文档的解析任务
      taskCenterStore.notifyTaskStarted({ documentId })
    } catch (parseError) {
      console.error('启动解析失败:', parseError)
      ElMessage.warning('模板创建成功，但解析启动失败，请稍后手动触发')
    }
    
    // 刷新模板列表
    await templateStore.fetchTemplates()
    // 不自动跳转编辑页面，等解析完成后用户自行进入
  } catch (error) {
    ElMessage.error('创建失败: ' + error.message)
  } finally {
    uploading.value = false
  }
}
</script>

<style lang="scss" scoped>
.home-page {
  max-width: 1200px;
  margin: 0 auto;
}

.welcome-section {
  margin-bottom: 20px;

  h1 {
    font-size: 24px;
    font-weight: 600;
    margin-bottom: 4px;
  }

  .gradient-text {
    background: linear-gradient(135deg, #1890ff 0%, #722ed1 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }

  p {
    color: var(--text-2);
  }
}

.stats-row {
  margin-bottom: 20px;
}

.ai-card {
  padding: 20px;
  margin-bottom: 20px;

  .ai-welcome {
    background: linear-gradient(135deg, #f0f7ff, #f5f0ff);
    border-radius: 10px;
    padding: 16px;
    margin-bottom: 16px;
  }

  .ai-avatar {
    width: 44px;
    height: 44px;
    background: linear-gradient(135deg, #1890ff 0%, #722ed1 100%);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
    margin-bottom: 10px;
  }

  .ai-title {
    font-size: 14px;
    font-weight: 600;
    margin-bottom: 8px;
  }

  .ai-list {
    list-style: none;
    margin-bottom: 10px;

    li {
      color: var(--text-2);
      padding: 3px 0;
      font-size: 13px;

      &::before {
        content: '•';
        color: var(--primary);
        margin-right: 8px;
      }
    }
  }

  .ai-tip {
    font-size: 12px;
    color: var(--text-3);
    padding: 8px 12px;
    background: rgba(255, 255, 255, 0.7);
    border-radius: 6px;
    border-left: 3px solid var(--primary);
  }

  .ai-input {
    margin-bottom: 14px;
  }

  .thinking-modes {
    display: flex;
    justify-content: center;
  }
}

.section {
  margin-bottom: 20px;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 14px;

    h2 {
      font-size: 15px;
      font-weight: 600;
    }
  }
}

.tpl-btn {
  width: 100%;
}

.quick-actions {
  .quick-action {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 16px;
    background: #fff;
    border: 2px dashed var(--border);
    border-radius: 10px;
    cursor: pointer;
    transition: all 0.2s;

    &:hover {
      border-color: var(--primary);
      background: var(--primary-light);
    }

    .quick-action-icon {
      width: 40px;
      height: 40px;
      background: var(--bg);
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;
    }

    .quick-action-title {
      font-weight: 600;
      margin-bottom: 2px;
    }

    .quick-action-desc {
      font-size: 12px;
      color: var(--text-3);
    }
  }
}

.upload-area {
  width: 100%;
  
  .upload-success {
    text-align: center;
    padding: 20px;
    color: #52c41a;

    div {
      margin-top: 8px;
      font-size: 14px;
    }
  }
}
</style>
