<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">{{ isAudioPublish ? '发布音频' : '发布视频' }}</text>
        <view class="nav-right"></view>
      </view>
    </view>

    <!-- 视频预览 -->
    <view class="video-preview" v-if="videoInfo?.videoUrl && !isAudioPublish">
      <video
        :src="fullVideoUrl"
        class="video-player"
        controls
        show-fullscreen-btn
      ></video>
    </view>

    <!-- 音频预览 -->
    <view class="audio-preview" v-if="isAudioPublish && audioInfo">
      <view class="audio-cover-large" :style="{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' }">
        <text class="audio-icon-large">🎵</text>
      </view>
      <view class="audio-info-large">
        <text class="audio-title-large">{{ audioInfo.title }}</text>
        <text class="audio-meta-large">{{ audioInfo.wordCount }}字 · {{ formatDuration(audioInfo.audioDuration) }}</text>
      </view>
    </view>

    <!-- 平台选择 -->
    <view class="section">
      <view class="section-title">选择发布平台</view>
      <view class="platform-grid">
        <view
          v-for="p in displayPlatforms"
          :key="p.id"
          class="platform-item"
          :class="{ 
            active: selectedPlatform === p.id, 
            'not-bound': !p.bound 
          }"
          @click="selectPlatform(p)"
        >
          <text class="platform-icon">{{ p.icon }}</text>
          <text class="platform-name">{{ p.name }}</text>
          <text class="platform-status" :class="{ 'status-bound': p.bound, 'status-not-bound': !p.bound }">
            {{ p.bound ? '已绑定' : '点击绑定' }}
          </text>
        </view>
      </view>
      <view class="platform-hint">
        <text>💡 提示：点击平台卡片即可选择，未绑定的平台需要先绑定账号</text>
      </view>
    </view>

    <!-- 绑定账号（平台未绑定时显示） -->
    <view class="section bind-section" v-if="selectedPlatform && !currentPlatform?.bound">
      <view class="section-title">绑定 {{ currentPlatform?.name }} 账号</view>
      <view class="bind-tips">
        <text class="tip-icon">ℹ️</text>
        <text class="tip-text">{{ currentPlatform?.tip }}</text>
      </view>

      <!-- 打开登录页面按钮 -->
      <button class="btn-primary login-btn" @click="openLoginWebView">
        🌐 打开 {{ currentPlatform?.name }} 登录页面
      </button>

      <!-- 分隔线 -->
      <view class="divider">
        <text class="divider-text">或者手动粘贴 Cookie</text>
      </view>

      <!-- 手动输入 Cookie -->
      <view class="cookie-input">
        <view class="input-label-row">
          <view class="input-label">Cookie</view>
          <button class="help-btn" @click="showCookieHelp">
            ❓ 如何获取
          </button>
        </view>
        <textarea
          class="input-area"
          v-model="manualCookie"
          placeholder="请粘贴登录后的 Cookie..."
          :adjust-position="true"
        ></textarea>
      </view>

      <view class="cookie-input">
        <view class="input-label">User-Agent（可选）</view>
        <input
          class="input-field"
          v-model="manualUA"
          placeholder="浏览器 User-Agent"
        />
      </view>

      <button class="btn-primary" @click="bindAccount" :disabled="!manualCookie">
        确认绑定
      </button>
    </view>

    <!-- 已绑定账号 -->
    <view class="section" v-if="currentPlatform?.bound">
      <view class="account-card">
        <image
          class="account-avatar"
          :src="currentPlatform.avatar || '/static/default-avatar.png'"
          mode="aspectFill"
        ></image>
        <view class="account-info">
          <text class="account-name">{{ currentPlatform.nickname }}</text>
          <text class="account-valid" :class="{ valid: currentPlatform.isValid }">
            {{ currentPlatform.isValid ? '凭证有效' : '凭证失效' }}
          </text>
        </view>
        <button class="btn-text" @click="rebindAccount">重新绑定</button>
      </view>
    </view>

    <!-- 发布设置 -->
    <view class="section" v-if="currentPlatform?.bound">
      <view class="section-title">发布设置</view>

      <view class="form-item">
        <view class="form-label">{{ isAudioPublish ? '音频标题' : '视频标题' }} *</view>
        <input
          class="input-field"
          v-model="publishTitle"
          :placeholder="'为 ' + (isAudioPublish ? (audioInfo?.title || '音频') : (videoInfo?.title || '视频')) + ' 设置标题'"
          maxlength="100"
        />
      </view>

      <view class="form-item">
        <view class="form-label">{{ isAudioPublish ? '音频描述' : '视频描述' }}</view>
        <textarea
          class="input-area"
          v-model="publishDesc"
          :placeholder="isAudioPublish ? '添加音频描述，让更多人听到你的作品' : '添加视频描述，让更多人看到你的作品'"
          maxlength="500"
          :adjust-position="true"
        ></textarea>
      </view>

      <view class="form-item">
        <view class="form-label">话题标签</view>
        <view class="tags-input">
          <view class="tag-list">
            <view
              v-for="(tag, i) in publishTags"
              :key="i"
              class="tag-item"
            >
              <text>#</text>{{ tag }}
              <text class="tag-remove" @click="removeTag(i)">×</text>
            </view>
          </view>
          <input
            class="tag-input"
            v-model="tagInput"
            placeholder="输入标签后回车添加"
            @confirm="addTag"
          />
        </view>
      </view>

      <!-- 推荐标签 -->
      <view class="recommended-tags">
        <text class="rec-label">推荐：</text>
        <view
          v-for="tag in recommendedTags"
          :key="tag"
          class="rec-tag"
          @click="addRecommendedTag(tag)"
        ># {{ tag }}</view>
      </view>
    </view>

    <!-- 发布按钮 -->
    <view class="publish-footer" v-if="currentPlatform?.bound">
      <button
        class="btn-publish"
        @click="handlePublish"
        :disabled="publishing || !selectedPlatform"
      >
        <text v-if="publishing">发布中...</text>
        <text v-else>发布到 {{ currentPlatform?.name }}</text>
      </button>
    </view>

    <!-- 结果弹窗 -->
    <view class="result-modal" v-if="showResult">
      <view class="modal-mask" @click="showResult = false"></view>
      <view class="modal-content">
        <text class="modal-icon">{{ resultSuccess ? '✅' : '❌' }}</text>
        <text class="modal-title">{{ resultSuccess ? '发布成功' : '发布失败' }}</text>
        <text class="modal-message">{{ resultMessage }}</text>
        <view class="modal-actions">
          <button class="btn-secondary" @click="showResult = false">关闭</button>
          <button class="btn-primary" v-if="resultSuccess" @click="openResult">查看作品</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import {
  getPlatformAccounts,
  bindPlatformAccount,
  getVideoPublishPreview,
  createAndPublishTask,
  type PlatformAccount,
  type VideoPreview,
} from '@/utils/publish-api';
import { getFullUrl, get } from '@/utils/request';
import { useAudioStore } from '@/store/audio';

