<template>
  <view class="page">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-content">
        <text class="page-title">生成音频</text>
      </view>
    </view>

    <!-- 主内容区 -->
    <view class="main-content">
      <!-- 文本输入区 -->
      <view class="card input-card">
        <view class="card-header">
          <text class="card-title">输入文本</text>
          <text class="word-count" :class="{ warning: text.length > 1800, error: text.length >= 2000 }">
            {{ text.length }}/2000 字
          </text>
        </view>
        <textarea
          v-model="text"
          class="text-input"
          placeholder="请输入要转换的文本内容..."
          :maxlength="2000"
          auto-height
        />
        <view class="input-actions">
          <button class="action-btn ai-btn" @click="goToAIPage">
            <text>🤖 AI 对话</text>
          </button>
          <button class="action-btn ai-btn" @click="goToAIContentPage">
            <text>📝 AI 内容</text>
          </button>
          <button class="action-btn template-btn" @click="showTemplatePanel = true">
            <text>📝 模板</text>
          </button>
          <button class="action-btn" @click="clearText">清空</button>
          <button class="action-btn" @click="pasteText">粘贴</button>
        </view>
        <view class="input-hint">
          <text>支持长按粘贴文本内容</text>
        </view>
      </view>

      <!-- 音色选择 - 网格布局 -->
      <view class="card voice-card">
        <text class="card-title">选择音色</text>
        <view class="voice-grid">
          <view
            v-for="voice in audioStore.voices"
            :key="voice.id"
            class="voice-item"
            :class="{ active: selectedVoice === voice.id }"
            @click="selectedVoice = voice.id"
          >
            <view class="voice-icon">
              <text>{{ voice.gender === 'female' ? '👩' : '👨' }}</text>
            </view>
            <text class="voice-name">{{ voice.name }}</text>
          </view>
        </view>
      </view>

      <!-- 参数调节 -->
      <view class="card params-card">
        <text class="card-title">参数调节</text>
        <view class="param-item">
          <view class="param-header">
            <text class="param-label">语速</text>
            <view class="param-value">{{ voiceParams.speed.toFixed(1) }}x</view>
          </view>
          <slider
            :value="(voiceParams.speed - 0.5) * 100 / 1.5"
            :min="0"
            :max="100"
            @change="(e: any) => voiceParams.speed = Number((0.5 + (e.detail.value / 100) * 1.5).toFixed(1))"
            activeColor="#4F46E5"
            backgroundColor="#e5e7eb"
            block-size="20"
          />
          <view class="param-range">
            <text>0.5x</text>
            <text>2.0x</text>
          </view>
        </view>
        <view class="param-item">
          <view class="param-header">
            <text class="param-label">音调</text>
            <view class="param-value">{{ voiceParams.pitch > 0 ? '+' : '' }}{{ voiceParams.pitch }}</view>
          </view>
          <slider
            :value="(voiceParams.pitch + 500) / 10"
            :min="0"
            :max="100"
            @change="(e: any) => voiceParams.pitch = Math.round(e.detail.value * 10 - 500)"
            activeColor="#4F46E5"
            backgroundColor="#e5e7eb"
            block-size="20"
          />
          <view class="param-range">
            <text>-500</text>
            <text>+500</text>
          </view>
        </view>
        <view class="param-item">
          <view class="param-header">
            <text class="param-label">音量</text>
            <view class="param-value">{{ voiceParams.volume }}%</view>
          </view>
          <slider
            :value="voiceParams.volume"
            :min="0"
            :max="100"
            @change="(e: any) => voiceParams.volume = e.detail.value"
            activeColor="#4F46E5"
            backgroundColor="#e5e7eb"
            block-size="20"
          />
          <view class="param-range">
            <text>0%</text>
            <text>100%</text>
          </view>
        </view>
      </view>

      <!-- 生成按钮 -->
      <button
        class="generate-btn"
        :disabled="!canGenerate"
        @click="handleGenerate"
        @touchstart="btnPressed = true"
        @touchend="btnPressed = false"
        :class="{ pressed: btnPressed }"
      >
        <text class="btn-text">{{ generating ? '生成中...' : '🎵 生成音频' }}</text>
      </button>
    </view>

    <!-- 模板选择面板 -->
    <view v-if="showTemplatePanel" class="template-panel" @click="showTemplatePanel = false">
      <view class="template-content" @click.stop>
        <view class="template-header">
          <text class="template-title">选择模板</text>
          <text class="template-close" @click="showTemplatePanel = false">✕</text>
        </view>

        <!-- 分类标签 -->
        <scroll-view scroll-x class="category-tabs">
          <view
            class="category-tab"
            :class="{ active: selectedCategory === '' }"
            @click="selectedCategory = ''"
          >
            <text>全部</text>
          </view>
          <view
            v-for="cat in templateCategories"
            :key="cat.name"
            class="category-tab"
            :class="{ active: selectedCategory === cat.name }"
            @click="selectedCategory = cat.name"
          >
            <text>{{ cat.name }}</text>
          </view>
        </scroll-view>

        <!-- 模板列表 -->
        <scroll-view scroll-y class="template-list">
          <view
            v-for="template in filteredTemplates"
            :key="template.id"
            class="template-item"
            @click="selectTemplate(template)"
          >
            <view class="template-item-header">
              <text class="template-name">{{ template.name }}</text>
              <text class="template-category">{{ template.category }}</text>
            </view>
            <text class="template-desc">{{ template.description || '暂无描述' }}</text>
            <text class="template-preview">{{ template.content.slice(0, 50) }}...</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { useUserStore } from '../../store/user';
