<template>
  <div>
    <div class="cdk-library-management">
        <!-- 兑换码库管理 -->
        <div class="gva-search-box">
          <el-form :inline="true" :model="mkSearchForm" class="demo-form-inline">
            <el-form-item label="兑换码库名称">
              <el-input v-model="mkSearchForm.codeName" placeholder="请输入兑换码库名称" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchMkData">查询</el-button>
              <el-button @click="resetMkData">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <div class="gva-table-box">
          <div class="gva-btn-list">
            <el-button type="primary" @click="handleAddMk">新增兑换码库</el-button>
          </div>
          
          <el-table
            :data="mkTableData"
            v-loading="mkTableLoading"
            style="width: 100%"
            class="gva-table"
            stripe
          >
            <el-table-column prop="ID" label="ID" width="80" />
            <el-table-column prop="codeName" label="兑换码库名称" min-width="150" />
            <el-table-column prop="type" label="类型" width="100">
              <template #default="{ row }">
                {{ getTypeText(row.type) }}
              </template>
            </el-table-column>
            <el-table-column prop="item" label="关联项目" width="150">
              <template #default="{ row }">
                {{ getItemDisplayName(row) }}
              </template>
            </el-table-column>
            <el-table-column prop="num" label="兑换码数量" width="120" />
            <el-table-column prop="no" label="已使用数量" width="120" />
            <el-table-column label="使用率" width="100">
              <template #default="{ row }">
                {{ getUsageRate(row.no, row.num) }}
              </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="260" fixed="right">
              <template #default="{ row }">
                <el-button type="text" @click="handleEditMk(row)">编辑</el-button>
                <el-button type="text" @click="handleManageCdk(row)">兑换码管理</el-button>
                <el-button type="text" @click="handleDeleteMk(row)" style="color: #f56c6c">删除</el-button>
                <el-button type="text" @click="handleExportMk(row)">导出Excel</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <el-pagination
            v-model:current-page="mkQueryParams.page"
            v-model:page-size="mkQueryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="mkTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleMkSizeChange"
            @current-change="handleMkCurrentChange"
            class="gva-pagination"
          />
        </div>
    </div>

    <!-- 新增/编辑兑换码库弹窗 -->
    <el-dialog
      v-model="mkDialogVisible"
      :title="mkDialogTitle"
      width="500px"
      :before-close="handleMkClose"
    >
      <el-form
        ref="mkFormRef"
        :model="mkForm"
        :rules="mkRules"
        label-width="120px"
      >
        <el-form-item label="兑换码库名称" prop="codeName">
          <el-input v-model="mkForm.codeName" placeholder="请输入兑换码库名称" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="mkForm.type" placeholder="请选择类型" style="width: 100%" @change="handleTypeChange">
            <el-option label="VIP" :value="1" />
            <el-option label="讲师VIP" :value="2" />
            <el-option label="课程" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item :label="getItemLabel(mkForm.type)" prop="item">
          <el-button type="primary" @click="handleSelectItem" style="width: 100%">
            {{ selectedItemName || '请选择' + getItemLabel(mkForm.type) }}
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleMkClose">取消</el-button>
          <el-button type="primary" @click="submitMk">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 选择项目弹窗 -->
    <el-dialog
      v-model="selectItemDialogVisible"
      :title="'选择' + getItemLabel(mkForm.type)"
      width="900px"
      :before-close="handleSelectItemClose"
    >
      <!-- 搜索框 -->
      <div style="margin-bottom: 15px;">
        <el-input
          v-model="itemSearchKeyword"
          placeholder="请输入关键词搜索"
          clearable
          @input="handleItemSearch"
          style="width: 300px;"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <el-table
        :data="filteredItemOptions"
        v-loading="itemOptionsLoading"
        style="width: 100%"
        @row-click="handleItemRowClick"
        highlight-current-row
      >
        <el-table-column prop="ID" label="ID" width="80" />
        <el-table-column :prop="getItemNameProp(mkForm.type)" :label="getItemLabel(mkForm.type) + '名称'" min-width="200" />
        
        <!-- VIP套餐相关列 -->
        <template v-if="mkForm.type === 1">
          <el-table-column prop="price" label="价格" width="100">
            <template #default="{ row }">
              ¥{{ row.price }}
            </template>
          </el-table-column>
          <el-table-column prop="duration" label="时长(天)" width="100" />
        </template>
        
        <!-- 讲师VIP相关列 -->
        <template v-if="mkForm.type === 2">
          <el-table-column prop="price" label="价格" width="100">
            <template #default="{ row }">
              ¥{{ row.price }}
            </template>
          </el-table-column>
          <el-table-column prop="teacher_name" label="讲师" width="120" />
          <el-table-column prop="desc" label="描述" width="150" show-overflow-tooltip />
        </template>
        
        <!-- 课程相关列 -->
        <template v-if="mkForm.type === 3">
          <el-table-column prop="price" label="价格" width="100">
            <template #default="{ row }">
              ¥{{ row.price }}
            </template>
          </el-table-column>
          <el-table-column prop="teacherName" label="讲师" width="120" />
          <el-table-column prop="isFree" label="是否免费" width="100">
            <template #default="{ row }">
              <el-tag :type="row.isFree === 1 ? 'success' : 'info'">
                {{ row.isFree === 1 ? '免费' : '付费' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '上架' : '下架' }}
              </el-tag>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleSelectItemClose">取消</el-button>
          <el-button type="primary" @click="confirmSelectItem" :disabled="!selectedItem">确定</el-button>
        </span>
      </template>
    </el-dialog>


    <!-- 选择导出域名弹窗 -->
    <el-dialog
      v-model="exportDialogVisible"
      title="选择导出域名"
      width="500px"
      :before-close="handleExportClose"
    >
      <el-form label-width="100px">
        <el-form-item label="域名">
          <el-select v-model="selectedDomainId" placeholder="请选择域名" style="width: 100%" :loading="domainOptionsLoading">
            <el-option
              v-for="d in domainOptions"
              :key="d.ID"
              :label="`${d.name}（${d.domain_url}）`"
              :value="d.ID"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleExportClose">取消</el-button>
          <el-button type="primary" :disabled="!selectedDomainId" @click="confirmExportMk">确定</el-button>
        </span>
      </template>
    </el-dialog>


  </div>