const audioStore = useAudioStore();
const isH5 = typeof window !== 'undefined' && (window as any).__uniConfig?.platform === 'h5';

// 平台类型定义
interface PlatformItem {
  id: string;
  name: string;
  icon: string;
  tip: string;
  bound: boolean;
  avatar: string;
  isValid: boolean;
  nickname?: string;
}

// 音频平台配置
const audioPlatforms = ref<PlatformItem[]>([
  {
    id: 'ximalaya' as const,
    name: '喜马拉雅',
    icon: '🎧',
    tip: '在喜马拉雅创作者平台登录后，复制浏览器 Cookie',
    bound: false,
    avatar: '',
    isValid: false,
  },
  {
    id: 'qingting' as const,
    name: '蜻蜓FM',
    icon: '📻',
    tip: '在蜻蜓FM创作者中心登录后，复制 Cookie',
    bound: false,
    avatar: '',
    isValid: false,
  },
  {
    id: 'lizhi' as const,
    name: '荔枝FM',
    icon: '🎤',
    tip: '在荔枝创作者中心登录后，复制 Cookie',
    bound: false,
    avatar: '',
    isValid: false,
  },
  {
    id: 'lanren' as const,
    name: '懒人听书',
    icon: '📚',
    tip: '在懒人听书创作者平台登录后，复制 Cookie',
    bound: false,
    avatar: '',
    isValid: false,
  },
  {
    id: 'netease_music' as const,
    name: '网易云音乐',
    icon: '🎵',
    tip: '在网易云音乐创作者中心登录后，复制 Cookie',
    bound: false,
    avatar: '',
    isValid: false,
  },
  {
    id: 'qq_music' as const,
    name: 'QQ音乐',
    icon: '🎶',
    tip: '在QQ音乐创作者平台登录后，复制 Cookie',
    bound: false,
    avatar: '',
    isValid: false,
  },
  {
    id: 'podcast' as const,
    name: '小宇宙',
    icon: '🎙️',
    tip: '在小宇宙创作者中心登录后，复制 Cookie',
    bound: false,
    avatar: '',
    isValid: false,
  },
  {
    id: 'wechat_audio' as const,
    name: '微信听书',
    icon: '📱',
    tip: '在微信听书创作者平台登录后，复制 Cookie',
    bound: false,
    avatar: '',
    isValid: false,
  },
]);

