<template>
  <div class="settings-page">
    <el-card shadow="never">
      <div class="settings-tabs">
        <div v-for="t in tabList" :key="t.key" class="s-tab" :class="{active: activeTab===t.key}" @click="activeTab=t.key">
          <span>{{ t.icon }}</span> {{ t.label }}
        </div>
      </div>

      <el-divider />
      <div v-loading="loading">

        <!-- 站点设置 -->
        <div v-if="activeTab==='site'" class="tab-content">
          <h3 class="tab-title">🌐 站点设置</h3>
          <el-form label-width="140px" class="setting-form">
            <el-form-item label="站点名称"><el-input v-model="cf.site_name" /></el-form-item>
            <el-form-item label="站点描述"><el-input v-model="cf.site_description" type="textarea" :rows="3" maxlength="200" /></el-form-item>
            <el-form-item label="站点Logo">
              <el-upload :action="uploadUrl" :headers="uh" :show-file-list="false" :on-success="r=>cf.site_logo=r.data.url">
                <el-image v-if="cf.site_logo" :src="cf.site_logo" style="width:60px;height:60px;border-radius:6px" />
                <el-button v-else size="small">上传Logo</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item label="客服电话"><el-input v-model="cf.contact_phone" placeholder="400-xxx-xxxx" /></el-form-item>
            <el-form-item label="客服邮箱"><el-input v-model="cf.contact_email" /></el-form-item>
            <el-form-item label="ICP备案号"><el-input v-model="cf.icp_beian" placeholder="粤ICP备xxxxxx号" /></el-form-item>
            <el-form-item label="自定义版权">
              <el-input v-model="cf.copyright_text" placeholder="付费版可自定义底部版权文字" maxlength="200" show-word-limit />
              <span class="upload-tip">免费版固定显示 Powered By LiteMall</span>
            </el-form-item>
          </el-form>
        </div>

        <!-- 支付配置 -->
        <div v-if="activeTab==='payment'" class="tab-content">
          <h3 class="tab-title">💳 支付配置</h3>
          <el-divider content-position="left">微信支付（Native/JSAPI）</el-divider>
          <el-form label-width="160px">
            <el-form-item label="微信AppId"><el-input v-model="cf.wechat_appid" /></el-form-item>
            <el-form-item label="微信商户号"><el-input v-model="cf.wechat_mchid" /></el-form-item>
            <el-form-item label="API密钥"><el-input v-model="cf.wechat_key" type="password" show-password /></el-form-item>
            <el-form-item label="APIv3密钥"><el-input v-model="cf.wechat_v3_key" type="password" show-password /></el-form-item>
            <el-form-item label="证书序列号"><el-input v-model="cf.wechat_serial_no" /></el-form-item>
          </el-form>
          <el-divider content-position="left">支付宝</el-divider>
          <el-form label-width="160px">
            <el-form-item label="支付宝AppId"><el-input v-model="cf.alipay_appid" /></el-form-item>
            <el-form-item label="商户私钥"><el-input v-model="cf.alipay_private_key" type="textarea" :rows="2" /></el-form-item>
            <el-form-item label="支付宝公钥"><el-input v-model="cf.alipay_public_key" type="textarea" :rows="2" /></el-form-item>
          </el-form>
        </div>

        <!-- 存储配置 -->
        <div v-if="activeTab==='storage'" class="tab-content">
          <h3 class="tab-title">☁️ 存储配置</h3>
          <el-form label-width="160px">
            <el-form-item label="存储驱动">
              <el-select v-model="cf.storage_driver" style="width:200px">
                <el-option label="本地存储" value="local" />
                <el-option label="阿里云OSS" value="oss" />
                <el-option label="腾讯云COS" value="cos" />
                <el-option label="七牛云" value="qiniu" />
              </el-select>
            </el-form-item>
            <template v-if="cf.storage_driver==='oss'">
              <el-form-item label="AccessKey"><el-input v-model="cf.oss_access_key" /></el-form-item>
              <el-form-item label="AccessSecret"><el-input v-model="cf.oss_access_secret" type="password" show-password /></el-form-item>
              <el-form-item label="Bucket"><el-input v-model="cf.oss_bucket" /></el-form-item>
              <el-form-item label="EndPoint"><el-input v-model="cf.oss_endpoint" placeholder="oss-cn-hangzhou.aliyuncs.com" /></el-form-item>
              <el-form-item label="访问域名"><el-input v-model="cf.oss_domain" placeholder="https://xxx.oss-cn-hangzhou.aliyuncs.com" /></el-form-item>
            </template>
            <template v-if="cf.storage_driver==='cos'">
              <el-form-item label="SecretId"><el-input v-model="cf.cos_secret_id" /></el-form-item>
              <el-form-item label="SecretKey"><el-input v-model="cf.cos_secret_key" type="password" show-password /></el-form-item>
              <el-form-item label="Bucket"><el-input v-model="cf.cos_bucket" /></el-form-item>
              <el-form-item label="所属地域"><el-input v-model="cf.cos_region" placeholder="ap-guangzhou" /></el-form-item>
            </template>
            <template v-if="cf.storage_driver==='qiniu'">
              <el-form-item label="AccessKey"><el-input v-model="cf.qiniu_access_key" /></el-form-item>
              <el-form-item label="SecretKey"><el-input v-model="cf.qiniu_secret_key" type="password" show-password /></el-form-item>
              <el-form-item label="Bucket"><el-input v-model="cf.qiniu_bucket" /></el-form-item>
              <el-form-item label="访问域名"><el-input v-model="cf.qiniu_domain" placeholder="https://xxx.qiniucdn.com" /></el-form-item>
            </template>
          </el-form>
        </div>

        <!-- 邮件配置 -->
        <div v-if="activeTab==='mail'" class="tab-content">
          <h3 class="tab-title">📧 邮件配置</h3>
          <el-form label-width="140px">
            <el-form-item label="SMTP服务器"><el-input v-model="cf.mail_smtp_host" placeholder="smtp.qq.com" /></el-form-item>
            <el-form-item label="SMTP端口"><el-input-number v-model="cf.mail_smtp_port" :min="1" :max="65535" style="width:160px" /></el-form-item>
            <el-form-item label="发件人邮箱"><el-input v-model="cf.mail_from" placeholder="noreply@example.com" /></el-form-item>
            <el-form-item label="SMTP账号"><el-input v-model="cf.mail_username" /></el-form-item>
            <el-form-item label="SMTP密码/授权码"><el-input v-model="cf.mail_password" type="password" show-password /></el-form-item>
            <el-form-item label="加密方式">
              <el-select v-model="cf.mail_encryption" style="width:160px"><el-option label="SSL" value="ssl" /><el-option label="TLS" value="tls" /><el-option label="无" value="" /></el-select>
            </el-form-item>
          </el-form>
        </div>

        <!-- 短信配置 -->
        <div v-if="activeTab==='sms'" class="tab-content">
          <h3 class="tab-title">📱 短信配置</h3>
          <el-form label-width="160px">
            <el-form-item label="短信服务商">
              <el-select v-model="cf.sms_driver" style="width:200px">
                <el-option label="阿里云短信" value="aliyun" />
                <el-option label="腾讯云短信" value="tencent" />
                <el-option label="创蓝短信" value="chuanglan" />
              </el-select>
            </el-form-item>
            <template v-if="cf.sms_driver==='aliyun'">
              <el-form-item label="AccessKey"><el-input v-model="cf.sms_aliyun_key" /></el-form-item>
              <el-form-item label="AccessSecret"><el-input v-model="cf.sms_aliyun_secret" type="password" show-password /></el-form-item>
              <el-form-item label="短信签名"><el-input v-model="cf.sms_sign" placeholder="如: 省胜优铺" /></el-form-item>
            </template>
            <template v-if="cf.sms_driver==='tencent'">
              <el-form-item label="SecretId"><el-input v-model="cf.sms_tencent_id" /></el-form-item>
              <el-form-item label="SecretKey"><el-input v-model="cf.sms_tencent_key" type="password" show-password /></el-form-item>
              <el-form-item label="SdkAppId"><el-input v-model="cf.sms_sdk_app_id" /></el-form-item>
              <el-form-item label="短信签名"><el-input v-model="cf.sms_sign" /></el-form-item>
            </template>
          </el-form>
        </div>

        <!-- 微信配置 -->
        <div v-if="activeTab==='wechat'" class="tab-content">
          <h3 class="tab-title">💬 微信配置</h3>
          <el-form label-width="160px">
            <el-divider content-position="left">公众号</el-divider>
            <el-form-item label="公众号AppId"><el-input v-model="cf.wechat_mp_appid" /></el-form-item>
            <el-form-item label="公众号Secret"><el-input v-model="cf.wechat_mp_secret" type="password" show-password /></el-form-item>
            <el-form-item label="公众号Token"><el-input v-model="cf.wechat_mp_token" /></el-form-item>
            <el-divider content-position="left">小程序</el-divider>
            <el-form-item label="小程序AppId"><el-input v-model="cf.wechat_mini_appid" /></el-form-item>
            <el-form-item label="小程序Secret"><el-input v-model="cf.wechat_mini_secret" type="password" show-password /></el-form-item>
          </el-form>
        </div>

        <!-- 安全设置 -->
        <div v-if="activeTab==='security'" class="tab-content">
          <h3 class="tab-title">🔒 安全设置</h3>
          <el-form label-width="200px">
            <el-form-item label="登录验证码"><el-switch v-model="cf.login_captcha" active-value="1" inactive-value="0" /></el-form-item>
            <el-form-item label="注册验证码"><el-switch v-model="cf.register_captcha" active-value="1" inactive-value="0" /></el-form-item>
            <el-form-item label="单设备登录"><el-switch v-model="cf.single_device" active-value="1" inactive-value="0" /></el-form-item>
            <el-form-item label="Token过期时间(天)"><el-input-number v-model="cf.token_expire_days" :min="1" :max="365" style="width:160px" /></el-form-item>
            <el-form-item label="登录失败锁定次数"><el-input-number v-model="cf.login_retry_limit" :min="0" :max="20" style="width:160px" /></el-form-item>
          </el-form>
        </div>

        <!-- 应用配置 -->
        <div v-if="activeTab==='app_config'" class="tab-content">
          <h3 class="tab-title">⚙️ 余额抵扣配置</h3>
          <el-form label-width="200px">
            <el-form-item label="余额抵扣开关">
              <el-switch v-model="cf.balance_deduct_enabled" active-value="1" inactive-value="0" />
              <span style="margin-left:10px;font-size:12px;color:#999">开启后用户可使用余额支付订单</span>
            </el-form-item>
            <el-form-item label="每笔抵扣比例">
              <el-input-number v-model="cf.balance_deduct_ratio" :min="0" :max="100" :step="5" style="width:160px" /><span style="margin-left:8px">%</span>
              <span style="margin-left:10px;font-size:12px;color:#999">每笔订单最多可用余额支付的比例</span>
            </el-form-item>
            <el-form-item label="积分抵现汇率">
              <el-input-number v-model="cf.points_to_cash_rate" :min="0.01" :precision="2" :step="0.1" style="width:160px" /><span style="margin-left:8px">积分 = 1元</span>
              <span style="margin-left:10px;font-size:12px;color:#999">多少积分可抵扣1元</span>
            </el-form-item>
          </el-form>
        </div>

        <!-- 模块开关 -->
        <div v-if="activeTab==='module'" class="tab-content">
          <h3 class="tab-title">🔌 模块开关</h3>
          <el-form label-width="200px">
            <el-form-item label="积分系统"><el-switch v-model="cf.module_points" active-value="1" inactive-value="0" /></el-form-item>
            <el-form-item label="分销功能"><el-switch v-model="cf.module_distribution" active-value="1" inactive-value="0" /></el-form-item>
            <el-form-item label="秒杀功能"><el-switch v-model="cf.module_seckill" active-value="1" inactive-value="0" /></el-form-item>
            <el-form-item label="拼团功能"><el-switch v-model="cf.module_group_buy" active-value="1" inactive-value="0" /></el-form-item>
            <el-form-item label="优惠券"><el-switch v-model="cf.module_coupon" active-value="1" inactive-value="0" /></el-form-item>
            <el-form-item label="AI客服"><el-switch v-model="cf.module_ai" active-value="1" inactive-value="0" /></el-form-item>
            <el-form-item label="会员等级"><el-switch v-model="cf.module_member" active-value="1" inactive-value="0" /></el-form-item>
            <el-form-item label="多终端"><el-switch v-model="cf.module_multi_terminal" active-value="1" inactive-value="0" /></el-form-item>
          </el-form>
        </div>

        <!-- 授权管理 -->
        <div v-if="activeTab==='license'" class="tab-content">
          <h3 class="tab-title">🔑 授权管理</h3>
          <el-form label-width="160px" style="max-width:600px">
            <el-form-item label="当前版本">
              <el-tag v-if="licenseInfo.type === 'free'" size="large" type="info">轻量版（SQLite）</el-tag>
              <el-tag v-else-if="licenseInfo.type === 'premium'" size="large" type="success">商用版（MySQL）</el-tag>
              <el-tag v-else size="large" type="warning">{{ licenseInfo.type }}</el-tag>
            </el-form-item>
            <el-form-item label="服务器ID">
              <el-input :model-value="licenseInfo.serverId" readonly>
                <template #append>
                  <el-button @click="copyServerId">复制</el-button>
                </template>
              </el-input>
              <div style="font-size:12px;color:#909399;margin-top:4px">购买授权时，请将此ID提供给卖家</div>
            </el-form-item>
            <el-divider />
            <el-form-item label="激活码">
              <el-input v-model="licenseInput" placeholder="输入激活码，如 LITEMALL-XXXX-YYYY-ZZZZ">
                <template #append>
                  <el-button type="primary" @click="activateLicense" :loading="activating">激活</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-alert
                v-if="licenseInfo.type !== 'free'"
                title="已授权"
                type="success"
                :description="'授权类型: ' + (licenseInfo.type === 'premium' ? '商用版' : '终身版')"
                show-icon
                :closable="false"
              />
              <el-alert
                v-else
                title="未授权"
                type="info"
                description="当前为轻量版，输入激活码解锁商用版全部功能"
                show-icon
                :closable="false"
              />
            </el-form-item>
          </el-form>
        </div>

      </div>

      <div class="save-bar">
        <el-button type="primary" size="large" :loading="saving" @click="saveSettings">💾 保存全部配置</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const API = axios.create({ baseURL: '/api/admin' })
