<template>
  <div class="system-settings">
    <n-card title="品牌自定义设置" :bordered="false">
      <n-form
        ref="formRef"
        :model="formData"
        label-placement="left"
        label-width="120"
        require-mark-placement="right-hanging"
      >
        <!-- 品牌名称 -->
        <n-form-item label="品牌名称" path="brandName">
          <n-input
            v-model:value="formData.brandName"
            placeholder="请输入品牌名称"
            maxlength="20"
            show-count
            clearable
          >
            <template #prefix>
              <n-icon><Text /></n-icon>
            </template>
          </n-input>
        </n-form-item>

        <!-- Logo URL -->
        <n-form-item label="Logo URL" path="brandLogo">
          <n-input
            v-model:value="formData.brandLogo"
            placeholder="请输入Logo图片URL或本地路径"
            clearable
          >
            <template #prefix>
              <n-icon><Image /></n-icon>
            </template>
          </n-input>
        </n-form-item>

        <!-- Logo预览 -->
        <n-form-item label="Logo预览">
          <div class="logo-preview">
            <div class="preview-box">
              <img
                :src="formData.brandLogo || '/icons/xiaoyugan.png'"
                :alt="formData.brandName"
                class="preview-image"
                @error="handlePreviewError"
              >
            </div>
            <n-text depth="3" style="font-size: 12px;">
              建议尺寸: 32x32 或更大的正方形图片
            </n-text>
          </div>
        </n-form-item>

        <!-- 图片上传 -->
        <n-form-item label="上传Logo">
          <n-upload
            :max="1"
            accept="image/*"
            :custom-request="handleUpload"
            @before-upload="beforeUpload"
          >
            <n-button>
              <template #icon>
                <n-icon><CloudUpload /></n-icon>
              </template>
              选择图片
            </n-button>
          </n-upload>
          <n-text depth="3" style="font-size: 12px; margin-left: 12px;">
            或直接输入图片URL
          </n-text>
        </n-form-item>

        <!-- 预设Logo -->
        <n-form-item label="预设Logo">
          <div class="preset-logos">
            <div
              v-for="preset in presetLogos"
              :key="preset.path"
              class="preset-item"
              :class="{ active: formData.brandLogo === preset.path }"
              @click="selectPreset(preset)"
            >
              <img :src="preset.path" :alt="preset.name">
              <span>{{ preset.name }}</span>
            </div>
          </div>
        </n-form-item>

        <!-- 操作按钮 -->
        <n-form-item :show-label="false">
          <n-space>
            <n-button
              type="primary"
              @click="handleSave"
              :loading="saving"
            >
              <template #icon>
                <n-icon><Save /></n-icon>
              </template>
              保存设置
            </n-button>
            <n-button @click="handleReset">
              <template #icon>
                <n-icon><Refresh /></n-icon>
              </template>
              恢复默认
            </n-button>
            <n-button @click="handlePreview">
              <template #icon>
                <n-icon><Eye /></n-icon>
              </template>
              实时预览
            </n-button>
          </n-space>
        </n-form-item>
      </n-form>
    </n-card>

    <!-- 使用说明 -->
    <n-card title="使用说明" :bordered="false" style="margin-top: 16px;">
      <n-space vertical>
        <n-alert type="info" :show-icon="false">
          <template #header>
            <div style="display: flex; align-items: center; gap: 8px;">
              <n-icon size="20"><InformationCircle /></n-icon>
              <span>如何自定义品牌信息</span>
            </div>
          </template>
          <n-ul>
            <n-li>
              <strong>品牌名称：</strong>显示在导航栏左上角的文字，最多20个字符
            </n-li>
            <n-li>
              <strong>Logo URL：</strong>可以输入网络图片URL或本地路径（如 /icons/xxx.png）
            </n-li>
            <n-li>
              <strong>上传图片：</strong>选择本地图片后会自动转换为Base64格式存储
            </n-li>
            <n-li>
              <strong>预设Logo：</strong>点击下方预设图标快速应用
            </n-li>
            <n-li>
              <strong>实时预览：</strong>点击预览按钮立即在导航栏查看效果
            </n-li>
          </n-ul>
        </n-alert>
      </n-space>
    </n-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useMessage } from 'naive-ui'
import { useSystemSettingsStore } from '@/stores/systemSettings'
import {
  Text,
  Image,
  CloudUpload,
  Save,
  Refresh,
  Eye,
  InformationCircle
} from '@vicons/ionicons5'

const message = useMessage()
const systemSettings = useSystemSettingsStore()

// 表单数据
const formData = reactive({
  brandName: '',
  brandLogo: ''
})

