<template>
  <view class="page fade-in">
    <!-- 顶部 -->
    <view class="hero">
      <text class="hero-title">{{ currentTab === 'list' ? '简历管理' : 'AI简历优化' }}</text>
      <text class="hero-sub">{{ currentTab === 'list' ? '管理你的简历' : '输入简历内容，AI 诊断并优化' }}</text>
    </view>

    <!-- 选项卡 -->
    <view class="tabs">
      <view class="tab" :class="{ active: currentTab === 'list' }" @click="switchTab('list')">📁 我的简历</view>
      <view class="tab" :class="{ active: currentTab === 'analyze' }" @click="switchTab('analyze')">🤖 AI分析</view>
    </view>

    <!-- Tab: 我的简历 -->
    <view class="body" v-if="currentTab === 'list'">
      <view class="add-card" @click="showForm = true" v-if="!showForm && isLoggedIn">
        <text class="add-plus">+</text>
        <text class="add-text">新建简历</text>
      </view>

      <view class="form-card" v-if="showForm">
        <view class="form-title">新建简历</view>
        <input class="field-input" v-model="formTitle" placeholder="简历标题（如：前端工程师）" />
        <input class="field-input" v-model="formPosition" placeholder="目标岗位" />
        <textarea class="field-textarea" v-model="formContent" placeholder="粘贴简历内容..." :maxlength="5000" />
        <view class="form-actions">
          <button class="act-cancel" @click="cancelForm">取消</button>
          <button class="act-save" @click="saveResume" :disabled="saving">{{ saving ? '保存中...' : '保存' }}</button>
        </view>
      </view>

      <!-- 未登录 -->
      <view class="login-prompt" v-if="!isLoggedIn && !showForm">
        <text class="prompt-icon">🔒</text>
        <text class="prompt-text">登录后可管理简历</text>
        <button class="prompt-btn btn-gradient" @click="goLogin">去登录</button>
      </view>

      <!-- 列表 -->
      <view class="list" v-if="isLoggedIn && resumes.length > 0">
        <view class="item card" v-for="r in resumes" :key="r.id" @click="selectResume(r)">
          <view class="item-title">{{ r.title }}</view>
          <view class="item-meta">
            <text class="item-tag">{{ r.targetPosition || '通用' }}</text>
            <text class="item-date">{{ r.createdAt }}</text>
          </view>
          <text class="item-del" @click.stop="deleteResume(r.id)">删除</text>
        </view>
      </view>

      <view class="empty" v-if="isLoggedIn && resumes.length === 0 && !showForm">
        <text class="empty-icon">📄</text>
        <text class="empty-title">暂无简历</text>
        <text class="empty-desc">新建一份简历，AI 帮你分析和优化</text>
      </view>
    </view>

    <!-- Tab: AI 分析 -->
    <view class="body" v-if="currentTab === 'analyze'">
      <!-- 选择简历 -->
      <view class="section-label">选择要分析的简历</view>
      <view class="select-list" v-if="resumes.length > 0">
        <view class="select-item" v-for="r in resumes" :key="r.id"
          :class="{ selected: selectedResumeId === r.id }" @click="selectedResumeId = r.id; selectedText = ''">
          <text class="select-name">{{ r.title }}</text>
          <text class="select-check" v-if="selectedResumeId === r.id">✓</text>
        </view>
      </view>
      <view class="select-item" :class="{ selected: selectedResumeId === '' }" @click="selectedResumeId = ''; selectedText = resumeText">
        <text class="select-name">{{ resumeText ? '已输入自定义内容' : '直接粘贴内容' }}</text>
        <text class="select-check" v-if="selectedResumeId === ''">✓</text>
      </view>

      <!-- 输入内容 -->
      <!-- 上传文件 -->
      <view class="upload-area" @click="chooseFile">
        <text class="upload-icon">{{ fileName ? '📎' : '📤' }}</text>
        <text class="upload-text">{{ fileName || '点击上传 PDF / Word 文件' }}</text>
        <text class="upload-status" v-if="uploading">解析中...</text>
      </view>
      <input type="file" ref="fileInputRef" accept=".pdf,.doc,.docx,.txt" style="display:none" @change="onFileSelected" />

      <view class="section-label" style="margin-top: 20rpx;">简历内容</view>
      <textarea class="analyze-textarea" v-model="resumeText" placeholder="粘贴简历文本内容..." :maxlength="10000" />

      <view class="section-label" style="margin-top: 20rpx;">目标岗位（可选）</view>
      <input class="field-input" v-model="targetPosition" placeholder="如：前端工程师" />

      <!-- 操作 -->
      <view class="analyze-actions">
        <button class="act-optimize" @click="submitOptimize" :disabled="analyzing">
          {{ analyzing ? 'AI 优化中...' : '✨ 智能优化' }}
        </button>
        <button class="act-diagnose" @click="submitDiagnose" :disabled="analyzing">
          {{ analyzing ? '诊断中...' : '📋 简历诊断' }}
        </button>
      </view>

      <!-- 结果 -->
      <view v-if="result" class="result-area">
        <view class="result-header">
          <text class="result-type">{{ resultType === 'diagnosis' ? '诊断结果' : '优化结果' }}</text>
        </view>

        <view v-if="resultType === 'diagnosis'" class="result-section">
          <view class="score-wrap">
            <text class="score-num">{{ result.score }}</text>
            <text class="score-total">/100</text>
          </view>
          <view class="issues-list" v-if="result.issues">
            <view class="issue" v-for="(issue, i) in result.issues" :key="i">
              <text class="issue-level" :class="issue.level">{{ issue.level === 'high' ? '严重' : issue.level === 'medium' ? '中等' : '轻微' }}</text>
              <view class="issue-body">
                <text class="issue-title">{{ issue.title }}</text>
                <text class="issue-desc">{{ issue.desc }}</text>
              </view>
            </view>
          </view>
          <view class="suggestions" v-if="result.suggestions">
            <text class="sugg-title">改进建议：</text>
            <text class="sugg-item" v-for="(s, i) in result.suggestions" :key="i">{{ i+1 }}. {{ s }}</text>
          </view>
        </view>

        <view v-if="resultType === 'optimize'" class="result-section">
          <view class="changes" v-if="result.changes">
            <text class="sugg-title">改动项：</text>
            <text class="change-item" v-for="(c, i) in result.changes" :key="i">{{ i+1 }}. {{ c }}</text>
          </view>
          <view class="optimized-content" v-if="result.optimized">
            <text class="sugg-title">优化后内容：</text>
            <text class="opt-text">{{ result.optimized }}</text>
          </view>
        </view>
        <!-- Download buttons -->
        <view class="result-actions" v-if="result">
          <button class="act-download" @click="downloadResult('txt')">📥 下载为 TXT</button>
          <button class="act-download outline" @click="downloadResult('html')">📄 预览 HTML</button>
        </view>
        <view class="disclaimer" v-if="result">
          <text>⚠️ 以上内容由 AI 生成，仅供参考，请在提交前自行核实重要信息。</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