API.interceptors.request.use(c => { c.headers.Authorization = 'Bearer ' + localStorage.getItem('admin_token'); return c })
const uploadUrl = '/api/admin/upload/image'
const uh = { Authorization: 'Bearer ' + localStorage.getItem('admin_token') }

const tabList = [
  { key:'site', icon:'🌐', label:'站点设置' },
  { key:'payment', icon:'💳', label:'支付配置' },
  { key:'storage', icon:'☁️', label:'存储配置' },
  { key:'mail', icon:'📧', label:'邮件配置' },
  { key:'sms', icon:'📱', label:'短信配置' },
  { key:'wechat', icon:'💬', label:'微信配置' },
  { key:'security', icon:'🔒', label:'安全设置' },
  { key:'module', icon:'🔌', label:'模块开关' },
  { key:'app_config', icon:'⚙️', label:'应用配置' },
  { key:'license', icon:'🔑', label:'授权管理' },
]
const activeTab = ref('site')
const loading = ref(false)
const saving = ref(false)
const cf = reactive({})

// config key 列表
const configKeys = {
  site: ['site_name','site_description','site_logo','contact_phone','contact_email','icp_beian','copyright_text'],
  payment: ['wechat_appid','wechat_mchid','wechat_key','wechat_v3_key','wechat_serial_no','alipay_appid','alipay_private_key','alipay_public_key'],
  storage: ['storage_driver','oss_access_key','oss_access_secret','oss_bucket','oss_endpoint','oss_domain','cos_secret_id','cos_secret_key','cos_bucket','cos_region','qiniu_access_key','qiniu_secret_key','qiniu_bucket','qiniu_domain'],
  mail: ['mail_smtp_host','mail_smtp_port','mail_from','mail_username','mail_password','mail_encryption'],
  sms: ['sms_driver','sms_aliyun_key','sms_aliyun_secret','sms_tencent_id','sms_tencent_key','sms_sdk_app_id','sms_sign'],
  wechat: ['wechat_mp_appid','wechat_mp_secret','wechat_mp_token','wechat_mini_appid','wechat_mini_secret'],
  security: ['login_captcha','register_captcha','single_device','token_expire_days','login_retry_limit'],
  module: ['module_points','module_distribution','module_seckill','module_group_buy','module_coupon','module_ai','module_member','module_multi_terminal'],
  app_config: ['balance_deduct_enabled','balance_deduct_ratio','points_to_cash_rate'],
}

