<template>
  <view class="page">
    <!-- 顶部导航 -->
    <view class="nav-bar">
      <view class="nav-btn" @click="goBack">
        <text class="nav-icon">←</text>
      </view>
      <text class="nav-title">设置</text>
      <view class="nav-btn" />
    </view>

    <!-- 设置列表 -->
    <scroll-view scroll-y class="settings-list" :scroll-top="scrollTop">
      <!-- 播放设置 -->
      <view class="settings-section">
        <text class="section-title">播放</text>

        <!-- 默认音色 -->
        <view class="settings-item" @click="showVoicePicker = true">
          <text class="item-icon">🎤</text>
          <text class="item-text">默认音色</text>
          <view class="item-value">
            <text class="value-text">{{ getVoiceLabel(preferences.defaultVoiceId) }}</text>
            <text class="item-arrow">›</text>
          </view>
        </view>

        <!-- 默认音量 -->
        <view class="settings-item">
          <text class="item-icon">🔊</text>
          <text class="item-text">默认音量</text>
          <view class="item-value">
            <text class="value-text">{{ preferences.defaultVolume }}%</text>
            <slider
              class="volume-slider"
              :value="preferences.defaultVolume"
              @change="onVolumeChange"
              min="0"
              max="100"
              step="5"
              activeColor="#4F46E5"
              backgroundColor="#E5E7EB"
              block-size="20"
            />
          </view>
        </view>

        <!-- 自动播放下一首 -->
        <view class="settings-item">
          <text class="item-icon">▶️</text>
          <text class="item-text">自动播放下一首</text>
          <switch
            :checked="preferences.autoPlayNext"
            @change="onAutoPlayChange"
            activeColor="#4F46E5"
          />
        </view>
      </view>

      <!-- 主题设置 -->
      <view class="settings-section">
        <text class="section-title">外观</text>
        <view class="settings-item" @click="showThemePicker = true">
          <text class="item-icon">🎨</text>
          <text class="item-text">主题</text>
          <view class="item-value">
            <text class="value-text">{{ themeLabels[theme] }}</text>
            <text class="item-arrow">›</text>
          </view>
        </view>
      </view>

      <!-- 下载设置 -->
      <view class="settings-section">
        <text class="section-title">下载</text>
        <view class="settings-item">
          <text class="item-icon">📶</text>
          <text class="item-text">仅WiFi下载</text>
          <switch
            :checked="preferences.wifiOnlyDownload"
            @change="onWifiOnlyChange"
            activeColor="#4F46E5"
          />
        </view>
      </view>

      <!-- 存储设置 -->
      <view class="settings-section">
        <text class="section-title">存储</text>
        <view class="settings-item" @click="handleClearCache">
          <text class="item-icon">🗑️</text>
          <text class="item-text">清理缓存</text>
          <view class="item-value">
            <text class="value-text">{{ cacheSize }}</text>
            <text class="item-arrow">›</text>
          </view>
        </view>
      </view>

      <!-- 关于 -->
      <view class="settings-section">
        <text class="section-title">关于</text>
        <view class="settings-item">
          <text class="item-icon">📌</text>
          <text class="item-text">版本</text>
          <view class="item-value">
            <text class="value-text">1.0.0</text>
          </view>
        </view>
      </view>

      <view class="bottom-padding" />
    </scroll-view>

    <!-- 主题选择弹窗 -->
    <view v-if="showThemePicker" class="picker-modal" @click="showThemePicker = false">
      <view class="picker-content" @click.stop>
        <text class="picker-title">选择主题</text>
        <view
          v-for="(label, key) in themeLabels"
          :key="key"
          class="picker-item"
          :class="{ active: theme === key }"
          @click="selectTheme(key)"
        >
          <text>{{ label }}</text>
          <text v-if="theme === key" class="check-icon">✓</text>
        </view>
      </view>
    </view>

    <!-- 音色选择弹窗 -->
    <view v-if="showVoicePicker" class="picker-modal" @click="showVoicePicker = false">
      <view class="picker-content" @click.stop>
        <text class="picker-title">选择默认音色</text>
        <scroll-view scroll-y class="voice-list" :scroll-top="scrollTop">
          <view
            v-for="voice in voiceOptions"
            :key="voice.id"
            class="picker-item"
            :class="{ active: preferences.defaultVoiceId === voice.id }"
            @click="selectVoice(voice.id)"
          >
            <view class="voice-info">
              <text class="voice-avatar">{{ voice.avatar }}</text>
              <view class="voice-detail">
                <text class="voice-name">{{ voice.name }}</text>
                <text class="voice-desc">{{ voice.desc }}</text>
              </view>
            </view>
            <text v-if="preferences.defaultVoiceId === voice.id" class="check-icon">✓</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

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