// 视频平台配置
const videoPlatforms = ref<PlatformItem[]>([
  {
    id: 'douyin' as const,
    name: '抖音',
    icon: '🎵',
    tip: '在抖音创作者平台登录后，复制浏览器 Cookie',
    bound: false,
    avatar: '',
    isValid: false,
  },
  {
    id: 'bilibili' as const,
    name: 'B站',
    icon: '📺',
    tip: '在B站开放平台授权后，复制 Access Token',
    bound: false,
    avatar: '',
    isValid: false,
  },
  {
    id: 'kuaishou' as const,
    name: '快手',
    icon: '📱',
    tip: '在快手创作者中心登录后，复制 Cookie',
    bound: false,
    avatar: '',
    isValid: false,
  },
  {
    id: 'xiaohongshu' as const,
    name: '小红书',
    icon: '📕',
    tip: '在小红书创作者中心登录后，复制 Cookie',
    bound: false,
    avatar: '',
    isValid: false,
  },
  {
    id: 'shipinhao' as const,
    name: '微信视频号',
    icon: '💬',
    tip: '在微信视频号创作者中心登录后，复制 Cookie',
    bound: false,
    avatar: '',
    isValid: false,
  },
  {
    id: 'xigua' as const,
    name: '西瓜视频',
    icon: '🍉',
    tip: '在西瓜视频创作者中心登录后，复制 Cookie',
    bound: false,
    avatar: '',
    isValid: false,
  },
  {
    id: 'youku' as const,
    name: '优酷',
    icon: '🎬',
    tip: '在优酷创作者中心登录后，复制 Cookie',
    bound: false,
    avatar: '',
    isValid: false,
  },
  {
    id: 'iqiyi' as const,
    name: '爱奇艺',
    icon: '🎥',
    tip: '在爱奇艺创作者中心登录后，复制 Cookie',
    bound: false,
    avatar: '',
    isValid: false,
  },
  {
    id: 'tencent_video' as const,
    name: '腾讯视频',
    icon: '📹',
    tip: '在腾讯视频创作者平台登录后，复制 Cookie',
    bound: false,
    avatar: '',
    isValid: false,
  },
  {
    id: 'zhihu' as const,
    name: '知乎视频',
    icon: '💡',
    tip: '在知乎创作者中心登录后，复制 Cookie',
    bound: false,
    avatar: '',
    isValid: false,
  },
  {
    id: 'weibo' as const,
    name: '微博视频',
    icon: '🔥',
    tip: '在微博创作者中心登录后，复制 Cookie',
    bound: false,
    avatar: '',
    isValid: false,
  },
]);

