<template>
  <div>
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" type="text" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回兑换码库管理
        </el-button>
        <h2>{{ libraryInfo.codeName }} - 兑换码管理</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleGenerateCdk">生成兑换码</el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="gva-search-box">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="兑换码">
          <el-input v-model="searchForm.code" placeholder="请输入兑换码" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="未使用" :value="1" />
            <el-option label="已使用" :value="2" />
            <el-option label="已作废" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="使用者">
          <el-input v-model="searchForm.useName" placeholder="请输入使用者名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchData">查询</el-button>
          <el-button @click="resetData">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计信息 -->
    <div class="stats-box">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ stats.total }}</div>
            <div class="stat-label">总数量</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item unused">
            <div class="stat-value">{{ stats.unused }}</div>
            <div class="stat-label">未使用</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item used">
            <div class="stat-value">{{ stats.used }}</div>
            <div class="stat-label">已使用</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item invalid">
            <div class="stat-value">{{ stats.invalid }}</div>
            <div class="stat-label">已作废</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 表格区域 -->
    <div class="gva-table-box">
      <el-table
        :data="tableData"
        v-loading="tableLoading"
        style="width: 100%"
        class="gva-table"
        stripe
      >
        <el-table-column prop="ID" label="ID" width="80" />
        <el-table-column prop="code" label="兑换码" min-width="180">
          <template #default="{ row }">
            <div class="code-cell">
              <span>{{ row.code }}</span>
              <el-button 
                type="text" 
                @click="copyCode(row.code)"
                class="copy-btn"
                title="复制兑换码"
              >
                <el-icon><CopyDocument /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="validDay" label="有效期(天)" width="120" />
        <el-table-column prop="expireAt" label="到期时间" width="180">
          <template #default="{ row }">
            <span :class="{ 'text-danger': isExpiringSoon(row.expireAt), 'text-expired': isExpired(row.expireAt) }">
              {{ formatDate(row.expireAt) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="useName" label="使用者" width="120">
          <template #default="{ row }">
            {{ row.useName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="useAt" label="使用时间" width="180">
          <template #default="{ row }">
            {{ row.useAt ? formatDate(row.useAt) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="CreatedAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.CreatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="text" 
              @click="openShare(row)"
            >
              分享
            </el-button>
            <el-button 
              type="text" 
              @click="handleDelete(row)" 
              style="color: #f56c6c"
              :disabled="row.status !== 1"
            >
              作废
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="gva-pagination"
      />
    </div>

    <!-- 分享弹窗 -->
    <el-dialog
      v-model="shareDialogVisible"
      title="分享兑换码"
      width="520px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form label-width="100px">
        <el-form-item label="选择域名">
          <el-select
            v-model="shareForm.domain"
            placeholder="请选择域名"
            filterable
            style="width: 100%"
            @change="updateShareLink"
          >
            <el-option
              v-for="item in domainOptions"
              :key="item.ID"
              :label="item.name ? `${item.name}（${item.domain_url}）` : item.domain_url"
              :value="item.domain_url"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分享链接">
          <div class="flex" style="width: 100%">
            <el-input v-model="shareForm.link" readonly />
            <el-button style="margin-left: 10px" type="primary" @click="copyShareLink" :disabled="!shareForm.link">复制</el-button>
          </div>
        </el-form-item>
        <el-form-item label="二维码" v-if="shareForm.link">
          <div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap">
            <vue-qr :text="shareForm.link" :size="180" :margin="0" :autoColor="true" :dotScale="1"/>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeShare">关 闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 生成兑换码弹窗 -->
    <el-dialog
      v-model="generateDialogVisible"
      title="生成兑换码"
      width="500px"
      :before-close="handleGenerateClose"
    >
      <el-form
        ref="generateFormRef"
        :model="generateForm"
        :rules="getDynamicRules()"
        label-width="120px"
      >
        <el-form-item label="兑换码库">
          <el-input v-model="libraryInfo.codeName" disabled />
        </el-form-item>
        <el-form-item label="生成数量" prop="number">
          <el-input-number 
            v-model="generateForm.number" 
            :min="1" 
            :max="100"
            placeholder="请输入生成数量"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="有效期" prop="validityType">
          <el-radio-group v-model="generateForm.validityType" @change="handleValidityTypeChange">
            <el-radio :label="'permanent'">永久有效</el-radio>
            <el-radio :label="'custom'">自定义天数</el-radio>
          </el-radio-group>
          <div v-if="generateForm.validityType === 'custom'" style="margin-top: 10px;">
            <el-input-number 
              v-model="generateForm.customDays" 
              :min="1" 
              :max="3650"
              placeholder="请输入有效期天数"
              style="width: 200px"
            />
            <span style="margin-left: 8px;">天</span>
          </div>
          <div style="font-size: 12px; color: #999; margin-top: 5px;">
            {{ generateForm.validityType === 'permanent' ? '兑换码永久有效，不会过期' : '兑换码的有效期，超过此期限将无法使用' }}
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleGenerateClose">取消</el-button>
          <el-button type="primary" @click="submitGenerate">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { cdkList, addCdk, delCdk } from '@/api/cdk/index.js'
import { list as domainList } from '@/api/domain'
import vueQr from 'vue-qr/src/packages/vue-qr.vue'
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, CopyDocument } from '@element-plus/icons-vue'

defineOptions({
  name: 'CdkManage'
})

const route = useRoute()
const router = useRouter()

// 兑换码库信息
const libraryInfo = ref({
  ID: '',
  codeName: ''
})

// 表格相关数据
const tableLoading = ref(false)
const tableData = ref([])
const queryParams = ref({
  page: 1,
  pageSize: 10,
  eid: 0
})
const total = ref(0)

// 搜索表单
const searchForm = ref({
  code: '',
  status: '',
  useName: ''
})
// 分享相关
const shareDialogVisible = ref(false)
const shareForm = ref({
  domain: '',
  link: ''
})
const currentShareCode = ref('')
const domainOptions = ref([])

const openShare = async (row) => {
  currentShareCode.value = row.code
  shareForm.value = { domain: '', link: '' }
  shareDialogVisible.value = true
  if (!domainOptions.value.length) {
    try {
      const res = await domainList({ page: 1, pageSize: 100 })
      if (res.code === 0) {
        domainOptions.value = res.data.list || []
      }
    } catch (e) {
      // ignore
    }
  }
}

const stripProtocol = (url) => {
  if (!url) return ''
  return url.replace(/^https?:\/\//i, '').replace(/\/$/, '')
}

const updateShareLink = () => {
  const host = stripProtocol(shareForm.value.domain)
  if (!host || !currentShareCode.value) {
    shareForm.value.link = ''
    return
  }
  shareForm.value.link = `${host}/pages/user/cdk/index?dhm=${encodeURIComponent(currentShareCode.value)}`
}

const copyShareLink = async () => {
  if (!shareForm.value.link) return
  try {
    await navigator.clipboard.writeText(shareForm.value.link)
    ElMessage.success('链接已复制到剪贴板')
  } catch (error) {
    // 兼容不支持的情况
    const ta = document.createElement('textarea')
    ta.value = shareForm.value.link
    document.body.appendChild(ta)
    ta.select()
    document.execCommand('copy')
    document.body.removeChild(ta)
    ElMessage.success('链接已复制到剪贴板')
  }
}

const closeShare = () => {
  shareDialogVisible.value = false
}


// 统计数据
const stats = computed(() => {
  const unused = tableData.value.filter(item => item.status === 1).length
  const used = tableData.value.filter(item => item.status === 2).length
  const invalid = tableData.value.filter(item => item.status === 3).length
  
  return {
    total: total.value,
    unused,
    used,
    invalid
  }
})

// 生成兑换码弹窗
const generateDialogVisible = ref(false)
const generateFormRef = ref(null)
const generateForm = ref({
  eid: 0,
  number: 1,
  expirer: 30,
  validityType: 'custom', // 'permanent' 或 'custom'
  customDays: 30
})

// 表单验证规则
const generateRules = {
  number: [
    { required: true, message: '请输入生成数量', trigger: 'blur' },
    { type: 'number', min: 1, max: 1000, message: '生成数量必须在1-1000之间', trigger: 'blur' }
  ],
  validityType: [
    { required: true, message: '请选择有效期类型', trigger: 'change' }
  ]
}

// 动态验证规则
const getDynamicRules = () => {
  const rules = { ...generateRules }
  if (generateForm.value.validityType === 'custom') {
    rules.customDays = [
      { required: true, message: '请输入有效期天数', trigger: 'blur' },
      { type: 'number', min: 1, max: 3650, message: '有效期必须在1-3650天之间', trigger: 'blur' }
    ]
  }
  return rules
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '未使用',
    2: '已使用',
    3: '已作废'
  }
  return statusMap[status] || '未知'
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    1: 'success',
    2: 'warning', 
    3: 'danger'
  }
  return typeMap[status] || 'info'
}

// 判断是否即将过期（7天内）
const isExpiringSoon = (expireTime) => {
  if (!expireTime) return false
  const expireDate = new Date(expireTime)
  const now = new Date()
  const diffTime = expireDate.getTime() - now.getTime()
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays <= 7 && diffDays > 0
}

// 判断是否已过期
const isExpired = (expireTime) => {
  if (!expireTime) return false
  const expireDate = new Date(expireTime)
  const now = new Date()
  return expireDate.getTime() < now.getTime()
}

// 复制兑换码
const copyCode = async (code) => {
  try {
    await navigator.clipboard.writeText(code)
    ElMessage.success('兑换码已复制到剪贴板')
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = code
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('兑换码已复制到剪贴板')
  }
}

// 搜索数据
const searchData = () => {
  queryParams.value.page = 1
  getList()
}

// 重置搜索
const resetData = () => {
  searchForm.value = {
    code: '',
    status: '',
    useName: ''
  }
  queryParams.value.page = 1
  getList()
}

// 分页处理
const handleSizeChange = (size) => {
  queryParams.value.pageSize = size
  getList()
}

const handleCurrentChange = (page) => {
  queryParams.value.page = page
  getList()
}

// 获取兑换码列表
async function getList() {
  tableLoading.value = true
  try {
    const params = {
      ...queryParams.value,
      ...searchForm.value
    }
    const res = await cdkList(params)
    if (res.code === 0) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取兑换码列表失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    tableLoading.value = false
  }
}

// 处理有效期类型变化
const handleValidityTypeChange = (type) => {
  if (type === 'permanent') {
    generateForm.value.expirer = 0
  } else {
    generateForm.value.expirer = generateForm.value.customDays || 30
  }
}

// 生成兑换码
const handleGenerateCdk = () => {
  generateForm.value = {
    eid: Number(libraryInfo.value.ID),
    number: 1,
    expirer: 30,
    validityType: 'custom',
    customDays: 30
  }
  generateDialogVisible.value = true
}

// 关闭生成弹窗
const handleGenerateClose = () => {
  generateDialogVisible.value = false
  generateFormRef.value?.resetFields()
}

// 提交生成
const submitGenerate = async () => {
  if (!generateFormRef.value) return
  
  // 动态设置验证规则
  generateFormRef.value.clearValidate()
  
  // 根据选择的有效期类型设置expirer值
  if (generateForm.value.validityType === 'permanent') {
    generateForm.value.expirer = 0
  } else {
    generateForm.value.expirer = generateForm.value.customDays
  }
  
  // 验证表单
  let isValid = true
  
  // 验证生成数量
  if (!generateForm.value.number || generateForm.value.number < 1 || generateForm.value.number > 1000) {
    ElMessage.error('生成数量必须在1-1000之间')
    isValid = false
  }
  
  // 验证自定义天数
  if (generateForm.value.validityType === 'custom') {
    if (!generateForm.value.customDays || generateForm.value.customDays < 1 || generateForm.value.customDays > 3650) {
      ElMessage.error('有效期必须在1-3650天之间')
      isValid = false
    }
  }
  
  if (isValid) {
    try {
      // 准备提交的数据
      const submitData = {
        eid: generateForm.value.eid,
        number: generateForm.value.number,
        expirer: generateForm.value.expirer
      }
      
      const res = await addCdk(submitData)
      if (res.code === 0) {
        ElMessage.success('生成成功')
        handleGenerateClose()
        getList()
      } else {
        ElMessage.error(res.msg || '生成失败')
      }
    } catch (error) {
      ElMessage.error('生成失败')
    }
  }
}

// 作废兑换码
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要作废这个兑换码吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await delCdk({ ID: row.ID })
    if (res.code === 0) {
      ElMessage.success('作废成功')
      getList()
    } else {
      ElMessage.error(res.msg || '作废失败')
    }
  } catch (error) {
    // 用户取消作废
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 页面初始化
onMounted(() => {
  // 从路由参数获取兑换码库信息
  const { id, name } = route.query
  if (id && name) {
    libraryInfo.value = {
      ID: id,
      codeName: decodeURIComponent(name)
    }
    queryParams.value.eid = id
    getList()
  } else {
    ElMessage.error('缺少兑换码库信息')
    goBack()
  }
})
</script>

<style lang="scss" scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .header-left {
    display: flex;
    align-items: center;
    
    .back-btn {
      margin-right: 15px;
      color: #409eff;
      
      &:hover {
        color: #66b1ff;
      }
    }
    
    h2 {
      margin: 0;
      font-size: 18px;
      color: #303133;
    }
  }
}

.gva-search-box {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stats-box {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .stat-item {
    text-align: center;
    padding: 20px;
    border-radius: 8px;
    background: #f8f9fa;
    
    &.unused {
      background: #f0f9ff;
      color: #0369a1;
    }
    
    &.used {
      background: #fefce8;
      color: #a16207;
    }
    
    &.invalid {
      background: #fef2f2;
      color: #dc2626;
    }

    .stat-value {
      font-size: 28px;
      font-weight: bold;
      margin-bottom: 5px;
    }

    .stat-label {
      font-size: 14px;
      opacity: 0.8;
    }
  }
}

.gva-table-box {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.gva-table {
  :deep(.el-table__header) {
    background-color: #f5f7fa;
  }
  
  :deep(.el-table__row:hover > td) {
    background-color: #f5f7fa !important;
  }
}

.gva-pagination {
  margin-top: 20px;
  text-align: right;
}

.demo-form-inline {
  .el-form-item {
    margin-right: 20px;
  }
}

.code-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  
  .copy-btn {
    margin-left: 8px;
    padding: 4px;
    
    &:hover {
      color: #409eff;
    }
  }
}

.text-danger {
  color: #f56c6c;
  font-weight: bold;
}

.text-expired {
  color: #909399;
  text-decoration: line-through;
}
</style>