</template>

<script setup>
import { 
  mkList, 
  addMk, 
  editMk, 
  delMk,
  exportMk
} from '@/api/cdk/index.js'
import { list as vipList } from '@/api/goods/vip.js'
import { list as teacherVipList } from '@/api/goods/teacherVip.js'
import { list as goodsList } from '@/api/goods/index.js'
import { list as domainList } from '@/api/domain.js'
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

defineOptions({
  name: 'CdkLibraryManagement'
})

const router = useRouter()

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

// 兑换码库相关数据
const mkTableLoading = ref(false)
const mkTableData = ref([])
const mkQueryParams = ref({
  page: 1,
  pageSize: 10
})
const mkTotal = ref(0)
const mkSearchForm = ref({
  codeName: ''
})



// 兑换码库弹窗相关
const mkDialogVisible = ref(false)
const mkFormRef = ref(null)
const mkForm = ref({
  ID: '',
  codeName: '',
  type: 1,
  item: ''
})
const mkDialogTitle = computed(() => mkForm.value.ID ? '编辑兑换码库' : '新增兑换码库')

// 选择项目相关
const selectItemDialogVisible = ref(false)
const itemOptions = ref([])
const itemOptionsLoading = ref(false)
const selectedItem = ref(null)
const selectedItemName = ref('')
const itemSearchKeyword = ref('')

