<template>
  <view class="page">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-content">
        <view class="nav-left" @click="goBack">
          <text class="back-icon">←</text>
        </view>
        <text class="page-title">AI 内容生成</text>
        <view class="nav-right">
          <text class="nav-btn" @click="showHelp = true">?</text>
        </view>
      </view>
    </view>

    <!-- 主内容区 -->
    <view class="main-content">
      <!-- 步骤1：基础设置 -->
      <view v-if="currentStep === 0" class="card">
        <view class="card-header">
          <text class="card-title">📋 内容设置</text>
        </view>

        <!-- 内容类型 -->
        <view class="form-item">
          <text class="form-label">内容类型</text>
          <scroll-view scroll-x class="type-scroll">
            <view class="type-list">
              <view
                v-for="type in allTypes"
                :key="type"
                class="type-item"
                :class="{ active: selectedType === type }"
                @click="selectedType = type"
              >
                {{ type }}
              </view>
            </view>
          </scroll-view>
        </view>

        <!-- 行业选择 -->
        <view class="form-item">
          <text class="form-label">所属行业</text>
          <scroll-view scroll-x class="industry-scroll">
            <view class="industry-list">
              <view
                v-for="ind in industries"
                :key="ind"
                class="industry-item"
                :class="{ active: selectedIndustry === ind }"
                @click="selectedIndustry = ind"
              >
                {{ ind }}
              </view>
            </view>
          </scroll-view>
        </view>

        <!-- 主题/需求输入 -->
        <view class="form-item">
          <text class="form-label">创作需求</text>
          <textarea
            v-model="prompt"
            class="prompt-input"
            :placeholder="getPromptPlaceholder()"
            :maxlength="500"
          />
          <view class="input-hint">
            <text>{{ prompt.length }}/500 字</text>
          </view>
        </view>

        <!-- 目标字数 -->
        <view class="form-item">
          <text class="form-label">目标字数：{{ targetLength }} 字</text>
          <slider
            :value="targetLength"
            :min="100"
            :max="10000"
            :step="100"
            @change="(e: any) => targetLength = e.detail.value"
            activeColor="#4F46E5"
            backgroundColor="#e5e7eb"
            block-size="20"
          />
          <view class="slider-range">
            <text>100字</text>
            <text>10000字</text>
          </view>
        </view>

        <button
          class="generate-btn"
          :disabled="!canGenerate || generating"
          @click="startGenerate"
        >
          <text v-if="generating">{{ generatingProgress || '生成中...' }}</text>
          <text v-else>🚀 开始生成</text>
        </button>
      </view>

      <!-- 步骤2：生成结果 -->
      <view v-if="currentStep === 1" class="card">
        <view class="card-header">
          <text class="card-title">📝 生成结果</text>
          <view class="header-actions">
            <text class="header-action" @click="copyContent">📋 复制</text>
            <text class="header-action" @click="saveDraft">💾 保存</text>
          </view>
        </view>

        <!-- 进度显示 -->
        <view v-if="generating" class="progress-section">
          <view class="progress-header">
            <text>{{ generatingProgress }}</text>
            <text v-if="currentCharCount > 0">{{ currentCharCount }} 字</text>
          </view>
          <progress
            :percent="Math.round(progressPercent)"
            activeColor="#4F46E5"
            backgroundColor="#e5e7eb"
            stroke-width="8"
          />
        </view>

        <!-- 生成的内容 -->
        <view v-if="generatedContent" class="result-content">
          <text class="content-text">{{ generatedContent }}</text>
        </view>

        <view class="result-footer">
          <text class="word-count">{{ generatedContent?.length || 0 }} 字</text>
        </view>

        <view class="btn-row">
          <button class="back-btn" @click="reset">← 重新生成</button>
          <button class="primary-btn" @click="useContent">📝 使用此内容</button>
        </view>
      </view>

      <!-- 步骤3：质量检测 -->
      <view v-if="currentStep === 2" class="card">
        <view class="card-header">
          <text class="card-title">✅ 质量检测</text>
        </view>

        <!-- 敏感词检测 -->
        <view class="quality-item">
          <view class="quality-header">
            <text class="quality-title">🔍 敏感词检测</text>
            <text class="quality-status" :class="sensitiveResult.isClean ? 'pass' : 'fail'">
              {{ sensitiveResult.isClean ? '通过' : '有问题' }}
            </text>
          </view>
          <view v-if="sensitiveResult.foundWords.length > 0" class="sensitive-words">
            <text v-for="word in sensitiveResult.foundWords" :key="word" class="sensitive-tag">
              {{ word }}
            </text>
          </view>
        </view>

        <!-- 合规检查 -->
        <view class="quality-item">
          <view class="quality-header">
            <text class="quality-title">📋 合规检查</text>
            <text class="quality-status" :class="complianceResult.passed ? 'pass' : 'fail'">
              {{ complianceResult.passed ? '通过' : '有问题' }}
            </text>
          </view>
          <view v-if="complianceResult.warnings.length > 0" class="compliance-warnings">
            <text v-for="warn in complianceResult.warnings" :key="warn" class="warning-tag">
              {{ warn }}
            </text>
          </view>
        </view>

        <!-- 质量评分 -->
        <view v-if="qualityScore" class="quality-item">
          <view class="quality-header">
            <text class="quality-title">📊 内容评分</text>
            <text class="quality-score">{{ qualityScore.overall }}分</text>
          </view>
          <view class="score-dimensions">
            <view
              v-for="(value, key) in qualityScore.dimensions"
              :key="key"
              class="dimension-item"
            >
              <text class="dimension-name">{{ getDimensionName(key) }}</text>
              <view class="dimension-bar">
                <view class="dimension-fill" :style="{ width: value + '%' }"></view>
              </view>
              <text class="dimension-value">{{ Math.round(value) }}</text>
            </view>
          </view>
        </view>

        <view class="btn-row">
          <button class="back-btn" @click="currentStep = 1">← 返回结果</button>
          <button class="primary-btn" @click="useContent">📝 使用此内容</button>
        </view>
      </view>
    </view>

    <!-- 帮助弹窗 -->
    <view v-if="showHelp" class="modal-overlay" @click="showHelp = false">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">使用帮助</text>
          <text class="modal-close" @click="showHelp = false">✕</text>
        </view>
        <view class="modal-body">
          <text class="help-title">支持的类型：</text>
          <text class="help-text">• 创作类：小说、故事、剧本、诗歌、散文</text>
          <text class="help-text">• 营销类：产品介绍、广告文案、朋友圈、小红书、抖音脚本</text>
          <text class="help-text">• 教育类：课件、培训、教程、知识科普</text>
          <text class="help-text">• 商务类：销售话术、客服话术、商务邮件</text>
          <text class="help-text">• 媒体类：新闻播报、天气预报、体育解说</text>
          <text class="help-title">使用流程：</text>
          <text class="help-text">1. 选择内容类型</text>
          <text class="help-text">2. 选择所属行业</text>
          <text class="help-text">3. 描述您的需求</text>
          <text class="help-text">4. 一键生成</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { post } from '../../utils/request';

