<template>
  <div class="license-page">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>🔑 授权管理</span>
          <el-tag :type="license.activated ? 'success' : 'info'" size="large">
            {{ license.typeText }}
          </el-tag>
        </div>
      </template>

      <!-- 已激活状态 -->
      <div v-if="license.activated" class="activated-box">
        <el-result icon="success" title="授权激活成功" :sub-title="'当前版本：' + license.typeText">
          <template #extra>
            <el-descriptions :column="1" border style="max-width:480px;margin:0 auto">
              <el-descriptions-item label="授权版本">{{ license.typeText }}</el-descriptions-item>
              <el-descriptions-item label="绑定域名">{{ license.domain }}</el-descriptions-item>
              <el-descriptions-item label="本机机器码">
                <span style="font-family:monospace;font-size:12px">{{ license.machineId }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </template>
        </el-result>
        <div class="footer-actions">
          <el-button @click="loadInfo">刷新状态</el-button>
          <el-button type="warning" @click="showUpgrade = true">
            🔄 更换 / 升级授权
          </el-button>
        </div>

        <!-- 更换/升级授权：填入新授权码即可覆盖旧授权（如 199 升级 599） -->
        <el-divider v-if="showUpgrade" />
        <div v-if="showUpgrade" class="upgrade-box">
          <el-alert type="warning" show-icon :closable="false"
            title="更换 / 升级授权"
            description="如需升级（如 199 元升级 599 元去版权），或更换绑定域名，填写新的授权码重新激活即可覆盖当前授权。">
          </el-alert>
          <el-form :model="form" label-width="120px" style="max-width:560px;margin-top:12px">
            <el-form-item label="新授权码" required>
              <el-input v-model="form.licenseCode" placeholder="粘贴新的授权码" clearable
                style="font-family:monospace" />
            </el-form-item>
            <el-form-item label="绑定域名" required>
              <el-input v-model="form.domain" :placeholder="'默认：' + license.domain" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :loading="activating" @click="activate">确认覆盖激活</el-button>
              <el-button @click="cancelUpgrade">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 未激活：填写授权码 -->
      <div v-else class="activate-box">
        <el-alert type="info" show-icon :closable="false"
          title="请填写您购买时获得的授权码"
          description="授权码在官网购买后获取。填入后系统将自动校验并激活。199元版保留版权，599元版去除版权。">
        </el-alert>

        <el-form :model="form" label-width="120px" style="max-width:560px">
          <el-form-item label="授权码" required>
            <el-input v-model="form.licenseCode" placeholder="粘贴您的授权码" clearable
              style="font-family:monospace" />
          </el-form-item>
          <el-form-item label="绑定域名" required>
            <el-input v-model="form.domain" placeholder="例如 shop.example.com" clearable />
          </el-form-item>
          <el-form-item label="本机机器码">
            <el-input :model-value="license.machineId" readonly style="font-family:monospace;font-size:12px">
              <template #append>
                <el-button @click="copyMachineId">复制</el-button>
              </template>
            </el-input>
            <div class="form-tip">激活时需将此机器码对应的域名与授权码绑定域名一致</div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="activating" @click="activate">立即激活</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card shadow="never" style="margin-top:16px">
      <template #header><span>ℹ️ 版权说明</span></template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="199元·永久授权">保留"省胜优铺"版权信息及官网链接</el-descriptions-item>
        <el-descriptions-item label="599元·永久授权">去除所有版权信息，可二次开发（禁止转卖）</el-descriptions-item>
        <el-descriptions-item label="域名绑定">授权码绑定单一域名+机器码，不可转让</el-descriptions-item>
        <el-descriptions-item label="技术支持">官网：https://ssypco.com</el-descriptions-item>
      </el-descriptions>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../utils/request'

const license = reactive({
  activated: false,
  type: 'free',
  typeText: '免费版',
  domain: '',
  machineId: '',
})

const form = reactive({ licenseCode: '', domain: '' })
const activating = ref(false)
const showUpgrade = ref(false)

async function loadInfo() {
  try {
    const { data } = await request.get('/ssyp-license/info')
    if (data.code === 0) {
      Object.assign(license, data.data)
    } else {
      ElMessage.warning(data.message)
    }
  } catch (e) {
    ElMessage.error('加载授权信息失败')
  }
}

function cancelUpgrade() {
  showUpgrade.value = false
  form.licenseCode = ''
  form.domain = ''
}

async function activate() {
  if (!form.licenseCode.trim()) return ElMessage.warning('请输入授权码')
  if (!form.domain.trim()) return ElMessage.warning('请输入绑定域名')
  activating.value = true
  try {
    const { data } = await request.post('/ssyp-license/activate', {
      licenseCode: form.licenseCode.trim(),
      domain: form.domain.trim(),
    })
    if (data.code === 0) {
      ElMessage.success(data.message)
      form.licenseCode = ''
      form.domain = ''
      showUpgrade.value = false
      await loadInfo()
    } else {
      ElMessage.error(data.message)
    }
  } catch (e) {
    ElMessage.error('激活请求失败')
  } finally {
    activating.value = false
  }
}

function copyMachineId() {
  navigator.clipboard.writeText(license.machineId).then(() => {
    ElMessage.success('机器码已复制')
  })
}

onMounted(loadInfo)
</script>

<style scoped>
.card-header { display:flex; justify-content:space-between; align-items:center; }
.activate-box .form-tip { font-size:12px;color:#999;margin-top:4px; }
.footer-actions { text-align:center; margin-top:8px; }
</style>