// 所有key打平
const allKeys = Object.values(configKeys).flat()

// 授权管理
const licenseInfo = ref({ type: 'free', serverId: '' })
const licenseInput = ref('')
const activating = ref(false)

async function fetchLicense() {
  try {
    const r = await API.get('/ssyp-license/info')
    if (r.code === 0 && r.data) {
      licenseInfo.value = { type: r.data.type, serverId: r.data.machineId || '' }
    }
  } catch { /* 静默 */ }
}

async function activateLicense() {
  if (!licenseInput.value.trim()) return ElMessage.warning('请输入激活码')
  activating.value = true
  try {
    // 授权激活统一走安全 ssyp-license 体系（原 /admin/license/activate 含硬编码万能激活码后门，已移除）
    const r = await API.post('/ssyp-license/activate', { licenseCode: licenseInput.value.trim(), domain: window.location.hostname })
    if (r.code === 0) {
      ElMessage.success('激活成功！已解锁对应功能')
      licenseInput.value = ''
      fetchLicense()
    } else {
      ElMessage.error(r.message || '激活失败')
    }
  } catch { ElMessage.error('激活失败')
  } finally { activating.value = false }
}

async function copyServerId() {
  try {
    await navigator.clipboard.writeText(licenseInfo.value.serverId)
    ElMessage.success('已复制服务器ID')
  } catch {
    ElMessage.warning('复制失败，请手动复制')
  }
}