const allTypes = [
  '小说', '故事', '剧本', '诗歌', '散文',
  '产品介绍', '广告文案', '朋友圈', '小红书', '抖音脚本',
  '课件', '培训', '教程', '知识科普',
  '销售话术', '客服话术', '商务邮件',
  '新闻播报', '天气预报', '体育解说',
];

const industries = ['通用', '医疗健康', '教育培训', '金融服务', '电子商务', '餐饮美食'];

const currentStep = ref(0);
const selectedType = ref('小说');
const selectedIndustry = ref('通用');
const prompt = ref('');
const targetLength = ref(2000);

// 生成状态
const generating = ref(false);
const generatingProgress = ref('');
const currentCharCount = ref(0);
const generatedContent = ref('');

// 质量检测
const sensitiveResult = ref<{ isClean: boolean; foundWords: string[] }>({ isClean: true, foundWords: [] });
const complianceResult = ref<{ passed: boolean; warnings: string[] }>({ passed: true, warnings: [] });
const qualityScore = ref<any>(null);

// UI状态
const showHelp = ref(false);

const canGenerate = computed(() => {
  return prompt.value.trim().length > 0 && !generating.value;
});

const progressPercent = computed(() => {
  if (!generating.value) return 100;
  return 50; // 生成中固定50%
});

