<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">{{ isEditMode ? '编辑书籍' : '创建书籍' }}</text>
      </view>
      <!-- 模式切换独立行 -->
      <view v-if="!isEditMode" class="mode-bar">
        <text class="mode-switch" @click="switchToInteractive">切换到交互模式</text>
      </view>
    </view>

    <!-- 主内容区 -->
    <view class="main-content">
      <view class="card">

        <!-- ========== 基础信息区 ========== -->
        <view class="section">
          <text class="section-title">基础信息</text>

          <!-- 内容描述 + 字数计数 -->
          <view class="form-item">
            <text class="form-label">内容描述 *</text>
            <view class="textarea-wrapper">
              <textarea
                v-model="newBook.description"
                class="form-textarea"
                :class="{ 'error': attemptedCreate && !newBook.description.trim() }"
                placeholder="描述这本书的内容、主题、写作目的..."
                :maxlength="500"
                @blur="detectScaleFromDesc"
              />
              <text class="char-count">{{ newBook.description.length }}/500</text>
            </view>
          </view>

          <!-- AI自动优化描述按钮 -->
          <view v-if="!isEditMode" class="form-item">
            <button
              class="btn-smart-recommend"
              :disabled="isRecommending || !newBook.description.trim()"
              @click="requestSmartRecommend"
            >
              <text class="recommend-icon">{{ isRecommending ? '⏳' : '✨' }}</text>
              <text class="recommend-text">{{ isRecommending ? '推荐中...' : 'AI自动优化描述' }}</text>
            </button>
          </view>

          <!-- 快速创建按钮（可直接点击创建） -->
          <view v-if="!isEditMode && newBook.description.trim()" class="quick-create-bar">
            <button
              class="btn-quick-create"
              :disabled="!canCreateBook || creating"
              @click="createNewBook"
            >
              {{ creating ? '创建中...' : '🚀 创建书籍' }}
            </button>
          </view>

          <!-- 书籍规模 chip 选择 -->
          <view class="form-item">
            <text class="form-label">书籍规模 *</text>
            <view class="scale-chips">
              <view
                v-for="scale in commonScales"
                :key="scale.value"
                :class="['chip', newBook.bookScale === scale.value ? 'active' : '']"
                @click="onScaleChipClick(scale.value)"
              >
                {{ scale.label }} {{ scale.audio }}
              </view>
            </view>
            <picker
              mode="selector"
              :range="bookScales"
              range-key="label"
              :value="bookScales.findIndex(s => s.value === newBook.bookScale)"
              @change="onBookScaleChange"
            >
              <text class="more-scales">更多规模 ▼</text>
            </picker>
          </view>

          <!-- 预估信息（选择规模后显示在最上方） -->
          <view v-if="!isEditMode && bookEstimate && bookEstimate.words && bookEstimate.audioMinutes" class="estimate-card">
            <view class="estimate-row">
              <text class="estimate-label">📊 预估：</text>
              <text class="estimate-value">{{ bookEstimate.words.min }}~{{ bookEstimate.words.max }}字</text>
              <text class="estimate-sep">|</text>
              <text class="estimate-value">{{ bookEstimate.audioMinutes.min }}~{{ bookEstimate.audioMinutes.max }}分钟</text>
              <text class="estimate-sep">|</text>
              <text class="estimate-value">约{{ bookEstimate.estimatedChapters }}章</text>
            </view>
            <view v-if="quotaCheck" class="quota-row">
              <text v-if="quotaCheck.allowed" class="quota-ok">✅ 额度充足</text>
              <text v-else class="quota-warn">⚠️ {{ quotaCheck.reason }}</text>
            </view>
          </view>
        </view>

        <!-- ========== 读者配置区 ========== -->
        <view class="section">
          <text class="section-title">读者配置</text>

          <!-- 面向人群 -->
          <view class="form-item">
            <text class="form-label">面向人群</text>
            <view class="chip-group">
              <view
                v-for="audience in audiences"
                :key="audience.value"
                :class="['chip', newBook.targetAudience === audience.value ? 'active' : '']"
                @click="newBook.targetAudience = audience.value; syncToDescription('面向人群', audience.value)"
              >
                <text class="chip-icon">{{ audience.icon }}</text>
                <text class="chip-text">{{ audience.label }}</text>
              </view>
            </view>
          </view>

          <!-- 知识难度 -->
          <view class="form-item">
            <text class="form-label">知识难度</text>
            <view class="chip-group">
              <view
                v-for="level in knowledgeLevels"
                :key="level.value"
                :class="['chip', newBook.knowledgeLevel === level.value ? 'active' : '']"
                @click="newBook.knowledgeLevel = level.value; syncToDescription('知识难度', level.value)"
              >
                <text class="chip-icon">{{ level.icon }}</text>
                <text class="chip-text">{{ level.label }}</text>
              </view>
            </view>
          </view>

          <!-- 书籍类型 -->
          <view class="form-item">
            <text class="form-label">书籍类型</text>
            <view class="chip-group">
              <view
                v-for="bt in bookTypes"
                :key="bt.value"
                :class="['chip', newBook.bookType === bt.value ? 'active' : '']"
                @click="newBook.bookType = bt.value; syncToDescription('书籍类型', bt.value)"
              >
                <text class="chip-icon">{{ bt.icon }}</text>
                <text class="chip-text">{{ bt.label }}</text>
              </view>
            </view>
          </view>

          <!-- 大纲层级 -->
          <view class="form-item">
            <text class="form-label">大纲层级</text>
            <view class="chip-group">
              <view
                v-for="opt in outlineLevelOptions"
                :key="opt.value"
                :class="['chip', newBook.outlineLevel === opt.value ? 'active' : '']"
                @click="newBook.outlineLevel = opt.value; syncToDescription('大纲层级', opt.value)"
              >
                <text class="chip-text">{{ opt.label }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- ========== 高级定制区（默认展开） ========== -->
        <view class="section">
          <view class="section-header" @click="showAdvancedOptions = !showAdvancedOptions">
            <text class="section-title">高级定制</text>
            <text class="section-arrow">{{ showAdvancedOptions ? '▲' : '▼' }}</text>
          </view>

          <view v-if="showAdvancedOptions" class="section-content">
            <!-- 快速模板 -->
            <view class="form-item">
              <text class="form-label">📋 快速模板</text>
              <view class="template-grid">
                <view
                  v-for="template in quickTemplates"
                  :key="template.name"
                  class="template-card"
                  @click="applyTemplate(template)"
                >
                  <text class="template-icon">{{ template.icon }}</text>
                  <text class="template-name">{{ template.name }}</text>
                  <text class="template-desc">{{ template.desc }}</text>
                </view>
              </view>
            </view>

            <!-- 写作风格 -->
            <view class="form-item">
              <text class="form-label">写作风格</text>
              <view class="chip-group">
                <view
                  v-for="style in styles"
                  :key="style"
                  :class="['chip', newBook.style === style ? 'active' : '']"
                  @click="newBook.style = style; syncToDescription('写作风格', style)"
                >
                  {{ style }}
                </view>
              </view>
            </view>

            <!-- 行业领域 -->
            <view class="form-item">
              <text class="form-label">行业领域</text>
              <view class="chip-group">
                <view
                  v-for="industry in industries"
                  :key="industry.value"
                  :class="['chip', newBook.industry === industry.value ? 'active' : '']"
                  @click="newBook.industry = industry.value; syncToDescription('行业领域', industry.label)"
                >
                  <text class="chip-icon">{{ industry.icon }}</text>
                  <text class="chip-text">{{ industry.label }}</text>
                </view>
              </view>
            </view>

            <!-- 特殊要求 (多选) -->
            <view class="form-item">
              <text class="form-label">特殊要求</text>
              <view class="chip-group">
                <view
                  v-for="feature in specialFeatures"
                  :key="feature.value"
                  :class="['chip', newBook.specialFeatures.includes(feature.value) ? 'active' : '']"
                  @click="toggleSpecialFeature(feature.value)"
                >
                  <text class="chip-icon">{{ feature.icon }}</text>
                  <text class="chip-text">{{ feature.label }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 提交按钮（固定底部） -->
        <view class="btn-group-fixed">
          <button v-if="isEditMode" class="btn-primary" :disabled="!canCreateBook || creating" @click="createNewBook">
            {{ creating ? '保存中...' : '保存修改' }}
          </button>
          <template v-else>
            <button class="btn-cancel" @click="goBack">取消</button>
            <button
              class="btn-primary"
              :disabled="!canCreateBook || creating"
              @click="createNewBook"
            >
              {{ creating ? '创建中...' : '创建书籍' }}
            </button>
          </template>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import * as api from '../../utils/book-generator-api';
import { getApiBaseUrl } from '../../utils/config';

const BASE_URL = getApiBaseUrl();

// 创建表单
const creating = ref(false);
const showAdvancedOptions = ref(true); // 默认展开高级选项
const isRecommending = ref(false);
const attemptedCreate = ref(false);
const isEditMode = ref(false);
const editingBookId = ref<string | null>(null);
const newBook = ref({
  title: '',
  subtitle: '',
  description: '',
  targetAudience: '',
  knowledgeLevel: '',
  industry: '',
  specialFeatures: [] as string[],
  style: '',
  bookScale: '',
  bookType: 'auto',
  outlineLevel: 'auto',
});

// 书籍预估信息
const bookEstimate = ref<{
  scale: string;
  words: { min: number; max: number; avg: number };
  audioMinutes: { min: number; max: number; avg: number };
  estimatedChapters: number;
  defaultGenLevel?: number;
  genLevelInfo?: { label: string; desc: string };
} | null>(null);

// 配额检查结果
const quotaCheck = ref<{
  allowed: boolean;
  reason: string | null;
  estimatedWords: { min: number; max: number; avg: number };
  estimatedAudioMinutes: { min: number; max: number; avg: number };
  quota: {
    totalMinutes: number;
    usedMinutes: number;
    remainingMinutes: number;
    overageEnabled: boolean;
    overagePrice: number;
  };
  costEstimate: {
    inQuotaMinutes: number;
    overageMinutes: number;
    estimatedPrice: number;
    displayText: string;
  };
} | null>(null);

// 选项配置
const knowledgeLevels = [
  { value: '入门', label: '入门级', icon: '🌱', desc: '零基础，简单易懂' },
  { value: '基础', label: '基础级', icon: '📚', desc: '基本概念，循序渐进' },
  { value: '进阶', label: '进阶级', icon: '📈', desc: '深入讲解，系统全面' },
  { value: '高级', label: '高级级', icon: '🎯', desc: '专业深入，前沿技术' },
  { value: '专家', label: '专家级', icon: '🔬', desc: '研究级别，底层原理' },
];

const audiences = [
  { value: '儿童', label: '儿童', icon: '👶', desc: '6-12岁，形象生动' },
  { value: '青少年', label: '青少年', icon: '🧑', desc: '13-18岁，通俗易懂' },
  { value: '大学生', label: '大学生', icon: '🎓', desc: '系统专业，有理论' },
  { value: '专业人士', label: '专业人士', icon: '💼', desc: '从业者，实用深入' },
  { value: '研究生', label: '研究生', icon: '🔍', desc: '研究级别，前沿深入' },
  { value: '大众读者', label: '大众读者', icon: '👥', desc: '通俗普及，有趣味' },
];

const industries = [
  { value: '', label: '不选', icon: '➖', desc: '不限定行业领域' },
  { value: 'IT/计算机', label: 'IT/计算机', icon: '💻', desc: '编程、软件、互联网' },
  { value: '金融', label: '金融', icon: '💰', desc: '投资、银行、证券' },
  { value: '医学', label: '医学', icon: '🏥', desc: '医疗、健康、临床' },
  { value: '教育', label: '教育', icon: '📚', desc: '教学、学习、心理学' },
  { value: '文学', label: '文学', icon: '✍️', desc: '小说、散文、传记' },
  { value: '科普', label: '科普', icon: '🔬', desc: '科学、自然、探索' },
  { value: '商业', label: '商业', icon: '📊', desc: '管理、营销、创业' },
  { value: '艺术', label: '艺术', icon: '🎨', desc: '设计、音乐、影视' },
];

const specialFeatures = [
  { value: '案例分析', label: '案例分析', icon: '📖' },
  { value: '代码示例', label: '代码示例', icon: '💻' },
  { value: '习题练习', label: '习题练习', icon: '✍️' },
  { value: '图表插图', label: '图表插图', icon: '📊' },
  { value: '项目实战', label: '项目实战', icon: '🎯' },
  { value: '思维导图', label: '思维导图', icon: '🧠' },
  { value: '总结回顾', label: '总结回顾', icon: '📝' },
];

const quickTemplates = [
  {
    name: '大学教材',
    icon: '🎓',
    desc: '面向大学生，系统专业，有案例习题',
    config: {
      knowledgeLevel: '进阶',
      targetAudience: '大学生',
      industry: '教育',
      specialFeatures: ['案例分析', '习题练习', '总结回顾'],
      style: '专业严谨',
    },
  },
  {
    name: '技术教程',
    icon: '💻',
    desc: '面向初学者，有代码示例和实战项目',
    config: {
      knowledgeLevel: '入门',
      targetAudience: '初学者',
      industry: 'IT/计算机',
      specialFeatures: ['代码示例', '项目实战', '案例分析'],
      style: '通俗易懂',
    },
  },
  {
    name: '科普读物',
    icon: '🔬',
    desc: '面向大众，通俗易懂，有趣味性',
    config: {
      knowledgeLevel: '入门',
      targetAudience: '大众读者',
      industry: '科普',
      specialFeatures: ['案例分析', '图表插图'],
      style: '轻松幽默',
    },
  },
  {
    name: '商业书籍',
    icon: '📊',
    desc: '面向从业者，有真实案例，实用性强',
    config: {
      knowledgeLevel: '进阶',
      targetAudience: '专业人士',
      industry: '商业',
      specialFeatures: ['案例分析', '总结回顾'],
      style: '专业严谨',
    },
  },
  {
    name: '儿童读物',
    icon: '👶',
    desc: '面向儿童，形象生动，有趣味性',
    config: {
      knowledgeLevel: '入门',
      targetAudience: '儿童',
      industry: '教育',
      specialFeatures: ['图表插图'],
      style: '轻松幽默',
    },
  },
  {
    name: '学术研究',
    icon: '🔍',
    desc: '面向研究生，前沿深入，有研究价值',
    config: {
      knowledgeLevel: '专家',
      targetAudience: '研究生',
      industry: 'IT/计算机',
      specialFeatures: ['案例分析', '总结回顾'],
      style: '专业严谨',
    },
  },
];

const styles = ['不填', '通俗易懂', '专业严谨', '轻松幽默', '诗意优美', '故事化'];
const commonScales = [
  { value: '1000', label: '1千字', audio: '约5分钟' },
  { value: '3000', label: '3千字', audio: '约15分钟' },
  { value: '5000', label: '5千字', audio: '约25分钟' },
  { value: '130000', label: '13万字', audio: '约11小时' },
];

const bookScales = [
  { value: '340000', label: '上2 | 34万字 170章 约28小时' },
  { value: '210000', label: '上1 | 21万字 105章 约17小时' },
  { value: '130000', label: '标准 | 13万字 65章 约11小时' },
  { value: '80000', label: '下1 | 8万字 40章 约7小时' },
  { value: '50000', label: '下2 | 5万字 25章 约4小时' },
  { value: '31000', label: '下3 | 3.1万字 16章 约2.5小时' },
  { value: '19000', label: '下4 | 1.9万字 10章 约1.5小时' },
  { value: '12000', label: '下5 | 1.2万字 6章 约1小时' },
  { value: '7000', label: '下6 | 7千字 4章 约35分钟' },
  { value: '4000', label: '下7 | 4千字 2章 约20分钟' },
  { value: '3000', label: '下8 | 3千字 2章 约15分钟' },
  { value: '2000', label: '下9 | 2千字 1章 约10分钟' },
  { value: '1000', label: '下10 | 1千字 1章 约5分钟' },
];

// 书籍类型选项
const bookTypes = [
  { value: 'auto', label: '自动检测', icon: '🤖', desc: 'AI判断类型决定大纲' },
  { value: '教材', label: '教材/学术', icon: '📚', desc: '3层大纲' },
  { value: '技术教程', label: '技术教程', icon: '💻', desc: '3层大纲' },
  { value: '小说', label: '小说/文学', icon: '📖', desc: '1层大纲' },
  { value: '商业', label: '商业/经管', icon: '📊', desc: '2层大纲' },
  { value: '科普', label: '科普/大众', icon: '🔬', desc: '2层大纲' },
];

// 大纲层级选项
const outlineLevelOptions = [
  { value: 'auto', label: '自动', desc: '根据规模自动选择' },
  { value: '1', label: '1层', desc: '仅章，无节和小节' },
  { value: '2', label: '2层', desc: '章→节，有节无小节' },
  { value: '3', label: '3层', desc: '章→节→小节，完整三层' },
];

// 计算属性
const canCreateBook = computed(() => {
  if (quotaCheck.value && !quotaCheck.value.allowed) {
    return false;
  }
  return !!newBook.value.description.trim();
});

// 切换特殊要求
function toggleSpecialFeature(feature: string) {
  const features = newBook.value.specialFeatures;
  const index = features.indexOf(feature);
  if (index > -1) {
    features.splice(index, 1);
  } else {
    features.push(feature);
  }
  syncToDescription('特殊要求', newBook.value.specialFeatures.join('、'));
}

// 应用模板
function applyTemplate(template: typeof quickTemplates[0]) {
  const config = template.config;
  newBook.value.knowledgeLevel = config.knowledgeLevel;
  newBook.value.targetAudience = config.targetAudience;
  newBook.value.industry = config.industry;
  newBook.value.specialFeatures = [...config.specialFeatures];
  newBook.value.style = config.style;

  // 自动展开高级选项
  showAdvancedOptions.value = true;

  uni.showToast({
    title: `已应用${template.name}模板`,
    icon: 'success',
  });
}

// AI自动优化描述（直接应用）
async function requestSmartRecommend() {
  if (!newBook.value.description.trim() || isRecommending.value) return;

  isRecommending.value = true;
  try {
    const response = await uni.request({
      url: `${BASE_URL}/book-generator/langgraph/smart-recommend`,
      method: 'POST',
      data: {
        description: newBook.value.description.trim(),
        title: newBook.value.title.trim(),
      },
    });

    const res = response.data as any;
    if (res.code === 0 && res.data) {
      const rec = res.data;
      const parts: string[] = [];

      if (rec.knowledgeLevel) {
        newBook.value.knowledgeLevel = rec.knowledgeLevel;
        parts.push(`知识难度：${rec.knowledgeLevel}`);
      }
      if (rec.targetAudience) {
        newBook.value.targetAudience = rec.targetAudience;
        parts.push(`面向人群：${rec.targetAudience}`);
      }
      if (rec.style) {
        newBook.value.style = rec.style;
        parts.push(`写作风格：${rec.style}`);
      }
      if (rec.industry) {
        newBook.value.industry = rec.industry;
        parts.push(`行业领域：${rec.industry}`);
      }

      // 追加到description textarea
      if (parts.length > 0) {
        const separator = newBook.value.description.trim() ? '\n' : '';
        newBook.value.description = newBook.value.description.trim() + separator + parts.join('\n');
      }

      // 自动展开高级选项
      showAdvancedOptions.value = true;

      uni.showToast({
        title: '推荐成功',
        icon: 'success',
      });
    } else {
      uni.showToast({
        title: res.message || '推荐失败',
        icon: 'none',
      });
    }
  } catch (e: any) {
    console.error('AI自动优化描述失败:', e);
    uni.showToast({
      title: '推荐服务暂不可用',
      icon: 'none',
    });
  } finally {
    isRecommending.value = false;
  }
}

// scale chip 点击处理
function onScaleChipClick(value: string) {
  onBookScaleChange({ detail: { value: bookScales.findIndex(s => s.value === value) } });
}

// 将选项同步到description textarea
function syncToDescription(label: string, value: string) {
  if (!value || value === 'auto' || value === '不填') return;
  const line = `${label}：${value}`;
  const desc = newBook.value.description;
  // 检查是否已存在该标签
  if (desc.includes(`${label}：`)) {
    // 替换已有行
    newBook.value.description = desc.replace(new RegExp(`${label}：[^\\n]*`), line);
  } else {
    // 追加新行
    newBook.value.description = desc.trim() ? `${desc.trim()}\n${line}` : line;
  }
}

// 选择书籍规模时加载预估
function getScaleDisplay(value: string): string {
  return bookScales.find(s => s.value === value)?.label || '';
}

async function onBookScaleChange(e: any) {
  const index = e.detail.value;
  const scale = bookScales[index].value;
  newBook.value.bookScale = scale;
  syncToDescription('书籍规模', scale);

  try {
    const bt = newBook.value.bookType;
    const bookTypeParam = bt && bt !== 'auto' ? `&bookType=${encodeURIComponent(bt)}` : '';
    const response = await uni.request({
      url: `${BASE_URL}/book-generator/langgraph/estimate?scale=${encodeURIComponent(scale)}&userId=1${bookTypeParam}`,
      method: 'GET'
    });

    const res = response.data as any;
    if (res.code === 0 && res.data && res.data.words && res.data.audioMinutes) {
      bookEstimate.value = {
        scale: res.data.scale,
        words: res.data.words,
        audioMinutes: res.data.audioMinutes,
        estimatedChapters: res.data.estimatedChapters
      };

      if (res.data.quotaCheck) {
        quotaCheck.value = res.data.quotaCheck;
      }
    } else {
      console.warn('预估数据不完整:', res);
      bookEstimate.value = null;
    }
  } catch (e) {
    console.error('加载预估失败:', e);
    bookEstimate.value = null;
    quotaCheck.value = null;
  }
}

function switchToInteractive() {
  uni.redirectTo({ url: '/pages/book-generator/interactive' });
}

// AI 预览检测规模（用户未手动选时，描述失焦自动触发）
let detectTimer: any = null;
async function detectScaleFromDesc() {
  const desc = newBook.value.description?.trim();
  if (!desc || newBook.value.bookScale) return; // 已手动选过，不覆盖
  clearTimeout(detectTimer);
  detectTimer = setTimeout(async () => {
    try {
      const response = await uni.request({
        url: `${BASE_URL}/book-generator/langgraph/detect-scale`,
        method: 'POST',
        data: { description: desc }
      });
      const res = response.data as any;
      if (res.code === 0 && res.data) {
        newBook.value.bookScale = res.data.bookScale;
        bookEstimate.value = {
          scale: res.data.bookScale,
          words: { min: res.data.totalWords, max: res.data.totalWords, avg: res.data.totalWords },
          audioMinutes: { min: 0, max: 0, avg: 0 },
          estimatedChapters: res.data.chapters,
        };
      }
    } catch { /* AI 调用失败不影响用户操作 */ }
  }, 800);
}

function goBack() {
  const pages = getCurrentPages();
  if (pages.length > 1) {
    uni.navigateBack();
  } else {
    uni.switchTab({ url: '/pages/index/index' });
  }
}

// 创建新书籍或更新书籍
async function createNewBook() {
  attemptedCreate.value = true;
  if (!canCreateBook.value) return;

  // 编辑模式：调用更新接口
  if (isEditMode.value && editingBookId.value) {
    try {
      await api.updateBook(editingBookId.value, {
        title: newBook.value.title || undefined,
        description: newBook.value.description || undefined,
        targetAudience: newBook.value.targetAudience || undefined,
        style: newBook.value.style || undefined,
        bookScale: newBook.value.bookScale || undefined,
      });
      uni.showToast({ title: '更新成功', icon: 'success' });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } catch (e: any) {
      uni.showToast({ title: e.message || '更新失败', icon: 'none' });
    } finally {
      creating.value = false;
    }
    return;
  }

  // 创建模式：原逻辑
  const configSummary: string[] = [];
  if (newBook.value.knowledgeLevel) configSummary.push(`知识难度：${newBook.value.knowledgeLevel}`);
  if (newBook.value.targetAudience) configSummary.push(`面向人群：${newBook.value.targetAudience}`);
  if (newBook.value.industry) configSummary.push(`行业领域：${newBook.value.industry}`);
  if (newBook.value.specialFeatures.length > 0) configSummary.push(`特殊要求：${newBook.value.specialFeatures.join('、')}`);
  if (newBook.value.style) configSummary.push(`写作风格：${newBook.value.style}`);

  const confirmResult = await new Promise<boolean>((resolve) => {
    uni.showModal({
      title: '📋 生成配置确认',
      content: `${configSummary.join('\n')}\n\n书名将由AI根据描述自动生成\n\n确认开始生成？`,
      confirmText: '确认生成',
      cancelText: '返回修改',
      success: (res) => resolve(res.confirm),
    });
  });

  if (!confirmResult) return;

  creating.value = true;
  try {
    let mergedDesc = newBook.value.description.trim();
    if (newBook.value.knowledgeLevel && newBook.value.knowledgeLevel !== '不填') {
      mergedDesc += `\n知识难度：${newBook.value.knowledgeLevel}`;
    }
    if (newBook.value.targetAudience && newBook.value.targetAudience !== '不填') {
      mergedDesc += `\n面向人群：${newBook.value.targetAudience}`;
    }
    if (newBook.value.industry && newBook.value.industry !== '不填') {
      mergedDesc += `\n行业领域：${newBook.value.industry}`;
    }
    if (newBook.value.specialFeatures && newBook.value.specialFeatures.length > 0) {
      mergedDesc += `\n特殊要求：${newBook.value.specialFeatures.join('、')}`;
    }
    if (newBook.value.style && newBook.value.style !== '不填') {
      mergedDesc += `\n写作风格：${newBook.value.style}`;
    }

    const genLevel = newBook.value.outlineLevel === 'auto' ? undefined : parseInt(newBook.value.outlineLevel);
    const bookType = newBook.value.bookType === 'auto' ? undefined : newBook.value.bookType;
    const result = await api.createBook({
      title: newBook.value.title,
      subtitle: newBook.value.subtitle,
      description: mergedDesc,
      bookScale: newBook.value.bookScale || undefined,
      bookType,
      genLevel,
    });

    uni.showToast({ title: '创建成功', icon: 'success' });

    // 跳转到详情页
    setTimeout(() => {
      uni.navigateTo({
        url: `/pages/book-generator/detail?id=${result.id}`
      });
    }, 1500);
  } catch (e: any) {
    uni.showToast({ title: e.message || '创建失败', icon: 'none' });
  } finally {
    creating.value = false;
  }
}

onMounted(() => {
  // 不再默认选中规模，让 AI 根据描述自动判断
});

onLoad(async (query: any) => {
  if (query?.editId) {
    isEditMode.value = true;
    editingBookId.value = query.editId;
    // 加载书籍数据用于编辑
    try {
      const book = await api.getBookForEdit(query.editId);
      if (book) {
        newBook.value.title = book.title || '';
        newBook.value.description = book.description || '';
        newBook.value.targetAudience = book.targetAudience || '';
        newBook.value.style = book.style || '';
        newBook.value.bookScale = book.bookScale || '';
      }
    } catch (e) {
      console.error('加载书籍失败:', e);
    }
  }
});
</script>

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

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background: #ffffff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.nav-content {
  display: flex;
  align-items: center;
  height: 88rpx;
  padding: 0 32rpx;
  padding-top: env(safe-area-inset-top);
}

.nav-left { width: 60rpx; flex-shrink: 0; }
.back-icon { font-size: 40rpx; color: #1f2937; }
.page-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1f2937;
  flex: 1;
  text-align: center;
}

/* 模式切换独立行 */
.mode-bar { padding: 0 32rpx 16rpx 32rpx; }
.mode-switch { display: flex; align-items: center; justify-content: center; width: 100%; height: 72rpx; background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%); color: #fff; border-radius: 12rpx; font-size: 26rpx; font-weight: 600; }

.main-content {
  padding-top: calc(88rpx + 16rpx + 72rpx + 16rpx + env(safe-area-inset-top));
}

.card {
  margin: 24rpx;
  padding: 32rpx;
  background: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.card-header { margin-bottom: 32rpx; }
.card-title { font-size: 36rpx; font-weight: 700; color: #1f2937; }

.form-item { margin-bottom: 32rpx; }
.form-label { font-size: 28rpx; font-weight: 600; color: #374151; margin-bottom: 12rpx; display: block; }
.form-hint { font-size: 24rpx; color: #9ca3af; margin-bottom: 16rpx; display: block; }
.form-hint-small { font-size: 24rpx; color: #9ca3af; margin-bottom: 16rpx; display: block; }

.form-input {
  width: 100%;
  height: 88rpx;
  padding: 0 24rpx;
  background: #f9fafb;
  border: 2rpx solid #e5e7eb;
  border-radius: 12rpx;
  font-size: 28rpx;
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 24rpx;
  padding-bottom: 60rpx;
  background: #f9fafb;
  border: 2rpx solid #e5e7eb;
  border-radius: 12rpx;
  font-size: 28rpx;
  line-height: 1.6;
  box-sizing: border-box;
}
.form-textarea.error { border-color: #ef4444; }
.textarea-wrapper { position: relative; }
.char-count {
  position: absolute;
  right: 24rpx;
  bottom: 16rpx;
  font-size: 22rpx;
  color: #9ca3af;
}

.chip-group { display: flex; flex-wrap: wrap; gap: 12rpx; }
.chip {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 20rpx;
  background: #f3f4f6;
  border-radius: 24rpx;
  font-size: 24rpx;
  color: #4b5563;
  transition: all 0.2s;
}
.chip.active { background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%); color: white; }
.chip-icon { font-size: 24rpx; }
.chip-text { font-size: 24rpx; }

.template-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 16rpx; margin-top: 16rpx; }
.template-card {
  padding: 20rpx;
  background: #f9fafb;
  border: 2rpx solid #e5e7eb;
  border-radius: 12rpx;
  text-align: center;
  transition: all 0.2s;
}
.template-card:active { transform: scale(1.02); box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.1); }
.template-icon { font-size: 40rpx; display: block; margin-bottom: 8rpx; }
.template-name { font-size: 26rpx; font-weight: 600; color: #1f2937; display: block; }
.template-desc { font-size: 22rpx; color: #9ca3af; display: block; margin-top: 4rpx; }

.scale-chips { display: flex; flex-wrap: wrap; gap: 12rpx; margin-bottom: 16rpx; }
.more-scales { font-size: 24rpx; color: #6366f1; padding: 12rpx 0; }

/* 预估卡片 */
.estimate-card {
  background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 24rpx;
}
.estimate-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8rpx; }
.estimate-label { font-size: 24rpx; color: #065f46; }
.estimate-value { font-size: 24rpx; font-weight: 500; color: #065f46; }
.estimate-sep { font-size: 24rpx; color: #6b7280; }
.quota-row { margin-top: 8rpx; }
.quota-ok { font-size: 24rpx; color: #059669; }
.quota-warn { font-size: 24rpx; color: #dc2626; }

/* AI自动优化描述按钮 */
.btn-smart-recommend {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  width: 100%;
  height: 80rpx;
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  border-radius: 12rpx;
  border: none;
}
.btn-smart-recommend[disabled] { opacity: 0.5; }
.recommend-icon { font-size: 32rpx; }
.recommend-text { font-size: 28rpx; font-weight: 600; color: white; }

/* 快速创建按钮 */
.quick-create-bar {
  margin-top: -8rpx;
  margin-bottom: 24rpx;
}
.btn-quick-create {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 80rpx;
  background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%);
  border-radius: 12rpx;
  border: none;
  font-size: 28rpx;
  font-weight: 600;
  color: white;
}
.btn-quick-create[disabled] { opacity: 0.5; }

/* 区域样式 */
.section { margin-bottom: 32rpx; padding-bottom: 32rpx; border-bottom: 1rpx solid #e5e7eb; }
.section:last-of-type { border-bottom: none; }
.section-title { font-size: 32rpx; font-weight: 600; color: #1f2937; display: block; margin-bottom: 24rpx; }
.section-header { display: flex; align-items: center; justify-content: space-between; padding: 16rpx 0; }
.section-arrow { font-size: 24rpx; color: #9ca3af; }
.section-content { margin-top: 16rpx; }

/* 按钮组固定底部 */
.btn-group-fixed {
  display: flex;
  gap: 16rpx;
  padding: 24rpx 0;
  position: sticky;
  bottom: 0;
  background: white;
  box-shadow: 0 -4rpx 16rpx rgba(0,0,0,0.05);
}
.btn-cancel, .btn-primary {
  flex: 1;
  height: 88rpx;
  border-radius: 16rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
}
.btn-cancel { background: #f3f4f6; color: #6b7280; }
.btn-primary { background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%); color: white; }
.btn-primary[disabled] { opacity: 0.5; }
</style>