// #ifdef MP-WEIXIN
import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
// #endif
// #ifndef MP-WEIXIN
import { onLoad } from '@dcloudio/uni-app'
// #endif
import { api } from '../../config'

// #ifdef MP-WEIXIN
onShareAppMessage(() => ({ title: '职引 - 简历诊断与优化 | AI智能优化', path: '/pages/resume/resume' }))
onShareTimeline(() => ({ title: '职引 - 简历诊断与优化 | AI智能优化' }))
// #endif

const currentTab = ref('list')
const showForm = ref(false)
const formTitle = ref('')
const formPosition = ref('')
const formContent = ref('')
const resumes = ref([])
const saving = ref(false)
const isLoggedIn = ref(false)

// Analyze tab
const resumeText = ref('')
const targetPosition = ref('')
const selectedResumeId = ref('')
const analyzing = ref(false)
const result = ref(null)
const resultType = ref('')
const fileName = ref('')
const uploading = ref(false)

const token = () => uni.getStorageSync('token') || ''

onLoad((options) => {
  if (options?.tab === 'analyze') currentTab.value = 'analyze'
})

onMounted(async () => {
  isLoggedIn.value = !!token()
  if (isLoggedIn.value) await loadList()
})

const switchTab = (tab) => {
  currentTab.value = tab
  if (tab === 'list' && token()) loadList()
}