// scroll-top 用于避免 scrollTop 错误
const scrollTop = ref(0);

// 主题相关
const theme = ref('light');
const themeLabels: Record<string, string> = {
  light: '浅色',
  dark: '深色',
  auto: '跟随系统',
};
const showThemePicker = ref(false);

// 音色选项
const voiceOptions = [
  { id: 'cherry', name: '芊悦', avatar: '👩', desc: '温柔女声' },
  { id: 'ethan', name: '晨煦', avatar: '👨', desc: '沉稳男声' },
  { id: 'serena', name: '苏瑶', avatar: '👩', desc: '知性女声' },
  { id: 'chelsie', name: '千雪', avatar: '👩', desc: '清甜女声' },
  { id: 'momo', name: '茉兔', avatar: '👩', desc: '可爱女声' },
  { id: 'vivian', name: '十三', avatar: '👩', desc: '活泼女声' },
  { id: 'moon', name: '月白', avatar: '👨', desc: '温润男声' },
  { id: 'maia', name: '四月', avatar: '👩', desc: '温暖女声' },
  { id: 'kai', name: '凯', avatar: '👨', desc: '大气男声' },
  { id: 'nofish', name: '不吃鱼', avatar: '👨', desc: '磁性男声' },
];

// 用户偏好
interface Preferences {
  playSpeed: number;
  quality: string;
  theme: string;
  defaultVoiceId: string;
  defaultVolume: number;
  autoPlayNext: boolean;
  wifiOnlyDownload: boolean;
}

const preferences = ref<Preferences>({
  playSpeed: 1.0,
  quality: 'standard',
  theme: 'light',
  defaultVoiceId: 'cherry',
  defaultVolume: 50,
  autoPlayNext: true,
  wifiOnlyDownload: false,
});

const showVoicePicker = ref(false);
const cacheSize = ref('0 MB');

// 获取音色标签
function getVoiceLabel(voiceId: string): string {
  const voice = voiceOptions.find(v => v.id === voiceId);
  return voice?.name || voiceId;
}

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

// 选择主题
function selectTheme(key: string) {
  theme.value = key;
  uni.setStorageSync('theme', key);

  // 应用主题
  if (key === 'dark') {
    uni.setStorageSync('dark_mode', true);
  } else if (key === 'light') {
    uni.setStorageSync('dark_mode', false);
  } else {
    // auto - 跟随系统
    uni.removeStorageSync('dark_mode');
  }

  showThemePicker.value = false;
}

// 选择音色
async function selectVoice(voiceId: string) {
  preferences.value.defaultVoiceId = voiceId;
  await savePreferences();
  showVoicePicker.value = false;
}

// 音量变化
async function onVolumeChange(e: any) {
  preferences.value.defaultVolume = e.detail.value;
  await savePreferences();
}

// 自动播放变化
async function onAutoPlayChange(e: any) {
  preferences.value.autoPlayNext = e.detail.value;
  await savePreferences();
}

// 仅WiFi下载变化
async function onWifiOnlyChange(e: any) {
  preferences.value.wifiOnlyDownload = e.detail.value;
  await savePreferences();
}

// 保存偏好设置
async function savePreferences() {
  try {
    const result = await put<Preferences>('/user/preferences', {
      defaultVoiceId: preferences.value.defaultVoiceId,
      defaultVolume: preferences.value.defaultVolume,
      autoPlayNext: preferences.value.autoPlayNext,
      wifiOnlyDownload: preferences.value.wifiOnlyDownload,
    });
    if (result) {
      Object.assign(preferences.value, result);
    }
    // 同时保存到本地
    uni.setStorageSync('userPreferences', preferences.value);
  } catch (error) {
    console.error('保存偏好设置失败:', error);
  }
}

