<template>
  <div class="config-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>系统配置</span>
          <el-button type="primary" size="small" @click="refreshConfigs" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="外观配置" name="appearance">
          <el-form :model="appearanceConfig" label-width="140px" :rules="appearanceRules" ref="appearanceFormRef">
            <el-form-item label="应用Logo" prop="app_logo">
              <div class="upload-container">
                <el-upload
                  class="logo-uploader"
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="handleLogoSuccess"
                  :on-error="handleUploadError"
                  :before-upload="beforeUpload"
                  name="file">
                  <img v-if="appearanceConfig.app_logo" :src="getImageUrl(appearanceConfig.app_logo)" class="logo-preview" />
                  <div v-else class="upload-placeholder">
                    <el-icon class="upload-icon"><Plus /></el-icon>
                    <div class="upload-text">点击上传Logo</div>
                  </div>
                </el-upload>
                <div class="upload-info">
                  <div class="form-tip">建议尺寸: 200x200px</div>
                  <div class="form-tip">支持格式: PNG, JPG</div>
                  <div class="form-tip">文件大小: 最大5MB</div>
                  <el-button 
                    v-if="appearanceConfig.app_logo" 
                    type="danger" 
                    size="small" 
                    text
                    @click="clearLogo">
                    清除Logo
                  </el-button>
                </div>
              </div>
            </el-form-item>

            <el-form-item label="关于我们图片" prop="about_us_image">
              <div class="upload-container">
                <el-upload
                  class="about-uploader"
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="handleAboutSuccess"
                  :on-error="handleUploadError"
                  :before-upload="beforeUpload"
                  name="file">
                  <img v-if="appearanceConfig.about_us_image" :src="getImageUrl(appearanceConfig.about_us_image)" class="about-preview" />
                  <div v-else class="upload-placeholder">
                    <el-icon class="upload-icon"><Plus /></el-icon>
                    <div class="upload-text">点击上传图片</div>
                  </div>
                </el-upload>
                <div class="upload-info">
                  <div class="form-tip">建议尺寸: 750x400px</div>
                  <div class="form-tip">支持格式: PNG, JPG</div>
                  <div class="form-tip">文件大小: 最大5MB</div>
                  <el-button 
                    v-if="appearanceConfig.about_us_image" 
                    type="danger" 
                    size="small" 
                    text
                    @click="clearAboutImage">
                    清除图片
                  </el-button>
                </div>
              </div>
            </el-form-item>

            <el-form-item label="用户默认头像" prop="default_avatar">
              <div class="upload-container">
                <el-upload
                  class="avatar-uploader"
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="handleDefaultAvatarSuccess"
                  :on-error="handleUploadError"
                  :before-upload="beforeUpload"
                  name="file">
                  <img v-if="appearanceConfig.default_avatar" :src="getImageUrl(appearanceConfig.default_avatar)" class="avatar-preview" />
                  <div v-else class="upload-placeholder">
                    <el-icon class="upload-icon"><Plus /></el-icon>
                    <div class="upload-text">点击上传头像</div>
                  </div>
                </el-upload>
                <div class="upload-info">
                  <div class="form-tip">建议尺寸: 200x200px</div>
                  <div class="form-tip">支持格式: PNG, JPG</div>
                  <div class="form-tip">文件大小: 最大5MB</div>
                  <div class="form-tip">新用户注册时将使用此头像</div>
                  <el-button 
                    v-if="appearanceConfig.default_avatar" 
                    type="danger" 
                    size="small" 
                    text
                    @click="clearDefaultAvatar">
                    清除头像
                  </el-button>
                </div>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="saveAppearanceConfig" :loading="saving">
                <el-icon><Check /></el-icon>
                保存外观配置
              </el-button>
              <el-button @click="resetAppearanceConfig">
                <el-icon><RefreshLeft /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="基本信息" name="general">
          <el-form :model="generalConfig" label-width="140px" :rules="generalRules" ref="generalFormRef">
            <el-form-item label="应用名称" prop="app_name">
              <el-input 
                v-model="generalConfig.app_name" 
                placeholder="请输入应用名称"
                maxlength="50"
                show-word-limit
                clearable />
              <div class="form-tip">应用名称将显示在小程序标题栏和关于页面</div>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="saveGeneralConfig" :loading="saving">
                <el-icon><Check /></el-icon>
                保存基本信息
              </el-button>
              <el-button @click="resetGeneralConfig">
                <el-icon><RefreshLeft /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="协议管理" name="agreement">
          <el-form :model="agreementConfig" label-width="140px" ref="agreementFormRef">
            <el-form-item label="用户协议" prop="user_agreement">
              <el-input 
                v-model="agreementConfig.user_agreement" 
                type="textarea"
                :rows="12"
                placeholder="请输入用户协议内容，支持换行"
                maxlength="50000"
                show-word-limit />
              <div class="form-tip">用户协议将显示在小程序的用户协议页面</div>
            </el-form-item>

            <el-form-item label="隐私政策" prop="privacy_policy">
              <el-input 
                v-model="agreementConfig.privacy_policy" 
                type="textarea"
                :rows="12"
                placeholder="请输入隐私政策内容，支持换行"
                maxlength="50000"
                show-word-limit />
              <div class="form-tip">隐私政策将显示在小程序的隐私政策页面</div>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="saveAgreementConfig" :loading="saving">
                <el-icon><Check /></el-icon>
                保存协议配置
              </el-button>
              <el-button @click="resetAgreementConfig">
                <el-icon><RefreshLeft /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="联系方式" name="contact">
          <el-form :model="contactConfig" label-width="140px" :rules="contactRules" ref="contactFormRef">
            <el-form-item label="联系电话" prop="contact_phone">
              <el-input 
                v-model="contactConfig.contact_phone" 
                placeholder="请输入联系电话 (例: +86 13800138000)"
                maxlength="20"
                clearable>
                <template #prefix>
                  <el-icon><Phone /></el-icon>
                </template>
              </el-input>
              <div class="form-tip">用户可通过此电话联系客服</div>
            </el-form-item>

            <el-form-item label="联系邮箱" prop="contact_email">
              <el-input 
                v-model="contactConfig.contact_email" 
                placeholder="请输入联系邮箱 (例: contact@example.com)"
                maxlength="100"
                clearable>
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
              <div class="form-tip">用户可通过此邮箱联系客服</div>
            </el-form-item>

            <el-form-item label="联系我们二维码" prop="contact_qr_image">
              <div class="upload-container">
                <el-upload
                  class="qr-uploader"
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="handleQrSuccess"
                  :on-error="handleUploadError"
                  :before-upload="beforeUpload"
                  name="file">
                  <img v-if="contactConfig.contact_qr_image" :src="getImageUrl(contactConfig.contact_qr_image)" class="qr-preview" />
                  <div v-else class="upload-placeholder">
                    <el-icon class="upload-icon"><Plus /></el-icon>
                    <div class="upload-text">点击上传二维码</div>
                  </div>
                </el-upload>
                <div class="upload-info">
                  <div class="form-tip">建议尺寸: 300x300px</div>
                  <div class="form-tip">支持格式: PNG, JPG</div>
                  <div class="form-tip">文件大小: 最大5MB</div>
                  <div class="form-tip">此二维码将显示在"联系我们"页面</div>
                  <el-button 
                    v-if="contactConfig.contact_qr_image" 
                    type="danger" 
                    size="small" 
                    text
                    @click="clearQrImage">
                    清除二维码
                  </el-button>
                </div>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="saveContactConfig" :loading="saving">
                <el-icon><Check /></el-icon>
                保存联系方式
              </el-button>
              <el-button @click="resetContactConfig">
                <el-icon><RefreshLeft /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="邀请规则" name="invite">
          <el-form :model="inviteConfig" label-width="140px" ref="inviteFormRef">
            <el-form-item label="规则说明" prop="invite_rules">
              <el-input 
                v-model="inviteConfig.invite_rules" 
                type="textarea"
                :rows="12"
                placeholder="请输入邀请奖励规则说明，支持换行"
                maxlength="5000"
                show-word-limit />
              <div class="form-tip">此规则将显示在小程序的邀请奖励页面</div>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="saveInviteConfig" :loading="saving">
                <el-icon><Check /></el-icon>
                保存邀请规则
              </el-button>
              <el-button @click="resetInviteConfig">
                <el-icon><RefreshLeft /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="预约登记规则" name="booking_rules">
          <div class="booking-rules-container">
            <el-alert 
              title="为每个预约表单页面配置登记规则，规则将显示在小程序预约页面顶部" 
              type="info" 
              :closable="false"
              style="margin-bottom: 20px;" />
            
            <el-collapse v-model="activeBookingRules">
              <el-collapse-item 
                v-for="item in serviceTypeOptions" 
                :key="item.value" 
                :name="item.value"
                :title="item.label">
                <el-form label-width="100px">
                  <el-form-item label="规则说明">
                    <el-input 
                      v-model="bookingRulesConfig[item.value]" 
                      type="textarea"
                      :rows="6"
                      :placeholder="`请输入${item.label}的预约登记规则`"
                      maxlength="2000"
                      show-word-limit />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" size="small" @click="saveBookingRule(item.value)" :loading="savingRule === item.value">
                      保存此规则
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-collapse-item>
            </el-collapse>

            <div style="margin-top: 20px;">
              <el-button type="primary" @click="saveAllBookingRules" :loading="saving">
                <el-icon><Check /></el-icon>
                保存全部规则
              </el-button>
            </div>
          </div>
        </el-tab-pane>

      </el-tabs>
    </el-card>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Check, RefreshLeft, Phone, Message } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import api from '@/utils/api'