// 预设Logo列表
const presetLogos = [
  { name: '小鱼竿', path: '/icons/xiaoyugan.png' },
  { name: '汽车', path: '/icons/car.jpg' },
  { name: '书籍', path: '/icons/book.jpg' },
  { name: '小塔', path: '/icons/ta.png' },
  { name: '图标1', path: '/icons/1733492491706148.png' },
  { name: '图标2', path: '/icons/1733492491706152.png' },
  { name: '图标3', path: '/icons/1736425783912140.png' },
  { name: '图标4', path: '/icons/173746572831736.png' }
]

const saving = ref(false)

// 加载当前设置
const loadSettings = () => {
  formData.brandName = systemSettings.brandName
  formData.brandLogo = systemSettings.brandLogo
}

// 选择预设Logo
const selectPreset = (preset) => {
  formData.brandLogo = preset.path
  message.success(`已选择 ${preset.name}`)
}

// 处理图片上传
const beforeUpload = (data) => {
  const file = data.file.file
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件！')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB！')
    return false
  }
  return true
}

const handleUpload = ({ file, onFinish, onError }) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    formData.brandLogo = e.target.result
    message.success('图片上传成功')
    onFinish()
  }
  reader.onerror = () => {
    message.error('图片读取失败')
    onError()
  }
  reader.readAsDataURL(file.file)
}

// 处理预览图片错误
const handlePreviewError = (e) => {
  e.target.src = '/icons/xiaoyugan.png'
}

// 保存设置
const handleSave = () => {
  if (!formData.brandName.trim()) {
    message.warning('请输入品牌名称')
    return
  }
  if (!formData.brandLogo.trim()) {
    message.warning('请设置Logo')
    return
  }
  
  saving.value = true
  setTimeout(() => {
    systemSettings.updateBrandName(formData.brandName)
    systemSettings.updateBrandLogo(formData.brandLogo)
    saving.value = false
    message.success('设置已保存')
  }, 500)
}

// 恢复默认
const handleReset = () => {
  systemSettings.resetToDefault()
  loadSettings()
  message.success('已恢复默认设置')
}

// 实时预览
const handlePreview = () => {
  systemSettings.updateBrandName(formData.brandName)
  systemSettings.updateBrandLogo(formData.brandLogo)
  message.success('预览效果已应用，请查看导航栏')
}

// 初始化
onMounted(() => {
  loadSettings()
})
</script>

<style scoped lang="scss">
.system-settings {
  max-width: 800px;
  margin: 0 auto;
}

.logo-preview {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.preview-box {
  width: 80px;
  height: 80px;
  border: 2px dashed var(--border-color, #e0e0e0);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--bg-tertiary, #f5f5f5);
  transition: all 0.3s ease;

  [data-theme="dark"] &,
  html.dark & {
    background: rgba(255, 255, 255, 0.05);
    border-color: rgba(255, 255, 255, 0.2);
  }

  &:hover {
    border-color: var(--primary-color, #18a058);
    background: var(--bg-secondary, #fafafa);

    [data-theme="dark"] &,
    html.dark & {
      background: rgba(255, 255, 255, 0.1);
    }
  }
}

.preview-image {
  width: 64px;
  height: 64px;
  object-fit: contain;
  border-radius: 8px;
}

.preset-logos {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 12px;
  width: 100%;
}

.preset-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 12px;
  border: 2px solid var(--border-color, #e0e0e0);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: var(--bg-primary, #ffffff);

  [data-theme="dark"] &,
  html.dark & {
    background: rgba(255, 255, 255, 0.05);
    border-color: rgba(255, 255, 255, 0.2);
  }

  img {
    width: 48px;
    height: 48px;
    object-fit: contain;
    border-radius: 8px;
  }

  span {
    font-size: 12px;
    color: var(--text-secondary, #666);
    text-align: center;

    [data-theme="dark"] &,
    html.dark & {
      color: rgba(255, 255, 255, 0.7);
    }
  }

  &:hover {
    border-color: var(--primary-color, #18a058);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

    [data-theme="dark"] &,
    html.dark & {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    }
  }

  &.active {
    border-color: var(--primary-color, #18a058);
    background: rgba(24, 160, 88, 0.1);

    [data-theme="dark"] &,
    html.dark & {
      background: rgba(24, 160, 88, 0.2);
    }

    span {
      color: var(--primary-color, #18a058);
      font-weight: 600;
    }
  }
}

:deep(.n-card__content) {
  padding-top: 16px;
}

:deep(.n-form-item) {
  margin-bottom: 24px;
}

:deep(.n-alert) {
  border-radius: 12px;
}

:deep(.n-ul) {
  margin-top: 12px;
}

:deep(.n-li) {
  margin-bottom: 8px;
  color: var(--text-secondary);

  [data-theme="dark"] &,
  html.dark & {
    color: rgba(255, 255, 255, 0.8);
  }
}
</style>