const platforms = ref<PlatformItem[]>([...videoPlatforms.value]);
const isAudioPublish = ref(false);
const audioId = ref<string>('');
const audioInfo = ref<any>(null);
const selectedPlatform = ref<string | null>(null);
const videoInfo = ref<VideoPreview | null>(null);
const projectId = ref<number>(0);
const videoUrl = ref<string>(''); // 直接使用视频URL发布
const publishing = ref(false);

// 发布表单
const publishTitle = ref('');
const publishDesc = ref('');
const publishTags = ref<string[]>([]);
const tagInput = ref('');

// 手动绑定
const manualCookie = ref('');
const manualUA = ref('');

// 结果弹窗
const showResult = ref(false);
const resultSuccess = ref(false);
const resultMessage = ref('');
const resultUrl = ref('');

const displayPlatforms = computed(() => {
  return isAudioPublish.value ? audioPlatforms.value : videoPlatforms.value;
});

const platformConfig: Record<string, string[]> = {
  // 音频平台
  ximalaya: ['有声书', '朗读', 'AI配音', '读书分享', '知识分享', '小说'],
  qingting: ['有声书', '配音', '朗读', '分享', '故事'],
  lizhi: ['播客', '有声书', '音乐', '情感', '直播'],
  lanren: ['有声书', '评书', '相声', '小说', '儿童故事'],
  netease_music: ['音乐', '翻唱', '原创', '有声书', '电台'],
  qq_music: ['音乐', '有声书', '电台', '播客', '翻唱'],
  podcast: ['播客', '访谈', '知识分享', '故事', '评论'],
  wechat_audio: ['有声书', '阅读', '知识', '文学', '教育'],
  // 视频平台
  douyin: ['有声书', '朗读', 'AI配音', '读书分享', '知识分享'],
  bilibili: ['有声书', 'ASMR', '读书', '配音', '知识区'],
  kuaishou: ['有声书', '配音', '朗读', '分享'],
  xiaohongshu: ['读书推荐', '知识分享', '学习', '成长', '生活方式'],
  shipinhao: ['知识分享', '读书', '教育', '文化', '生活'],
  xigua: ['影视解说', '知识', '读书', '纪录片', '生活'],
  youku: ['影视', '纪录片', '知识', '教育', '娱乐'],
  iqiyi: ['影视', '综艺', '知识', '教育', '动漫'],
  tencent_video: ['影视', '纪录片', '知识', '动漫', '娱乐'],
  zhihu: ['知识分享', '科普', '读书', '观点', '经验'],
  weibo: ['热点', '读书', '知识', '娱乐', '生活'],
};

const recommendedTags = computed(() => {
  if (!selectedPlatform.value) return [];
  return platformConfig[selectedPlatform.value] || [];
});

const currentPlatform = computed(() =>
  displayPlatforms.value.find((p) => p.id === selectedPlatform.value)
);

const fullVideoUrl = computed(() => {
  if (!videoInfo.value?.videoUrl) return '';
  return getFullUrl(videoInfo.value.videoUrl);
});

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

function selectPlatform(p: PlatformItem) {
  // 直接选中平台，无论是否绑定
  selectedPlatform.value = p.id;
  
  // 如果未绑定，提示用户绑定
  if (!p.bound) {
    uni.showToast({ 
      title: '请先绑定账号', 
      icon: 'none',
      duration: 1500
    });
  }
}

function rebindAccount() {
  if (!selectedPlatform.value) return;
  const p = platforms.value.find((x) => x.id === selectedPlatform.value);
  if (p) {
    p.bound = false;
    manualCookie.value = '';
    manualUA.value = '';
  }
}

function showCookieHelp() {
  const platformName = currentPlatform.value?.name || '该平台';
  
  uni.showModal({
    title: `${platformName} Cookie 获取方法`,
    content: `方法一（推荐）：
1. 点击"打开${platformName}登录页面"
2. 登录成功后，按 F12
3. 切换到 Console 标签
4. 输入: copy(document.cookie)
5. 回到本页按 Ctrl+V 粘贴

方法二：
1. 登录${platformName}
2. 按 F12 → Application → Cookies
3. 右键复制所有 Cookie
4. 粘贴到上方输入框

提示：Cookie 有效期约7-30天`,
    showCancel: false,
    confirmText: '我知道了'
  });
}