// 过滤后的项目选项
const filteredItemOptions = computed(() => {
  if (!itemSearchKeyword.value) {
    return itemOptions.value
  }
  
  const keyword = itemSearchKeyword.value.toLowerCase()
  return itemOptions.value.filter(item => {
    const nameProp = getItemNameProp(mkForm.value.type)
    const name = item[nameProp]?.toLowerCase() || ''
    const teacherName = (item.teacher_name || item.teacherName || '').toLowerCase()
    const desc = (item.desc || '').toLowerCase()
    
    return name.includes(keyword) || 
           teacherName.includes(keyword) || 
           desc.includes(keyword) ||
           item.ID.toString().includes(keyword)
  })
})


// 导出相关
const exportDialogVisible = ref(false)
const exportingRow = ref(null)
const domainOptionsLoading = ref(false)
const domainOptions = ref([])
const selectedDomainId = ref('')





// 项目名称缓存
const itemNameCache = ref({})

// 表单验证规则
const mkRules = {
  codeName: [
    { required: true, message: '请输入兑换码库名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  item: [
    { required: true, message: '请选择对应的项目', trigger: 'change' }
  ]
}



// 获取类型文本
const getTypeText = (type) => {
  const typeMap = {
    1: 'VIP',
    2: '讲师VIP',
    3: '课程'
  }
  return typeMap[type] || '未知'
}

// 获取使用率
const getUsageRate = (used, total) => {
  if (!total || total === 0) return '0%'
  const rate = ((used || 0) / total * 100).toFixed(1)
  return `${rate}%`
}

// 获取项目标签
const getItemLabel = (type) => {
  const labelMap = {
    1: 'VIP套餐',
    2: '讲师VIP',
    3: '课程'
  }
  return labelMap[type] || '项目'
}

// 获取项目名称属性
const getItemNameProp = (type) => {
  const propMap = {
    1: 'name',
    2: 'title', 
    3: 'title'
  }
  return propMap[type] || 'name'
}

// 处理类型变化
const handleTypeChange = (type) => {
  // 清空已选择的项目
  mkForm.value.item = ''
  selectedItem.value = null
  selectedItemName.value = ''
  console.log('类型变更为:', getTypeText(type))
}

// 处理选择项目
const handleSelectItem = async () => {
  if (!mkForm.value.type) {
    ElMessage.warning('请先选择类型')
    return
  }
  
  await loadItemOptions()
  selectItemDialogVisible.value = true
}

// 加载项目选项
const loadItemOptions = async () => {
  itemOptionsLoading.value = true
  try {
    let res
    const params = { page: 1, pageSize: 1000 }
    
    switch (mkForm.value.type) {
      case 1: // VIP
        res = await vipList(params)
        break
      case 2: // 讲师VIP
        res = await teacherVipList(params)
        break
      case 3: // 课程
        res = await goodsList(params)
        break
      default:
        itemOptions.value = []
        return
    }
    
    if (res.code === 0) {
      itemOptions.value = res.data.list || []
    } else {
      ElMessage.error(res.msg || '获取数据失败')
      itemOptions.value = []
    }
  } catch (error) {
    console.error('加载项目选项失败:', error)
    ElMessage.error('加载数据失败')
    itemOptions.value = []
  } finally {
    itemOptionsLoading.value = false
  }
}

// 处理项目行点击
const handleItemRowClick = (row) => {
  selectedItem.value = row
}

// 确认选择项目
const confirmSelectItem = () => {
  if (!selectedItem.value) {
    ElMessage.warning('请选择一个项目')
    return
  }
  
  mkForm.value.item = selectedItem.value.ID
  const nameProp = getItemNameProp(mkForm.value.type)
  selectedItemName.value = selectedItem.value[nameProp]
  
  handleSelectItemClose()
}

// 关闭选择项目弹窗
const handleSelectItemClose = () => {
  selectItemDialogVisible.value = false
  selectedItem.value = null
  itemSearchKeyword.value = ''
}

// 处理项目搜索
const handleItemSearch = () => {
  // 搜索逻辑已在 computed 中处理
}

// 获取项目显示名称
const getItemDisplayName = (row) => {
  const cacheKey = `${row.type}_${row.item}`
  if (itemNameCache.value[cacheKey]) {
    return itemNameCache.value[cacheKey]
  }
  return `ID: ${row.item}`
}

// 加载项目名称缓存
const loadItemNameCache = async () => {
  try {
    // 获取所有类型的数据并缓存名称
    const [vipRes, teacherVipRes, goodsRes] = await Promise.all([
      vipList({ page: 1, pageSize: 1000 }),
      teacherVipList({ page: 1, pageSize: 1000 }),
      goodsList({ page: 1, pageSize: 1000 })
    ])
    
    // 缓存VIP名称
    if (vipRes.code === 0 && vipRes.data.list) {
      vipRes.data.list.forEach(item => {
        itemNameCache.value[`1_${item.ID}`] = item.name
      })
    }
    
    // 缓存讲师VIP名称
    if (teacherVipRes.code === 0 && teacherVipRes.data.list) {
      teacherVipRes.data.list.forEach(item => {
        itemNameCache.value[`2_${item.ID}`] = item.title
      })
    }
    
    // 缓存课程名称
    if (goodsRes.code === 0 && goodsRes.data.list) {
      goodsRes.data.list.forEach(item => {
        itemNameCache.value[`3_${item.ID}`] = item.title
      })
    }
  } catch (error) {
    console.error('加载项目名称缓存失败:', error)
  }
}



// 兑换码库相关方法
const searchMkData = () => {
  mkQueryParams.value.page = 1
  getMkList()
}

const resetMkData = () => {
  mkSearchForm.value = {
    codeName: ''
  }
  mkQueryParams.value = {
    page: 1,
    pageSize: 10
  }
  getMkList()
}

const handleMkSizeChange = (size) => {
  mkQueryParams.value.pageSize = size
  getMkList()
}

const handleMkCurrentChange = (page) => {
  mkQueryParams.value.page = page
  getMkList()
}

async function getMkList() {
  mkTableLoading.value = true
  try {
    const params = {
      ...mkQueryParams.value,
      ...mkSearchForm.value
    }
    const res = await mkList(params)
    if (res.code === 0) {
      mkTableData.value = res.data.list || []
      mkTotal.value = res.data.total || 0
    }
  } finally {
    mkTableLoading.value = false
  }
}

// 获取兑换码库选项
async function getMkOptions() {
  try {
    const res = await mkList({ page: 1, pageSize: 1000 })
    if (res.code === 0) {
      mkOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取兑换码库选项失败:', error)
  }
}

const handleAddMk = () => {
  mkForm.value = {
    codeName: '',
    type: 1,
    item: ''
  }
  selectedItemName.value = ''
  selectedItem.value = null
  mkDialogVisible.value = true
}

const handleEditMk = async (row) => {
  mkForm.value = {
    ID: row.ID,
    codeName: row.codeName,
    type: row.type,
    item: row.item
  }
  
  // 获取已选择项目的名称
  await loadItemOptions()
  const nameProp = getItemNameProp(row.type)
  const selectedItemData = itemOptions.value.find(item => item.ID === row.item)
  selectedItemName.value = selectedItemData ? selectedItemData[nameProp] : `ID: ${row.item}`
  
  mkDialogVisible.value = true
}

const handleManageCdk = (row) => {
  // 跳转到兑换码管理页面，传递兑换码库ID和名称
  router.push({
    path: 'cdkManage',
    query: {
      id: row.ID,
      name: encodeURIComponent(row.codeName)
    }
  })
}



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

const handleMkClose = () => {
  mkDialogVisible.value = false
  mkFormRef.value?.resetFields()
  selectedItemName.value = ''
  selectedItem.value = null
}

// 导出：打开域名选择
const handleExportMk = async (row) => {
  exportingRow.value = row
  await loadDomainOptions()
  exportDialogVisible.value = true
}

const handleExportClose = () => {
  exportDialogVisible.value = false
  exportingRow.value = null
  selectedDomainId.value = ''
}

const loadDomainOptions = async () => {
  domainOptionsLoading.value = true
  try {
    const res = await domainList({ page: 1, pageSize: 1000, status: 1 })
    if (res.code === 0) {
      domainOptions.value = res.data.list || []
    } else {
      domainOptions.value = []
    }
  } catch (e) {
    domainOptions.value = []
  } finally {
    domainOptionsLoading.value = false
  }
}

const confirmExportMk = async () => {
  if (!exportingRow.value || !selectedDomainId.value) return
  try {
    const domainRow = domainOptions.value.find(d => d.ID === selectedDomainId.value)
    const domain = domainRow?.domain_url
    if (!domain) {
      ElMessage.error('请选择有效域名')
      return
    }
    const resp = await exportMk({ eid: exportingRow.value.ID, domain })
    // 兼容拦截器：Blob时返回整个响应对象；错误时可能是JSON结构
    let blob = resp?.data instanceof Blob ? resp.data : (resp instanceof Blob ? resp : null)
    if (!blob) {
      if (resp && typeof resp.code !== 'undefined') {
        ElMessage.error(resp.msg || '导出失败')
      } else {
        ElMessage.error('导出失败')
      }
      return
    }
    // 若后端以JSON错误通过blob返回
    if (blob.type && blob.type.includes('application/json')) {
      const text = await blob.text()
      try {
        const json = JSON.parse(text)
        ElMessage.error(json.msg || '导出失败')
      } catch (_) {
        ElMessage.error('导出失败')
      }
      return
    }
    // 尝试解析文件名
    let filename = (exportingRow.value.codeName || '兑换码库') + '.xlsx'
    try {
      const disposition = resp?.headers?.['content-disposition'] || resp?.headers?.['Content-Disposition']
      if (disposition) {
        const match = /filename\*=UTF-8''([^;]+)|filename=("?)([^";]+)\2/i.exec(disposition)
        const raw = decodeURIComponent(match?.[1] || match?.[3] || '')
        if (raw) filename = raw
      }
    } catch (_) {}
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = filename
    document.body.appendChild(a)
    a.click()
    a.remove()
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
    handleExportClose()
  } catch (e) {
    ElMessage.error('导出失败')
  }
}

const submitMk = async () => {
  if (!mkFormRef.value) return
  await mkFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const isEdit = !!mkForm.value.ID
        const res = isEdit ? await editMk(mkForm.value) : await addMk(mkForm.value)
        
        if (res.code === 0) {
          ElMessage.success(isEdit ? '编辑成功' : '新增成功')
          handleMkClose()
          getMkList()
        } else {
          ElMessage.error(res.msg || (isEdit ? '编辑失败' : '新增失败'))
        }
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
  })
}