import { useAudioStore } from '../../store/audio';
import { get } from '../../utils/request';
import type { VoiceParams } from '../../types';

interface Template {
  id: number;
  name: string;
  category: string;
  content: string;
  description?: string;
}

const userStore = useUserStore();
const audioStore = useAudioStore();

// 状态
const text = ref('');
const selectedVoice = ref('cherry');
const voiceParams = ref<VoiceParams>({
  speed: 1.0,
  pitch: 0,
  volume: 50,
});
const generating = ref(false);
const btnPressed = ref(false);

// 模板相关状态
const showTemplatePanel = ref(false);
const templates = ref<Template[]>([]);
const templateCategories = ref<{ name: string; count: number }[]>([]);
const selectedCategory = ref('');

// 筛选后的模板
const filteredTemplates = computed(() => {
  if (!selectedCategory.value) return templates.value;
  return templates.value.filter(t => t.category === selectedCategory.value);
});

// 计算属性
const canGenerate = computed(() => {
  return text.value.trim().length > 0 && !generating.value;
});

// 初始化
onMounted(async () => {
  await audioStore.fetchVoices();
  await fetchTemplates();
});

// 获取模板列表
async function fetchTemplates() {
  try {
    const result = await get<{ data: Template[] }>('/templates');
    templates.value = result.data || [];
  } catch (error) {
    console.error('获取模板失败:', error);
  }
}

// 选择模板
function selectTemplate(template: Template) {
  text.value = template.content;
  showTemplatePanel.value = false;
  uni.showToast({ title: `已应用模板: ${template.name}`, icon: 'success' });
}

// 页面显示时检查是否有 AI 生成的文本
onShow(() => {
  const aiText = uni.getStorageSync('ai_generated_text');
  if (aiText) {
    text.value = aiText;
    uni.removeStorageSync('ai_generated_text');
    uni.showToast({ title: '已填充 AI 生成的文本', icon: 'success' });
  }
});

// 清空文本
function clearText() {
  text.value = '';
}

// 粘贴文本
async function pasteText() {
  const content = await uni.getClipboardData();
  if (content.data) {
    text.value = content.data;
  }
}

// 跳转到 AI 生成页面
function goToAIPage() {
  uni.navigateTo({ url: '/pages/ai/index' });
}

// 跳转到 AI 内容生成页面
function goToAIContentPage() {
  uni.navigateTo({ url: '/pages/ai-content/index' });
}

// 生成音频
async function handleGenerate() {
  if (!canGenerate.value) return;

  generating.value = true;
  try {
    const result = await audioStore.generateAudio(
      text.value,
      selectedVoice.value,
      voiceParams.value
    );

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

    // 清空文本，方便下次输入
    text.value = '';

    // 跳转到播放器
    uni.navigateTo({
      url: `/pages/player/index?id=${result.audioId}`,
    });
  } catch (error: any) {
    console.error('生成失败:', error);
    uni.showToast({ 
      title: error.message || '生成失败，请重试', 
      icon: 'none' 
    });
  } finally {
    generating.value = false;
  }
}
</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: center;
  padding: 0 32rpx;
  height: 88rpx;
}

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