const dimensionNames: Record<string, string> = {
  fluency: '流畅度',
  naturalness: '自然度',
  emotion_consistency: '情感一致',
  topic_adherence: '主题相关',
  structural_integrity: '结构完整',
};

function getDimensionName(key: string) {
  return dimensionNames[key] || key;
}

function getPromptPlaceholder() {
  const placeholders: Record<string, string> = {
    '小说': '描述你想要的故事类型，如：都市爱情、玄幻穿越、悬疑推理...',
    '故事': '描述故事的主题和背景...',
    '产品介绍': '介绍产品的名称、特点、优势...',
    '广告文案': '描述产品卖点、活动内容...',
    '朋友圈': '描述想表达的心情或内容...',
    '培训': '描述培训主题和目标受众...',
    '销售话术': '描述产品类型和目标客户...',
    '新闻播报': '描述新闻事件内容...',
  };
  return placeholders[selectedType.value] || '描述您的创作需求...';
}

function goBack() {
  uni.navigateBack();
}

async function startGenerate() {
  if (!canGenerate.value) return;

  generating.value = true;
  generatingProgress.value = '正在生成内容...';
  currentCharCount.value = 0;
  generatedContent.value = '';

  try {
    const result = await post<any>('/ai-content/generate', {
      type: selectedType.value,
      industry: selectedIndustry.value,
      prompt: prompt.value,
      targetLength: targetLength.value,
    });

    generatedContent.value = result.content || result.text || '生成内容为空';
    currentCharCount.value = generatedContent.value.length;
    generatingProgress.value = '生成完成';

    // 自动进行质量检测
    await checkQuality();
    currentStep.value = 1;
  } catch (e: any) {
    uni.showToast({ title: '生成失败: ' + (e.message || '未知错误'), icon: 'none' });
  } finally {
    generating.value = false;
  }
}

async function checkQuality() {
  if (!generatedContent.value) return;

  // 敏感词检测
  try {
    const sensitive = await post<any>('/ai-content/sensitive/check', { text: generatedContent.value });
    sensitiveResult.value = sensitive;
  } catch (e) {}

  // 合规检查
  try {
    const compliance = await post<any>('/ai-content/compliance/check', {
      text: generatedContent.value,
      industry: selectedIndustry.value,
    });
    complianceResult.value = compliance;
  } catch (e) {}

  // 质量评分
  try {
    qualityScore.value = await post<any>('/ai-content/quality/score', { text: generatedContent.value });
  } catch (e) {}
}

function copyContent() {
  uni.setClipboardData({
    data: generatedContent.value,
    success: () => {
      uni.showToast({ title: '已复制', icon: 'success' });
    },
  });
}

function saveDraft() {
  uni.showToast({ title: '已保存草稿', icon: 'success' });
}

function useContent() {
  uni.setStorageSync('ai_generated_text', generatedContent.value);
  uni.navigateBack();
}

function reset() {
  currentStep.value = 0;
  generatedContent.value = '';
  generatingProgress.value = '';
  currentCharCount.value = 0;
}

function showQualityScore() {
  currentStep.value = 2;
}
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f5f5f5;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 88rpx;
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  z-index: 100;
  padding-top: 44rpx;
}

.nav-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  height: 88rpx;
}

.nav-left, .nav-right {
  width: 80rpx;
}

.back-icon {
  font-size: 40rpx;
  color: #fff;
}

.nav-btn {
  font-size: 32rpx;
  color: #fff;
}

.page-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #ffffff;
}

.main-content {
  padding: 140rpx 32rpx 32rpx;
}

.card {
  background: #fff;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
}

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

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1f2937;
}

.header-actions {
  display: flex;
  gap: 24rpx;
}

.header-action {
  font-size: 26rpx;
  color: #4F46E5;
}

/* 表单 */
.form-item {
  margin-bottom: 32rpx;
}

.form-label {
  font-size: 28rpx;
  color: #6b7280;
  margin-bottom: 16rpx;
  display: block;
}