// 兑换码相关方法
const searchCdkData = () => {
  cdkQueryParams.value.page = 1
  getCdkList()
}

const resetCdkData = () => {
  cdkSearchForm.value = {
    code: '',
    mkId: '',
    status: ''
  }
  cdkQueryParams.value = {
    page: 1,
    pageSize: 10
  }
  getCdkList()
}

const handleCdkSizeChange = (size) => {
  cdkQueryParams.value.pageSize = size
  getCdkList()
}

const handleCdkCurrentChange = (page) => {
  cdkQueryParams.value.page = page
  getCdkList()
}

async function getCdkList() {
  cdkTableLoading.value = true
  try {
    const params = {
      ...cdkQueryParams.value,
      ...cdkSearchForm.value
    }
    const res = await cdkList(params)
    if (res.code === 0) {
      cdkTableData.value = res.data.list || []
      cdkTotal.value = res.data.total || 0
    }
  } finally {
    cdkTableLoading.value = false
  }
}

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



// 页面初始化
onMounted(() => {
  loadItemNameCache()
  getMkList()
})
</script>

<style lang="scss" scoped>
.cdk-library-management {
  // 兑换码库管理样式
}

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

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

.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;
  }
}

.text-danger {
  color: #f56c6c;
  font-weight: bold;
}
</style>