const loadList = async () => {
  try {
    const res = await uni.request({ url: api('/resume/list'), method: 'GET', header: { 'Authorization': `Bearer ${token()}` } })
    if (res.statusCode === 200) resumes.value = (res.data || []).map(r => ({
      id: r.id, title: r.title, targetPosition: r.targetPosition,
      createdAt: r.createdAt ? new Date(r.createdAt).toLocaleDateString('zh-CN') : '--', content: r.content,
    }))
  } catch(e) { console.error(e) }
}

const selectResume = (r) => {
  currentTab.value = 'analyze'
  selectedResumeId.value = r.id
  resumeText.value = r.content || ''
  targetPosition.value = r.targetPosition || ''
}

const submitDiagnose = async () => {
  const content = getContent()
  if (!content) { uni.showToast({ title: '请先输入简历内容', icon: 'none' }); return }
  const token = uni.getStorageSync('token')
  if (!token) { uni.showToast({ title: '请先登录', icon: 'none' }); return }
  analyzing.value = true; result.value = null
  try {
    const res = await uni.request({ url: api('/analyze/diagnosis'), method: 'POST', header: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, data: { content } })
    if (res.statusCode === 200) { result.value = res.data; resultType.value = 'diagnosis' }
  } catch { uni.showToast({ title: '诊断失败', icon: 'none' }) }
  finally { analyzing.value = false }
}

const submitOptimize = async () => {
  const content = getContent()
  if (!content) { uni.showToast({ title: '请先输入简历内容', icon: 'none' }); return }
  const token = uni.getStorageSync('token')
  if (!token) { uni.showToast({ title: '请先登录', icon: 'none' }); return }
  analyzing.value = true; result.value = null
  try {
    const direction = targetPosition.value || '通用岗位'
    const res = await uni.request({ url: api('/analyze/optimize'), method: 'POST', header: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, data: { content, direction } })
    if (res.statusCode === 200) { result.value = res.data; resultType.value = 'optimize' }
  } catch { uni.showToast({ title: '优化失败', icon: 'none' }) }
  finally { analyzing.value = false }
}

const getContent = () => selectedResumeId.value ? (resumes.value.find(r => r.id === selectedResumeId.value)?.content || '') : resumeText.value

// 文件上传
const chooseFile = () => {
  // #ifdef H5
  const input = document.querySelector('input[type="file"]')
  if (input) input.click()
  // #endif
  // #ifdef MP-WEIXIN
  uni.chooseMessageFile({
    count: 1,
    type: 'file',
    extension: ['pdf', 'doc', 'docx', 'txt'],
    success: (res) => { const f = res.tempFiles[0]; uploadMpFile(f.path, f.name) }
  })
  // #endif
}

const uploadMpFile = async (filePath, name) => {
  fileName.value = name
  uploading.value = true
  try {
    const res = await uni.uploadFile({ url: api('/upload'), filePath, name: 'file', header: { 'Authorization': `Bearer ${token()}` } })
    const data = JSON.parse(res.data)
    if (res.statusCode === 200) {
      resumeText.value = data.text
      selectedResumeId.value = ''
      uni.showToast({ title: `已解析：${data.fileName}`, icon: 'success' })
    } else { throw new Error(data.message) }
  } catch (e) { uni.showToast({ title: (e && e.message) || '解析失败', icon: 'none' }) }
  finally { uploading.value = false }
}

const onFileSelected = async (e) => {
  const file = e.target?.files?.[0]
  if (!file) return
  fileName.value = file.name
  uploading.value = true
  try {
    const formData = new FormData()
    formData.append('file', file)
    const res = await fetch(api('/upload'), { method: 'POST', headers: { 'Authorization': `Bearer ${token()}` }, body: formData })
    const data = await res.json()
    if (res.ok) {
      resumeText.value = data.text
      selectedResumeId.value = ''
      uni.showToast({ title: `已解析：${data.fileName}`, icon: 'success' })
    } else { throw new Error(data.message) }
  } catch (e) { uni.showToast({ title: (e && e.message) || '解析失败', icon: 'none' }) }
  finally { uploading.value = false; if (document.querySelector('input[type="file"]')) (document.querySelector('input[type="file"]')).value = '' }
}