/* 类型选择 */
.type-scroll, .industry-scroll {
  white-space: nowrap;
}

.type-list, .industry-list {
  display: inline-flex;
  gap: 16rpx;
  padding: 8rpx 0;
}

.type-item, .industry-item {
  font-size: 26rpx;
  padding: 12rpx 24rpx;
  background: #f3f4f6;
  border-radius: 32rpx;
  color: #6b7280;
  white-space: nowrap;
  border: 2rpx solid transparent;
}

.type-item.active, .industry-item.active {
  background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%);
  color: #fff;
  border-color: #4f46e5;
}

/* 输入框 */
.prompt-input {
  width: 100%;
  min-height: 200rpx;
  background: #f9fafb;
  border-radius: 16rpx;
  padding: 24rpx;
  font-size: 28rpx;
  line-height: 1.6;
}

.input-hint {
  text-align: right;
  margin-top: 8rpx;
}

.input-hint text {
  font-size: 22rpx;
  color: #9ca3af;
}

/* 滑块 */
.slider-range {
  display: flex;
  justify-content: space-between;
  margin-top: 8rpx;
}

.slider-range text {
  font-size: 22rpx;
  color: #9ca3af;
}

/* 进度 */
.progress-section {
  background: #f9fafb;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 24rpx;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12rpx;
}

.progress-header text {
  font-size: 26rpx;
  color: #6b7280;
}

/* 结果 */
.result-content {
  background: #f9fafb;
  border-radius: 16rpx;
  padding: 24rpx;
  max-height: 600rpx;
  overflow-y: auto;
}

.content-text {
  font-size: 28rpx;
  color: #374151;
  line-height: 1.8;
  white-space: pre-wrap;
}

.result-footer {
  margin-top: 16rpx;
  text-align: right;
}

.word-count {
  font-size: 24rpx;
  color: #9ca3af;
}

/* 质量检测 */
.quality-item {
  background: #f9fafb;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 16rpx;
}

.quality-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.quality-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #1f2937;
}

.quality-status {
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}

.quality-status.pass {
  background: #d1fae5;
  color: #059669;
}

.quality-status.fail {
  background: #fee2e2;
  color: #dc2626;
}

.quality-score {
  font-size: 32rpx;
  font-weight: 700;
  color: #4F46E5;
}

.sensitive-words, .compliance-warnings {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
}

.sensitive-tag, .warning-tag {
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  background: #fee2e2;
  color: #dc2626;
  border-radius: 6rpx;
}

.score-dimensions {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.dimension-item {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.dimension-name {
  font-size: 24rpx;
  color: #6b7280;
  width: 120rpx;
}

.dimension-bar {
  flex: 1;
  height: 12rpx;
  background: #e5e7eb;
  border-radius: 6rpx;
  overflow: hidden;
}

.dimension-fill {
  height: 100%;
  background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%);
  border-radius: 6rpx;
}

.dimension-value {
  font-size: 24rpx;
  color: #4F46E5;
  width: 50rpx;
  text-align: right;
}

/* 按钮 */
.btn-row {
  display: flex;
  gap: 16rpx;
  margin-top: 24rpx;
}

.generate-btn, .primary-btn {
  flex: 1;
  height: 88rpx;
  background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
  border-radius: 16rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  font-weight: 600;
  color: #fff;
}

.generate-btn[disabled] {
  background: #e5e7eb;
  color: #9ca3af;
}

.back-btn {
  flex: 1;
  height: 88rpx;
  background: #f3f4f6;
  border-radius: 16rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #6b7280;
}

.generate-btn::after, .back-btn::after, .primary-btn::after {
  border: none;
}

/* 弹窗 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  width: 600rpx;
  max-height: 80vh;
  background: #fff;
  border-radius: 24rpx;
  padding: 32rpx;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.modal-title {
  font-size: 34rpx;
  font-weight: 600;
}

.modal-close {
  font-size: 40rpx;
  color: #9ca3af;
}

.modal-body {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.help-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #1f2937;
  margin-top: 16rpx;
  margin-bottom: 8rpx;
}

.help-text {
  font-size: 26rpx;
  color: #6b7280;
  line-height: 1.6;
}
</style>