.main-content {
  padding: 132rpx 32rpx 180rpx;
}

.card {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

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

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

.word-count {
  font-size: 24rpx;
  color: #6b7280;
}

.word-count.warning {
  color: #f59e0b;
}

.word-count.error {
  color: #ef4444;
  font-weight: 600;
}

.text-input {
  width: 100%;
  min-height: 300rpx;
  font-size: 28rpx;
  color: #1f2937;
  line-height: 1.6;
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16rpx;
  margin-top: 16rpx;
}

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

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

.action-btn {
  font-size: 24rpx;
  color: #6b7280;
  background: #f3f4f6;
  padding: 12rpx 24rpx;
  border-radius: 12rpx;
  border: none;
  transition: all 0.2s;
}

.action-btn:active {
  opacity: 0.7;
  transform: scale(0.98);
}

.action-btn::after {
  border: none;
}

.voice-list {
  white-space: nowrap;
  margin-top: 24rpx;
}

/* 音色网格布局 - 2列 */
.voice-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16rpx;
  margin-top: 24rpx;
}

.voice-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24rpx 16rpx;
  border-radius: 16rpx;
  background: #f9fafb;
  border: 2rpx solid transparent;
  transition: all 0.3s;
}

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

.voice-item.active .voice-name {
  color: #ffffff;
}

.voice-item:active {
  transform: scale(0.95);
}

.voice-icon {
  font-size: 48rpx;
  margin-bottom: 12rpx;
}

.voice-name {
  font-size: 26rpx;
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 4rpx;
}

.voice-desc {
  font-size: 20rpx;
  color: #6b7280;
}

.param-item {
  margin-top: 24rpx;
}

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

.param-label {
  font-size: 26rpx;
  color: #6b7280;
}

.param-value {
  font-size: 28rpx;
  font-weight: 600;
  color: #4F46E5;
  background: #EEF2FF;
  padding: 4rpx 16rpx;
  border-radius: 8rpx;
}

.param-range {
  display: flex;
  justify-content: space-between;
  margin-top: 8rpx;
}

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

.generate-btn {
  width: 100%;
  height: 100rpx;
  background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
  border-radius: 24rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(79, 70, 229, 0.4);
  transition: all 0.3s ease;
}

.generate-btn::after {
  border: none;
}

.generate-btn[disabled] {
  background: #e5e7eb;
  box-shadow: none;
}

.generate-btn.pressed {
  transform: scale(0.96);
  box-shadow: 0 4rpx 12rpx rgba(79, 70, 229, 0.3);
}

.btn-text {
  font-size: 34rpx;
  font-weight: 600;
  color: #ffffff;
  letter-spacing: 2rpx;
}

.ai-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

/* 模板选择面板 */
.template-panel {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: flex-end;
}

.template-content {
  width: 100%;
  max-height: 80vh;
  background: #ffffff;
  border-radius: 32rpx 32rpx 0 0;
  padding: 32rpx;
  display: flex;
  flex-direction: column;
}

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

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

.template-close {
  font-size: 40rpx;
  color: #9ca3af;
  padding: 8rpx;
}

.category-tabs {
  white-space: nowrap;
  margin-bottom: 24rpx;
}

.category-tab {
  display: inline-block;
  padding: 12rpx 24rpx;
  margin-right: 16rpx;
  border-radius: 32rpx;
  background: #f3f4f6;
  font-size: 26rpx;
  color: #6b7280;
}

.category-tab.active {
  background: #4f46e5;
  color: #ffffff;
}

.template-list {
  flex: 1;
  max-height: 50vh;
}

.template-item {
  padding: 24rpx;
  border-radius: 16rpx;
  background: #f9fafb;
  margin-bottom: 16rpx;
}

.template-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

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

.template-category {
  font-size: 22rpx;
  color: #9ca3af;
  background: #e5e7eb;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}

.template-desc {
  font-size: 24rpx;
  color: #6b7280;
  margin-bottom: 8rpx;
  display: block;
}

.template-preview {
  font-size: 22rpx;
  color: #9ca3af;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