const authStore = useAuthStore()
const activeTab = ref('appearance')
const saving = ref(false)
const loading = ref(false)

// Form refs
const appearanceFormRef = ref(null)
const generalFormRef = ref(null)
const contactFormRef = ref(null)
const agreementFormRef = ref(null)
const inviteFormRef = ref(null)

// 预约登记规则相关
const activeBookingRules = ref([])
const savingRule = ref('')
const bookingRulesConfig = ref({})

// 服务类型选项
const serviceTypeOptions = [
  { value: 'flight', label: '全球机票代理' },
  { value: 'hotel', label: '全球酒店预定' },
  { value: 'lounge', label: '全球机场贵宾室服务' },
  { value: 'airport_transfer', label: '机场接/送机服务' },
  { value: 'unaccompanied_minor', label: '无成人陪伴儿童代办' },
  { value: 'train', label: '高铁票代订' },
  { value: 'telemedicine', label: '远程医疗问诊代理服务' },
  { value: 'special_passenger', label: '特殊（特护）旅客定制服务代办' },
  { value: 'pet_transport', label: '宠物托运代理' },
  { value: 'guide_translation', label: '西班牙语专业导游/翻译服务' },
  { value: 'visa', label: '签证咨询' },
  { value: 'exhibition', label: '墨西哥展会咨询与协办服务' },
  { value: 'air_logistics', label: '跨境航空物流/快递一站式服务' },
  { value: 'sea_freight', label: '海运/清关一站式服务' },
  { value: 'travel_planning', label: '旅游线路规划/咨询' },
  { value: 'insurance', label: '跨境出行意外保险/国际财产保险咨询' }
]