function openLoginWebView() {
  if (!selectedPlatform.value) {
    uni.showToast({ title: '请先选择平台', icon: 'none' });
    return;
  }
  
  const urls: Record<string, string> = {
    // 音频平台
    ximalaya: 'https://www.ximalaya.com/revision/main',
    qingting: 'https://www.qtfm.cn/',
    lizhi: 'https://www.lizhi.fm/',
    lanren: 'https://www.lrts.me/',
    netease_music: 'https://music.163.com/',
    qq_music: 'https://y.qq.com/',
    podcast: 'https://www.xiaoyuzhoufm.com/',
    wechat_audio: 'https://weread.qq.com/',
    // 视频平台
    douyin: 'https://creator.douyin.com/',
    bilibili: 'https://openhome.bilibili.com/',
    kuaishou: 'https://cp.kuaishou.com/',
    xiaohongshu: 'https://creator.xiaohongshu.com/',
    shipinhao: 'https://channels.weixin.qq.com/',
    xigua: 'https://studio.ixigua.com/',
    youku: 'https://creator.youku.com/',
    iqiyi: 'https://mp.iqiyi.com/',
    tencent_video: 'https://om.qq.com/',
    zhihu: 'https://www.zhihu.com/',
    weibo: 'https://weibo.com/',
  };
  
  const url = urls[selectedPlatform.value];
  if (!url) {
    uni.showToast({ title: '暂不支持该平台', icon: 'none' });
    return;
  }
  
  // #ifdef H5
  // H5 环境下打开新窗口
  window.open(url, '_blank', 'width=1200,height=800');
  
  // 显示获取Cookie的指引
  uni.showModal({
    title: '如何获取 Cookie',
    content: '1. 在新窗口登录平台账号\n2. 按F12打开开发者工具\n3. 切换到Console标签\n4. 输入: copy(document.cookie)\n5. 回到本页粘贴Cookie',
    showCancel: false,
    confirmText: '我知道了'
  });
  // #endif
  
  // #ifndef H5
  // App 端使用 WebView
  uni.navigateTo({
    url: `/pages/webview/index?url=${encodeURIComponent(url)}&platform=${selectedPlatform.value}`
  });
  // #endif
}

async function bindAccount() {
  if (!selectedPlatform.value || !manualCookie.value) return;

  uni.showLoading({ title: '绑定中...' });
  try {
    const result = await bindPlatformAccount({
      platform: selectedPlatform.value as any,
      cookies: manualCookie.value,
      headers: manualUA.value ? { 'User-Agent': manualUA.value } : undefined,
    });

    const p = platforms.value.find((x) => x.id === selectedPlatform.value);
    if (p) {
      p.bound = true;
      (p as any).nickname = result.nickname || '已绑定';
    }

    uni.hideLoading();
    uni.showToast({ title: '绑定成功', icon: 'success' });
  } catch (err: any) {
    uni.hideLoading();
    uni.showToast({ title: err.message || '绑定失败', icon: 'none' });
  }
}