// 下载结果（H5 用 Blob 下载，小程序用文件保存）
const downloadResult = (format) => {
  if (!result.value) return
  const content = format === 'html'
    ? `<!DOCTYPE html><html><meta charset="utf-8"><title>职引 - ${resultType.value === 'diagnosis' ? '诊断报告' : '优化结果'}</title><body>${JSON.stringify(result.value)}</body></html>`
    : `${resultType.value === 'diagnosis' ? '=== 简历诊断报告 ===\n\n' : '=== 简历优化结果 ===\n\n'}${JSON.stringify(result.value, null, 2)}`
  const fileName = `简历${resultType.value === 'diagnosis' ? '诊断报告' : '优化结果'}.${format}`

  // #ifdef H5
  const blob = new Blob([content], { type: format === 'html' ? 'text/html' : 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = fileName
  a.click()
  URL.revokeObjectURL(url)
  // #endif
  // #ifdef MP-WEIXIN
  const fs = uni.getFileSystemManager()
  const tempPath = `${wx.env.USER_DATA_PATH}/${fileName}`
  fs.writeFile({ filePath: tempPath, data: content, encoding: 'utf-8', success: () => {
    uni.openDocument({ filePath: tempPath, success: () => uni.showToast({ title: '预览成功', icon: 'success' }) })
  }})
  // #endif
}

const saveResume = async () => {
  if (!formTitle.value) { uni.showToast({ title: '请输入标题', icon: 'none' }); return }
  saving.value = true
  try {
    await uni.request({ url: api('/resume/create'), method: 'POST', header: { 'Authorization': `Bearer ${token()}`, 'Content-Type': 'application/json' }, data: { title: formTitle.value, content: formContent.value, targetPosition: formPosition.value } })
    uni.showToast({ title: '保存成功', icon: 'success' })
    cancelForm(); loadList()
  } catch { uni.showToast({ title: '保存失败', icon: 'none' }) }
  finally { saving.value = false }
}

const deleteResume = async (id) => {
  uni.showModal({ title: '确认删除', content: '确定删除这份简历吗？', success: async (r) => {
    if (!r.confirm) return
    try { await uni.request({ url: api(`/resume/${id}`), method: 'DELETE', header: { 'Authorization': `Bearer ${token()}` } }); uni.showToast({ title: '删除成功', icon: 'success' }); loadList() }
    catch { uni.showToast({ title: '删除失败', icon: 'none' }) }
  }})
}

const cancelForm = () => { showForm.value = false; formTitle.value = ''; formPosition.value = ''; formContent.value = '' }
const goLogin = () => uni.navigateTo({ url: '/pages/login/login' })
</script>

<style scoped>
.page {  background: var(--color-bg); }
.hero { background: linear-gradient(135deg, var(--color-gradient-start) 0%, var(--color-gradient-mid) 50%, var(--color-gradient-end) 100%); padding: 48rpx 32rpx 72rpx; border-radius: 0 0 48rpx 48rpx; min-height: 90rpx; }
.hero-title { font-size: 40rpx; font-weight: 700; color: #FFFFFF; display: block; }
.hero-sub { font-size: 22rpx; color: rgba(255,255,255,0.7); margin-top: 8rpx; display: block; }

/* Tabs */
.tabs { display: flex; gap: 8rpx; padding: 0 32rpx; margin-top: -40rpx; }
.tab { flex: 1; background: #FFFFFF; padding: 16rpx; text-align: center; border-radius: var(--radius-md); font-size: 24rpx; color: var(--color-text-secondary); box-shadow: var(--shadow-sm); transition: all 0.25s; }
.tab.active { background: var(--color-primary); color: #FFFFFF; font-weight: 600; box-shadow: var(--shadow-purple); }

.body { padding: 20rpx 32rpx 48rpx; }

/* Upload */
.upload-area { display: flex; align-items: center; gap: 12rpx; background: #EEF2FF; border: 2rpx dashed var(--color-primary-light); border-radius: var(--radius-md); padding: 24rpx; margin-bottom: 16rpx; }
.upload-icon { font-size: 32rpx; }
.upload-text { flex: 1; font-size: 24rpx; color: var(--color-primary); }
.upload-status { font-size: 22rpx; color: var(--color-text-tertiary); }

/* Result actions */
.result-actions { display: flex; gap: 16rpx; margin-top: 20rpx; }
.act-download { flex: 1; height: 72rpx; line-height: 72rpx; background: linear-gradient(135deg, var(--color-gradient-start), var(--color-gradient-mid)); color: #FFFFFF; border-radius: var(--radius-sm); font-size: 24rpx; border: none; }
.act-download.outline { background: #FFFFFF; color: var(--color-primary); border: 2rpx solid var(--color-primary); }

/* Login prompt */
.login-prompt { display: flex; flex-direction: column; align-items: center; padding: 100rpx 0; gap: 16rpx; }
.prompt-icon { font-size: 64rpx; opacity: 0.4; }
.prompt-text { font-size: 26rpx; color: var(--color-text-tertiary); }
.prompt-btn { padding: 16rpx 48rpx; border-radius: var(--radius-round); font-size: 26rpx; }

/* Add card */
.add-card { background: #FFFFFF; border: 2rpx dashed #D1D5DB; border-radius: var(--radius-lg); padding: 36rpx; display: flex; flex-direction: column; align-items: center; margin-bottom: 24rpx; }
.add-plus { font-size: 48rpx; color: var(--color-primary); font-weight: 700; }
.add-text { font-size: 26rpx; color: var(--color-text-tertiary); margin-top: 8rpx; }

/* Form */
.form-card { background: #FFFFFF; border-radius: var(--radius-lg); padding: 28rpx; box-shadow: var(--shadow-md); margin-bottom: 24rpx; }
.form-title { font-size: 28rpx; font-weight: 600; color: var(--color-text); margin-bottom: 20rpx; }
.field-input { width: 100%; height: 72rpx; background: #F9FAFB; border: 2rpx solid var(--color-border); border-radius: var(--radius-sm); padding: 0 20rpx; font-size: 24rpx; margin-bottom: 16rpx; }
.field-textarea { width: 100%; height: 240rpx; background: #F9FAFB; border: 2rpx solid var(--color-border); border-radius: var(--radius-sm); padding: 16rpx 20rpx; font-size: 24rpx; line-height: 1.6; }
.form-actions { display: flex; gap: 16rpx; margin-top: 20rpx; }
.act-cancel { flex: 1; height: 72rpx; line-height: 72rpx; background: #F3F4F6; color: var(--color-text-secondary); border-radius: var(--radius-sm); font-size: 24rpx; border: none; }
.act-save { flex: 1; height: 72rpx; line-height: 72rpx; background: linear-gradient(135deg, var(--color-gradient-start), var(--color-gradient-mid)); color: #FFFFFF; border-radius: var(--radius-sm); font-size: 24rpx; border: none; }

/* List */
.item { padding: 24rpx 28rpx; margin-bottom: 12rpx; display: flex; flex-direction: column; }
.item-title { font-size: 26rpx; font-weight: 600; color: var(--color-text); }
.item-meta { display: flex; gap: 16rpx; margin-top: 8rpx; }
.item-tag { font-size: 20rpx; color: var(--color-primary); background: #EEF2FF; padding: 2rpx 12rpx; border-radius: var(--radius-round); }
.item-date { font-size: 20rpx; color: var(--color-text-tertiary); }
.item-del { font-size: 22rpx; color: var(--color-error); margin-top: 8rpx; align-self: flex-end; }

/* Select list */
.section-label { font-size: 24rpx; font-weight: 600; color: var(--color-text); margin-bottom: 12rpx; }
.select-list { display: flex; flex-direction: column; gap: 8rpx; }
.select-item { display: flex; justify-content: space-between; align-items: center; padding: 16rpx 20rpx; background: #FFFFFF; border: 2rpx solid var(--color-border); border-radius: var(--radius-sm); }
.select-item.selected { border-color: var(--color-primary); background: #EEF2FF; }
.select-name { font-size: 24rpx; color: var(--color-text); }
.select-check { font-size: 24rpx; color: var(--color-primary); font-weight: 700; }

/* Analyze textarea */
.analyze-textarea { width: 100%; height: 280rpx; background: #FFFFFF; border: 2rpx solid var(--color-border); border-radius: var(--radius-sm); padding: 16rpx 20rpx; font-size: 24rpx; line-height: 1.6; }

/* Actions */
.analyze-actions { display: flex; gap: 16rpx; margin-top: 24rpx; }
.act-optimize { flex: 1; height: 80rpx; line-height: 80rpx; background: linear-gradient(135deg, var(--color-gradient-start), var(--color-gradient-mid)); color: #FFFFFF; border-radius: var(--radius-sm); font-size: 26rpx; font-weight: 600; border: none; }
.act-diagnose { flex: 1; height: 80rpx; line-height: 80rpx; background: #FFFFFF; color: var(--color-primary); border: 2rpx solid var(--color-primary); border-radius: var(--radius-sm); font-size: 26rpx; font-weight: 500; }
.act-optimize:disabled, .act-diagnose:disabled { opacity: 0.6; }

/* Result */
.result-area { margin-top: 24rpx; }
.result-header { margin-bottom: 16rpx; }
.result-type { font-size: 28rpx; font-weight: 700; color: var(--color-text); }
.result-section { background: #FFFFFF; border-radius: var(--radius-lg); padding: 28rpx; box-shadow: var(--shadow-sm); }
.score-wrap { display: flex; align-items: baseline; justify-content: center; margin-bottom: 24rpx; }
.score-num { font-size: 64rpx; font-weight: 800; color: var(--color-primary); }
.score-total { font-size: 28rpx; color: var(--color-text-tertiary); }
.issues-list { display: flex; flex-direction: column; gap: 16rpx; }
.issue { display: flex; gap: 12rpx; }
.issue-level { font-size: 20rpx; padding: 2rpx 10rpx; border-radius: var(--radius-round); white-space: nowrap; height: fit-content; }
.issue-level.high { background: #FEF2F2; color: var(--color-error); }
.issue-level.medium { background: #FFF7ED; color: var(--color-warning); }
.issue-level.low { background: #F3F4F6; color: var(--color-text-tertiary); }
.issue-body { flex: 1; }
.issue-title { font-size: 24rpx; font-weight: 600; color: var(--color-text); }
.issue-desc { font-size: 22rpx; color: var(--color-text-secondary); margin-top: 4rpx; }
.suggestions { margin-top: 20rpx; }
.sugg-title { font-size: 24rpx; font-weight: 600; color: var(--color-text); margin-bottom: 12rpx; display: block; }
.sugg-item { font-size: 22rpx; color: var(--color-text-secondary); line-height: 1.8; display: block; }
.changes { margin-bottom: 20rpx; }
.change-item { font-size: 22rpx; color: var(--color-text-secondary); line-height: 1.8; display: block; }
.optimized-content { margin-top: 16rpx; padding-top: 16rpx; border-top: 1rpx solid var(--color-border); }
.opt-text { font-size: 24rpx; color: var(--color-text); line-height: 1.8; white-space: pre-wrap; }
.empty { display: flex; flex-direction: column; align-items: center; padding: 80rpx 0; }
.empty-icon { font-size: 64rpx; margin-bottom: 16rpx; opacity: 0.5; }
.empty-title { font-size: 28rpx; font-weight: 600; color: var(--color-text); }
.empty-desc { font-size: 22rpx; color: var(--color-text-tertiary); margin-top: 8rpx; }
.disclaimer { margin-top: 16rpx; padding: 12rpx; background: #FFF8E1; border-radius: var(--radius-sm); }
.disclaimer text { font-size: 20rpx; color: #92400E; line-height: 1.6; }
</style>