onMounted(async () => {
  fetchLicense()
  loading.value = true
  try {
    const r = await API.get('/config')
    const groups = r.data.data || {}
    const map = {}
    for (const [g, items] of Object.entries(groups)) {
      items.forEach(item => { map[item.key] = item.value })
    }
    allKeys.forEach(k => { cf[k] = map[k] ?? '' })
  } catch { ElMessage.error('加载配置失败') }
  loading.value = false
})

async function saveSettings() {
  saving.value = true
  try {
    const configs = allKeys.map(key => ({ key, value: String(cf[key] ?? '') }))
    await API.put('/config', { configs })
    ElMessage.success('配置已保存')
  } catch { ElMessage.error('保存失败') }
  finally { saving.value = false }
}
</script>

<style scoped>
.settings-page { max-width: 900px; }
.settings-tabs { display: flex; flex-wrap: wrap; gap: 4px; }
.s-tab { display:flex; align-items:center; gap:4px; padding:8px 16px; border-radius:6px; cursor:pointer; font-size:13px; transition:all .2s; }
.s-tab:hover { background:#f5f7fa; }
.s-tab.active { background:#ecf5ff; color:#409eff; font-weight:600; }
.tab-content { min-height: 300px; }
.tab-title { font-size:16px; font-weight:600; color:#333; margin:0 0 20px 0; padding-bottom:12px; border-bottom:2px solid #409eff; display:inline-block; }
.setting-form { max-width: 600px; }
.save-bar { text-align:center; padding: 24px 0 0; border-top:1px solid #eee; margin-top:24px; }
</style>