// 加载偏好设置
async function loadPreferences() {
  try {
    // 先尝试从本地加载
    const localPrefs = uni.getStorageSync('userPreferences');
    if (localPrefs) {
      Object.assign(preferences.value, localPrefs);
    }

    // 从服务器加载
    const result = await get<Preferences>('/user/preferences');
    if (result) {
      Object.assign(preferences.value, result);
      uni.setStorageSync('userPreferences', preferences.value);
    }
  } catch (error) {
    console.error('加载偏好设置失败:', error);
  }
}

// 清理缓存
function handleClearCache() {
  uni.showModal({
    title: '清理缓存',
    content: '确定要清理缓存吗？',
    success: (res) => {
      if (res.confirm) {
        uni.showLoading({ title: '清理中...' });

        // 延迟模拟清理
        setTimeout(() => {
          uni.hideLoading();
          uni.showToast({ title: '缓存已清理', icon: 'success' });
          cacheSize.value = '0 MB';
        }, 1000);
      }
    },
  });
}

// 初始化
onMounted(async () => {
  // 读取主题设置
  const savedTheme = uni.getStorageSync('theme');
  if (savedTheme) {
    theme.value = savedTheme;
  }

  // 加载偏好设置
  await loadPreferences();

  // 估算缓存大小（简化）
  try {
    const info = uni.getStorageInfoSync();
    if (info.currentSize < 1024) {
      cacheSize.value = `${info.currentSize} KB`;
    } else {
      cacheSize.value = `${(info.currentSize / 1024).toFixed(1)} MB`;
    }
  } catch (e) {
    cacheSize.value = '未知';
  }
});
</script>

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

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 88rpx;
  padding-top: env(safe-area-inset-top);
  padding-left: 32rpx;
  padding-right: 32rpx;
  background: #ffffff;
}

.nav-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-icon {
  font-size: 36rpx;
  color: #1f2937;
}

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

.settings-list {
  padding-top: calc(88rpx + env(safe-area-inset-top));
  padding-bottom: calc(100rpx + env(safe-area-inset-bottom));
  height: 100vh;
  box-sizing: border-box;
}

.settings-section {
  padding: 24rpx 32rpx;
  margin-bottom: 8rpx;
}

.section-title {
  font-size: 24rpx;
  color: #9ca3af;
  margin-bottom: 16rpx;
  display: block;
}

.settings-item {
  display: flex;
  align-items: center;
  padding: 28rpx 32rpx;
  background: #ffffff;
  border-radius: 16rpx;
  margin-bottom: 12rpx;
}

.item-icon {
  font-size: 36rpx;
  margin-right: 20rpx;
}

.item-text {
  flex: 1;
  font-size: 30rpx;
  color: #1f2937;
}

.item-value {
  display: flex;
  align-items: center;
}

.value-text {
  font-size: 28rpx;
  color: #9ca3af;
  margin-right: 8rpx;
}

.item-arrow {
  font-size: 32rpx;
  color: #d1d5db;
}

.volume-slider {
  width: 200rpx;
  margin-left: 16rpx;
}

.bottom-padding {
  height: 40rpx;
}

/* 选择弹窗 */
.picker-modal {
  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;
}

.picker-content {
  width: 100%;
  max-height: 70vh;
  background: #ffffff;
  border-radius: 32rpx 32rpx 0 0;
  padding: 40rpx 32rpx;
  padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
}

.picker-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #1f2937;
  text-align: center;
  display: block;
  margin-bottom: 32rpx;
}

.picker-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 28rpx 0;
  border-bottom: 1rpx solid #f3f4f6;
  font-size: 30rpx;
  color: #1f2937;
}

.picker-item:last-child {
  border-bottom: none;
}

.picker-item.active {
  color: #4f46e5;
}

.check-icon {
  color: #4f46e5;
  font-size: 32rpx;
}

/* 音色列表 */
.voice-list {
  max-height: 50vh;
}

.voice-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.voice-avatar {
  font-size: 48rpx;
  margin-right: 20rpx;
}

.voice-detail {
  display: flex;
  flex-direction: column;
}

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

.voice-desc {
  font-size: 24rpx;
  color: #9ca3af;
}
</style>