// Original configs for reset
const originalConfigs = reactive({
  appearance: {},
  general: {},
  contact: {},
  agreement: {},
  invite: {}
})

const appearanceConfig = ref({
  app_logo: '',
  about_us_image: '',
  default_avatar: ''
})

const generalConfig = ref({
  app_name: ''
})

const contactConfig = ref({
  contact_phone: '',
  contact_email: '',
  contact_qr_image: ''
})

const agreementConfig = ref({
  user_agreement: '',
  privacy_policy: ''
})

const inviteConfig = ref({
  invite_rules: ''
})

// Validation rules
const appearanceRules = {
  app_logo: [
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        // Allow both absolute URLs and relative paths
        if (value.startsWith('http://') || value.startsWith('https://') || value.startsWith('/')) {
          callback()
        } else {
          callback(new Error('请输入有效的URL地址或路径'))
        }
      }, 
      trigger: 'blur' 
    }
  ],
  about_us_image: [
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        // Allow both absolute URLs and relative paths
        if (value.startsWith('http://') || value.startsWith('https://') || value.startsWith('/')) {
          callback()
        } else {
          callback(new Error('请输入有效的URL地址或路径'))
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

const generalRules = {
  app_name: [
    { required: true, message: '请输入应用名称', trigger: 'blur' },
    { min: 2, max: 50, message: '应用名称长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

const contactRules = {
  contact_phone: [
    { pattern: /^[\d\s\+\-\(\)]+$/, message: '请输入有效的电话号码', trigger: 'blur' }
  ],
  contact_email: [
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  contact_qr_image: [
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        if (value.startsWith('http://') || value.startsWith('https://') || value.startsWith('/')) {
          callback()
        } else {
          callback(new Error('请输入有效的URL地址或路径'))
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 使用相对路径,让vite代理处理
const uploadUrl = ref('/api/v1/admin/upload/image')

// 使用computed确保token始终是最新的,并添加Bearer前缀
const uploadHeaders = computed(() => ({
  Authorization: authStore.token ? `Bearer ${authStore.token}` : ''
}))

// 获取完整图片URL
const getFullImageUrl = (imageUrl) => {
  if (!imageUrl) return ''
  if (imageUrl.startsWith('http')) {
    return imageUrl
  }
  // 在开发环境中,vite代理会处理/uploads路径
  // 在生产环境中,需要添加API base URL
  const baseUrl = import.meta.env.VITE_API_BASE_URL || ''
  return baseUrl ? `${baseUrl}${imageUrl}` : imageUrl
}

// Load configurations
const loadConfigs = async () => {
  loading.value = true
  try {
    const response = await api.get('/api/v1/admin/config')
    const result = response.data
    if (result.code === 0) {
      const configs = result.data
      configs.forEach(config => {
        if (config.category === 'appearance') {
          appearanceConfig.value[config.key] = config.value || ''
          originalConfigs.appearance[config.key] = config.value || ''
        } else if (config.category === 'general') {
          generalConfig.value[config.key] = config.value || ''
          originalConfigs.general[config.key] = config.value || ''
        } else if (config.category === 'contact') {
          contactConfig.value[config.key] = config.value || ''
          originalConfigs.contact[config.key] = config.value || ''
        } else if (config.category === 'agreement') {
          agreementConfig.value[config.key] = config.value || ''
          originalConfigs.agreement[config.key] = config.value || ''
        } else if (config.category === 'invite') {
          inviteConfig.value[config.key] = config.value || ''
          originalConfigs.invite[config.key] = config.value || ''
        }
      })
    }
    
    // 加载预约规则（使用独立接口）
    await loadBookingRules()
  } catch (error) {
    console.error('Load configs error:', error)
    ElMessage.error('加载配置失败')
  } finally {
    loading.value = false
  }
}

// Refresh configurations
const refreshConfigs = async () => {
  await loadConfigs()
  ElMessage.success('配置已刷新')
}

// 加载预约规则
const loadBookingRules = async () => {
  try {
    const response = await api.get('/api/v1/admin/booking-rules')
    if (response.data.code === 0) {
      const rules = response.data.data || []
      rules.forEach(rule => {
        bookingRulesConfig.value[rule.serviceType] = rule.rules || ''
      })
    }
  } catch (error) {
    console.error('Load booking rules error:', error)
  }
}

// Save appearance config
const saveAppearanceConfig = async () => {
  if (!appearanceFormRef.value) return
  
  await appearanceFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    saving.value = true
    try {
      await api.put('/api/v1/admin/config/app_logo', {
        value: appearanceConfig.value.app_logo,
        type: 'image',
        category: 'appearance',
        description: 'Application logo image URL'
      })
      
      await api.put('/api/v1/admin/config/about_us_image', {
        value: appearanceConfig.value.about_us_image,
        type: 'image',
        category: 'appearance',
        description: 'About us section image URL'
      })
      
      await api.put('/api/v1/admin/config/default_avatar', {
        value: appearanceConfig.value.default_avatar,
        type: 'image',
        category: 'appearance',
        description: '用户默认头像'
      })
      
      // Update original configs
      originalConfigs.appearance = { ...appearanceConfig.value }
      
      ElMessage.success('外观配置保存成功')
    } catch (error) {
      console.error('Save appearance config error:', error)
      ElMessage.error(error.response?.data?.message || '保存配置失败')
    } finally {
      saving.value = false
    }
  })
}

// Save general config
const saveGeneralConfig = async () => {
  if (!generalFormRef.value) return
  
  await generalFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    saving.value = true
    try {
      await api.put('/api/v1/admin/config/app_name', {
        value: generalConfig.value.app_name,
        type: 'string',
        category: 'general',
        description: 'Application name'
      })
      
      // Update original configs
      originalConfigs.general = { ...generalConfig.value }
      
      ElMessage.success('基本信息保存成功')
    } catch (error) {
      console.error('Save general config error:', error)
      ElMessage.error(error.response?.data?.message || '保存配置失败')
    } finally {
      saving.value = false
    }
  })
}

// Save contact config
const saveContactConfig = async () => {
  if (!contactFormRef.value) return
  
  await contactFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    saving.value = true
    try {
      await api.put('/api/v1/admin/config/contact_phone', {
        value: contactConfig.value.contact_phone,
        type: 'string',
        category: 'contact',
        description: 'Contact phone number'
      })
      
      await api.put('/api/v1/admin/config/contact_email', {
        value: contactConfig.value.contact_email,
        type: 'string',
        category: 'contact',
        description: 'Contact email address'
      })
      
      await api.put('/api/v1/admin/config/contact_qr_image', {
        value: contactConfig.value.contact_qr_image,
        type: 'image',
        category: 'contact',
        description: 'Contact us QR code image URL'
      })
      
      // Update original configs
      originalConfigs.contact = { ...contactConfig.value }
      
      ElMessage.success('联系方式保存成功')
    } catch (error) {
      console.error('Save contact config error:', error)
      ElMessage.error(error.response?.data?.message || '保存配置失败')
    } finally {
      saving.value = false
    }
  })
}

// Reset configs
const resetAppearanceConfig = () => {
  appearanceConfig.value = { ...originalConfigs.appearance }
  appearanceFormRef.value?.clearValidate()
}

const resetGeneralConfig = () => {
  generalConfig.value = { ...originalConfigs.general }
  generalFormRef.value?.clearValidate()
}

const resetContactConfig = () => {
  contactConfig.value = { ...originalConfigs.contact }
  contactFormRef.value?.clearValidate()
}

const resetAgreementConfig = () => {
  agreementConfig.value = { ...originalConfigs.agreement }
  agreementFormRef.value?.clearValidate()
}

// Save agreement config
const saveAgreementConfig = async () => {
  saving.value = true
  try {
    await api.put('/api/v1/admin/config/user_agreement', {
      value: agreementConfig.value.user_agreement,
      type: 'string',
      category: 'agreement',
      description: 'User agreement content'
    })
    
    await api.put('/api/v1/admin/config/privacy_policy', {
      value: agreementConfig.value.privacy_policy,
      type: 'string',
      category: 'agreement',
      description: 'Privacy policy content'
    })
    
    originalConfigs.agreement = { ...agreementConfig.value }
    ElMessage.success('协议配置保存成功')
  } catch (error) {
    console.error('Save agreement config error:', error)
    ElMessage.error(error.response?.data?.message || '保存配置失败')
  } finally {
    saving.value = false
  }
}

// Save invite config
const saveInviteConfig = async () => {
  saving.value = true
  try {
    await api.put('/api/v1/admin/config/invite_rules', {
      value: inviteConfig.value.invite_rules,
      type: 'string',
      category: 'invite',
      description: '邀请奖励规则说明'
    })
    
    originalConfigs.invite = { ...inviteConfig.value }
    ElMessage.success('邀请规则保存成功')
  } catch (error) {
    console.error('Save invite config error:', error)
    ElMessage.error(error.response?.data?.message || '保存配置失败')
  } finally {
    saving.value = false
  }
}

// Reset invite config
const resetInviteConfig = () => {
  inviteConfig.value = { ...originalConfigs.invite }
  inviteFormRef.value?.clearValidate()
}

// 保存单个预约规则
const saveBookingRule = async (serviceType) => {
  savingRule.value = serviceType
  try {
    await api.put(`/api/v1/admin/booking-rules/${serviceType}`, {
      rules: bookingRulesConfig.value[serviceType] || ''
    })
    ElMessage.success('规则保存成功')
  } catch (error) {
    console.error('Save booking rule error:', error)
    ElMessage.error(error.response?.data?.message || '保存规则失败')
  } finally {
    savingRule.value = ''
  }
}

// 保存全部预约规则
const saveAllBookingRules = async () => {
  saving.value = true
  try {
    const rules = serviceTypeOptions.map(item => ({
      serviceType: item.value,
      rules: bookingRulesConfig.value[item.value] || ''
    }))
    await api.post('/api/v1/admin/booking-rules/batch', { rules })
    ElMessage.success('全部规则保存成功')
  } catch (error) {
    console.error('Save all booking rules error:', error)
    ElMessage.error(error.response?.data?.message || '保存规则失败')
  } finally {
    saving.value = false
  }
}

// Clear images
const clearLogo = async () => {
  try {
    await ElMessageBox.confirm('确定要清除Logo吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    appearanceConfig.value.app_logo = ''
  } catch {
    // User cancelled
  }
}

const clearAboutImage = async () => {
  try {
    await ElMessageBox.confirm('确定要清除关于我们图片吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    appearanceConfig.value.about_us_image = ''
  } catch {
    // User cancelled
  }
}

// Handle logo upload success
const handleLogoSuccess = (response) => {
  if (response.code === 0) {
    appearanceConfig.value.app_logo = response.data.url
    ElMessage.success('Logo上传成功')
  } else {
    ElMessage.error(response.message || 'Logo上传失败')
  }
}

// Helper function to get full image URL
const getImageUrl = (path) => {
  if (!path) return ''
  if (path.startsWith('http')) return path
  const baseUrl = import.meta.env.VITE_API_BASE_URL || ''
  return `${baseUrl}${path}`
}

// Handle about image upload success
const handleAboutSuccess = (response) => {
  if (response.code === 0) {
    appearanceConfig.value.about_us_image = response.data.url
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.message || '图片上传失败')
  }
}

// Handle default avatar upload success
const handleDefaultAvatarSuccess = (response) => {
  if (response.code === 0) {
    appearanceConfig.value.default_avatar = response.data.url
    ElMessage.success('默认头像上传成功')
  } else {
    ElMessage.error(response.message || '默认头像上传失败')
  }
}

// Clear default avatar
const clearDefaultAvatar = async () => {
  try {
    await ElMessageBox.confirm('确定要清除默认头像吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    appearanceConfig.value.default_avatar = ''
  } catch {
    // User cancelled
  }
}

// Handle QR code upload success
const handleQrSuccess = (response) => {
  if (response.code === 0) {
    contactConfig.value.contact_qr_image = response.data.url
    ElMessage.success('二维码上传成功')
  } else {
    ElMessage.error(response.message || '二维码上传失败')
  }
}

// Clear QR image
const clearQrImage = async () => {
  try {
    await ElMessageBox.confirm('确定要清除联系二维码吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    contactConfig.value.contact_qr_image = ''
  } catch {
    // User cancelled
  }
}

// Handle upload error
const handleUploadError = (error) => {
  console.error('Upload error:', error)
  ElMessage.error('上传失败,请重试')
}

// Before upload validation
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

// Handle tab change
const handleTabChange = (tabName) => {
  // Clear validation when switching tabs
  if (tabName === 'appearance') {
    appearanceFormRef.value?.clearValidate()
  } else if (tabName === 'general') {
    generalFormRef.value?.clearValidate()
  } else if (tabName === 'contact') {
    contactFormRef.value?.clearValidate()
  } else if (tabName === 'agreement') {
    agreementFormRef.value?.clearValidate()
  } else if (tabName === 'booking_rules') {
    // 预约登记规则tab不需要清除验证
  }
}

onMounted(() => {
  loadConfigs()
})
</script>

<style scoped>
.config-container {
  padding: 20px;
}

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

.upload-container {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.logo-uploader,
.about-uploader {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  background-color: #fafafa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-uploader:hover,
.about-uploader:hover {
  border-color: #409eff;
  background-color: #f0f7ff;
}

.logo-uploader {
  width: 200px;
  height: 200px;
}

.about-uploader {
  width: 400px;
  height: 200px;
}

/* 确保Element Plus上传组件内容居中 */
.logo-uploader :deep(.el-upload),
.about-uploader :deep(.el-upload) {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.upload-icon {
  font-size: 32px;
  color: #8c939d;
}

.upload-text {
  font-size: 14px;
  color: #8c939d;
}

.logo-preview {
  width: 200px;
  height: 200px;
  object-fit: contain;
  display: block;
}

.about-preview {
  width: 400px;
  height: 200px;
  object-fit: cover;
  display: block;
}

.qr-uploader {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  background-color: #fafafa;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 200px;
  height: 200px;
}

.qr-uploader:hover {
  border-color: #409eff;
  background-color: #f0f7ff;
}

.qr-uploader :deep(.el-upload) {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.qr-preview {
  width: 200px;
  height: 200px;
  object-fit: contain;
  display: block;
}

.avatar-uploader {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  background-color: #fafafa;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 200px;
  height: 200px;
}

.avatar-uploader:hover {
  border-color: #409eff;
  background-color: #f0f7ff;
}

.avatar-uploader :deep(.el-upload) {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-preview {
  width: 200px;
  height: 200px;
  object-fit: cover;
  display: block;
  border-radius: 50%;
}

.upload-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}

:deep(.el-form-item__content) {
  align-items: flex-start;
}

:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

:deep(.el-input__prefix) {
  display: flex;
  align-items: center;
}

:deep(.el-tabs__content) {
  padding-top: 20px;
}
</style>