function addTag() {
  const tag = tagInput.value.trim().replace(/^#/, '');
  if (tag && !publishTags.value.includes(tag)) {
    publishTags.value.push(tag);
  }
  tagInput.value = '';
}

function addRecommendedTag(tag: string) {
  if (!publishTags.value.includes(tag)) {
    publishTags.value.push(tag);
  }
}

function removeTag(index: number) {
  publishTags.value.splice(index, 1);
}

async function handlePublish() {
  if (!selectedPlatform.value) return;

  if (!publishTitle.value.trim()) {
    uni.showToast({ title: `请输入${isAudioPublish.value ? '音频' : '视频'}标题`, icon: 'none' });
    return;
  }

  publishing.value = true;
  uni.showLoading({ title: '发布中...' });

  try {
    if (isAudioPublish.value) {
      // TODO: 调用音频发布 API
      uni.hideLoading();
      publishing.value = false;
      uni.showToast({ 
        title: '音频发布功能开发中', 
        icon: 'none',
        duration: 2000
      });
      return;
    } else {
      // 视频发布
      // 支持两种方式：projectId 或 videoUrl
      if (!projectId.value && !videoUrl.value) {
        uni.hideLoading();
        publishing.value = false;
        uni.showToast({ title: '视频信息无效', icon: 'none' });
        return;
      }

      const publishData: any = {
        platform: selectedPlatform.value as any,
        title: publishTitle.value,
        description: publishDesc.value,
        tags: publishTags.value,
      };

      // 如果有 projectId 则使用 projectId，否则使用 videoUrl
      if (projectId.value) {
        publishData.videoProjectId = projectId.value;
      } else {
        publishData.videoUrl = videoUrl.value;
      }

      const result = await createAndPublishTask(publishData);

      uni.hideLoading();

      if (result.success) {
        resultSuccess.value = true;
        resultMessage.value = `视频已成功发布到 ${currentPlatform.value?.name}！`;
        resultUrl.value = result.publishedUrl || '';
      } else {
        resultSuccess.value = false;
        resultMessage.value = result.error || '发布失败，请稍后重试';
      }
      showResult.value = true;
    }
  } catch (err: any) {
    uni.hideLoading();
    publishing.value = false;
    uni.showToast({ title: err.message || '发布失败', icon: 'none' });
  }
}

function openResult() {
  showResult.value = false;
  if (resultUrl.value) {
    // #ifdef H5
    window.open(resultUrl.value, '_blank');
    // #endif
    // #ifndef H5
    uni.setClipboardData({ data: resultUrl.value });
    uni.showToast({ title: '链接已复制', icon: 'success' });
    // #endif
  }
}

function formatDuration(seconds: number): string {
  if (!seconds) return '--:--';
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins}:${secs.toString().padStart(2, '0')}`;
}

onLoad(async (query: any) => {
  // 判断是音频还是视频发布
  if (query?.audioId) {
    isAudioPublish.value = true;
    audioId.value = query.audioId;
    
    // 加载音频信息
    try {
      // 从后端获取音频详情
      const audioData = await get<any>(`/history/${audioId.value}`);
      if (audioData) {
        audioInfo.value = audioData;
        publishTitle.value = audioData.title || '音频';
        publishDesc.value = audioData.text?.substring(0, 200) || '';
      }
    } catch (e) {
      console.error('加载音频信息失败', e);
      // 如果获取失败，使用默认值
      audioInfo.value = {
        _id: audioId.value,
        title: '音频',
        wordCount: 0,
        audioDuration: 0,
        text: ''
      };
      publishTitle.value = '音频';
      publishDesc.value = '';
    }
  } else if (query?.videoUrl) {
    // 直接使用视频URL发布（来自书籍章节）
    isAudioPublish.value = false;
    // uni.navigateTo 已自动解码，不需要再 decodeURIComponent
    videoUrl.value = query.videoUrl;
    publishTitle.value = query.title || '视频';
    publishDesc.value = '';
    console.log('[Publish] 使用视频URL发布:', videoUrl.value);
  } else if (query?.projectId) {
    projectId.value = Number(query.projectId);

    // 加载视频预览信息
    try {
      videoInfo.value = await getVideoPublishPreview(projectId.value);
      publishTitle.value = videoInfo.value.title || '';
      publishDesc.value = videoInfo.value.description || '';
    } catch (e) {
      console.error('加载视频信息失败', e);
    }
  }

  // 加载已绑定的平台账号
  try {
    const accounts = await getPlatformAccounts();
    const allPlatforms = [...audioPlatforms.value, ...videoPlatforms.value];
    
    accounts.forEach((acc) => {
      const p = allPlatforms.find((x) => x.id === acc.platform);
      if (p) {
        p.bound = true;
        (p as any).nickname = acc.nickname;
        p.avatar = acc.avatar;
        p.isValid = acc.isValid;
      }
    });

    // 默认选中第一个已绑定的平台
    const currentPlatforms = isAudioPublish.value ? audioPlatforms.value : videoPlatforms.value;
    const firstBound = currentPlatforms.find((p) => p.bound);
    if (firstBound) {
      selectedPlatform.value = firstBound.id;
    }
  } catch (e: any) {
    console.error('加载平台账号失败', e);
    // 如果是401错误，提示用户登录
    if (e.message && (e.message.includes('登录') || e.message.includes('401'))) {
      uni.showToast({
        title: '请先登录后再使用发布功能',
        icon: 'none',
        duration: 3000
      });
    }
  }
});

let initialLoadDone = false;
onShow(() => {
  // H5 环境下 onLoad 可能不会再次触发，但页面需要刷新数据
  // 只有当有数据时才能刷新
  if (initialLoadDone && (audioId.value || projectId.value)) {
    // 重新加载页面数据
    if (audioId.value) {
      get<any>(`/history/${audioId.value}`).then(audioData => {
        if (audioData) {
          audioInfo.value = audioData;
          publishTitle.value = audioData.title || '音频';
          publishDesc.value = audioData.text?.substring(0, 200) || '';
        }
      }).catch(console.error);
    }
    if (projectId.value) {
      getVideoPublishPreview(projectId.value).then(videoInfo => {
        if (videoInfo) {
          videoInfo.value = videoInfo;
          publishTitle.value = videoInfo.title || '';
          publishDesc.value = videoInfo.description || '';
        }
      }).catch(console.error);
    }
  }
  initialLoadDone = true;
});
</script>

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

.nav-bar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px 15px;
}
.nav-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.nav-left { width: 40px; }
.back-icon { font-size: 24px; color: white; }
.page-title { font-size: 18px; font-weight: 600; color: white; }

/* 视频预览 */
.video-preview { padding: 10px 15px; background: #000; }
.video-player { width: 100%; border-radius: 8px; max-height: 220px; }

/* 音频预览 */
.audio-preview {
  margin: 15px;
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
}
.audio-cover-large {
  width: 80px;
  height: 80px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}
.audio-icon-large {
  font-size: 40px;
  opacity: 0.8;
}
.audio-info-large {
  flex: 1;
}
.audio-title-large {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  display: block;
  margin-bottom: 8px;
}
.audio-meta-large {
  font-size: 13px;
  color: #666;
}

/* 通用区块 */
.section {
  margin: 15px;
  background: white;
  border-radius: 12px;
  padding: 16px;
}
.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

/* 平台选择 */
.platform-grid {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}
.platform-item {
  flex: 1;
  min-width: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px 8px;
  border-radius: 10px;
  border: 2px solid #eee;
  background: #fafafa;
  cursor: pointer;
  transition: all 0.2s;
  user-select: none;
}
.platform-item:active {
  transform: scale(0.98);
}
.platform-item.active {
  border-color: #667eea;
  background: #f0f1ff;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}
.platform-item.not-bound {
  border-style: dashed;
  border-color: #d1d5db;
}
.platform-item.not-bound:active {
  border-color: #667eea;
  background: #f0f1ff;
}
.platform-icon { font-size: 32px; margin-bottom: 6px; }
.platform-name { font-size: 14px; font-weight: 500; color: #333; }
.platform-status {
  font-size: 11px;
  margin-top: 4px;
  padding: 2px 8px;
  border-radius: 10px;
}
.platform-status.status-bound {
  color: #059669;
  background: rgba(5, 150, 105, 0.1);
}
.platform-status.status-not-bound {
  color: #667eea;
  background: rgba(102, 126, 234, 0.1);
}

/* 平台提示 */
.platform-hint {
  margin-top: 12px;
  padding: 10px 12px;
  background: #f9fafb;
  border-radius: 8px;
  font-size: 12px;
  color: #6b7280;
  line-height: 1.5;
}

/* 绑定区域 */
.login-btn {
  margin: 16px 0;
}

/* 分隔线 */
.divider {
  display: flex;
  align-items: center;
  margin: 16px 0;
}
.divider::before,
.divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background: #e5e7eb;
}
.divider-text {
  padding: 0 12px;
  font-size: 13px;
  color: #9ca3af;
}

.bind-tips {
  background: #fff8e6;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
  display: flex;
  align-items: flex-start;
  gap: 8px;
}
.tip-icon { font-size: 16px; }
.tip-text { font-size: 13px; color: #666; line-height: 1.5; }

/* 表单 */
.form-item { margin-bottom: 14px; }
.form-label { font-size: 14px; color: #333; margin-bottom: 6px; font-weight: 500; }
.input-field {
  width: 100%;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 10px 12px;
  font-size: 14px;
  background: #fafafa;
  box-sizing: border-box;
}
.input-area {
  width: 100%;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 10px 12px;
  font-size: 14px;
  background: #fafafa;
  box-sizing: border-box;
  min-height: 80px;
  resize: none;
}

/* Cookie 输入 */
.cookie-input { margin-bottom: 12px; }
.input-label-row { 
  display: flex; 
  justify-content: space-between; 
  align-items: center; 
  margin-bottom: 4px; 
}
.input-label { font-size: 13px; color: #666; }
.help-btn {
  font-size: 12px;
  color: #667eea;
  background: none;
  border: none;
  padding: 0;
  margin: 0;
  line-height: 1;
}

/* 账号卡片 */
.account-card {
  display: flex;
  align-items: center;
  padding: 12px;
  background: #f9f9f9;
  border-radius: 10px;
}
.account-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: #ddd;
  margin-right: 12px;
}
.account-info { flex: 1; }
.account-name { font-size: 15px; font-weight: 500; color: #333; display: block; }
.account-valid { font-size: 12px; color: #999; }
.account-valid.valid { color: #67c23a; }

/* 标签 */
.tags-input { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
.tag-list { display: flex; flex-wrap: wrap; gap: 6px; width: 100%; }
.tag-item {
  background: #667eea;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}
.tag-remove { cursor: pointer; font-size: 14px; line-height: 1; }
.tag-input {
  flex: 1;
  min-width: 120px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  padding: 6px 10px;
  font-size: 13px;
  background: #fafafa;
}

.recommended-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
  align-items: center;
}
.rec-label { font-size: 12px; color: #999; }
.rec-tag {
  background: #f0f0f0;
  color: #666;
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 12px;
  cursor: pointer;
}

/* 底部发布按钮 */
.publish-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px;
  background: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}
.btn-publish {
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 25px;
  padding: 14px;
  font-size: 16px;
  font-weight: 600;
}
.btn-publish[disabled] {
  opacity: 0.6;
}

/* 通用按钮 */
.btn-primary {
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 10px;
  padding: 12px;
  font-size: 15px;
  font-weight: 500;
  margin-top: 12px;
}
.btn-primary[disabled] {
  opacity: 0.5;
}
.btn-secondary {
  background: #f0f0f0;
  color: #666;
  border: none;
  border-radius: 10px;
  padding: 12px 24px;
  font-size: 15px;
}
.btn-text {
  background: none;
  border: none;
  color: #667eea;
  font-size: 14px;
  padding: 4px 8px;
}

/* 结果弹窗 */
.result-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}
.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
}
.modal-content {
  position: relative;
  background: white;
  border-radius: 16px;
  padding: 30px 24px;
  width: 80%;
  max-width: 320px;
  text-align: center;
}
.modal-icon { font-size: 48px; display: block; margin-bottom: 12px; }
.modal-title { font-size: 18px; font-weight: 600; color: #333; display: block; margin-bottom: 8px; }
.modal-message { font-size: 14px; color: #666; display: block; margin-bottom: 20px; line-height: 1.5; }
.modal-actions { display: flex; gap: 12px; justify-content: center; }
</style>
