<template>
  <div class="voucher-holders-container">
    <!-- 搜索和操作栏 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="用户">
          <div class="user-selector-inline">
            <el-tag v-if="queryParams.user_id" type="primary" closable @close="clearQueryUser" style="margin-right: 8px">
              {{ getQueryUserName() }}
            </el-tag>
            <el-button type="primary" plain @click="openQueryUserSelector" size="default">
              <el-icon><User /></el-icon>
              {{ queryParams.user_id ? '重新选择' : '选择用户' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="action-bar">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加代金券
        </el-button>
        <el-button type="success" @click="fetchHoldersList">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
       
      </div>
    </el-card>

    <!-- 拥有者列表 -->
    <el-card class="table-container" shadow="never">
      <el-table
        v-loading="loading"
        :data="holdersList"
        style="width: 100%"
      >
        <el-table-column prop="Id" label="ID" width="80" />
        <el-table-column label="用户ID" min-width="100">
          <template #default="{ row }">
            <el-link v-if="row.UserId" type="primary" :underline="false" @click="router.push({ path: '/user/detail', query: { user_id: row.UserId } })">{{ row.UserId }}</el-link>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="代金券ID" min-width="110" v-if="!codeId">
          <template #default="{ row }">
            {{ row.discountId || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="代金券名称" min-width="180" v-if="!codeId" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.discount?.name || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="代金券编码" min-width="150" v-if="!codeId">
          <template #default="{ row }">
            {{ row.discount?.code || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="面额" min-width="110">
          <template #default="{ row }">
            <span class="amount">¥{{ row.discount?.amount ? (row.discount.amount / 100).toFixed(2) : '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="useTimes" label="已使用" min-width="100" />
        <el-table-column prop="maxUseTimes" label="最大使用" min-width="100" />
        <el-table-column label="状态" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row)" size="small">
              {{ getStatusText(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="过期时间" min-width="160">
          <template #default="{ row }">
            {{ formatDate(row.expireAt) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="160">
          <template #default="{ row }">
            {{ formatDate(row.CreatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="210" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleView(row)">查看</el-button>
            <el-button type="warning" link size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.count"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        class="pagination"
      />
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="拥有者详情"
      width="700px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="记录ID">{{ currentDetail.Id }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentDetail.UserId }}</el-descriptions-item>
        <el-descriptions-item label="代金券ID">{{ currentDetail.discountId }}</el-descriptions-item>
        <el-descriptions-item label="代金券编码">{{ currentDetail.discount?.code || '-' }}</el-descriptions-item>
        <el-descriptions-item label="代金券名称" :span="2">{{ currentDetail.discount?.name || '-' }}</el-descriptions-item>
        <el-descriptions-item label="面额">
          <span class="amount">¥{{ currentDetail.discount?.amount ? (currentDetail.discount.amount / 100).toFixed(2) : '0.00' }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="最低消费">
          ¥{{ currentDetail.discount?.minAmount ? (currentDetail.discount.minAmount / 100).toFixed(2) : '0.00' }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentDetail)">
            {{ getStatusText(currentDetail) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="类型">
          {{ currentDetail.discount?.type === 'coupon' ? '代金券' : '优惠码' }}
        </el-descriptions-item>
        <el-descriptions-item label="已使用次数">{{ currentDetail.useTimes || 0 }}</el-descriptions-item>
        <el-descriptions-item label="最大使用次数">{{ currentDetail.maxUseTimes || '无限制' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ formatDate(currentDetail.CreatedAt) }}</el-descriptions-item>
        <el-descriptions-item label="过期时间" :span="2">{{ formatDate(currentDetail.expireAt) }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentDetail.discount?.note || '-' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button type="primary" @click="detailDialogVisible = false">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑代金券对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="dialogType === 'add' ? '添加代金券' : '编辑代金券'"
      width="600px"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="120px"
      >
        <el-form-item label="用户" prop="user_id" v-if="dialogType === 'add'">
          <div class="user-selector-wrapper">
            <div class="selected-user-display" v-if="editForm.user_id">
              <el-tag type="primary" closable @close="clearEditUser">
                {{ getEditUserName() }}
              </el-tag>
            </div>
            <el-button 
              type="primary" 
              plain 
              @click="openEditUserSelector"
              style="width: 100%"
            >
              <el-icon><User /></el-icon>
              {{ editForm.user_id ? '重新选择用户' : '选择用户' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="代金券" prop="discount_id">
          <el-select v-model="editForm.discount_id" placeholder="请选择代金券" filterable style="width: 100%" >
            <el-option v-for="item in discountOptions" :key="item.id" :label="`${item.name} (¥${(item.amount/100).toFixed(2)})`" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="已使用次数" prop="use_times" v-if="dialogType === 'edit'">
          <el-input-number v-model="editForm.use_times" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="最大使用次数" prop="max_use_times" v-if="dialogType === 'edit'">
          <el-input-number v-model="editForm.max_use_times" :min="0" placeholder="0表示无限制" style="width: 100%" />
        </el-form-item>
        <el-form-item label="过期时间" prop="expire_at" v-if="dialogType === 'edit'">
          <el-date-picker
            v-model="editForm.expire_at"
            type="datetime"
            placeholder="选择过期时间"
            format="YYYY-MM-DD HH:mm:ss"
            :teleported="true"
            placement="top-start"
            :editable="true"
            :clearable="true"
            value-format="X"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 用户选择弹窗 -->
    <UserSelector
      v-model:visible="userSelectorVisible"
      @select="confirmUserSelection"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, User } from '@element-plus/icons-vue'
import { 
  getUserVoucherList, 
  allocateVoucher, 
  updateUserVoucher, 
  deleteUserVoucher,
  getDiscountCodeList
} from '@/api/admin/discount'
import UserSelector from '@/components/UserSelector/index.vue'

const props = defineProps({
  codeId: {
    type: [String, Number],
    default: ''
  }
})

const router = useRouter()

// 查询参数
const queryParams = reactive({
  user_id: undefined,
  code_id: props.codeId || undefined,
  page: 1,
  count: 10
})

watch(() => props.codeId, (newVal) => {
  if (newVal) {
    queryParams.code_id = newVal
    // 如果有 code_id，尝试刷新列表（取决于 API 是否支持仅按 code_id 查询）
    // 如果 API 必须要求 user_id，则这里可能不需要立即刷新，或者提示用户选择用户
    if (queryParams.user_id) {
      fetchHoldersList()
    }
  }
})

// 状态数据
const loading = ref(false)
const holdersList = ref([])
const total = ref(0)
const detailDialogVisible = ref(false)
const currentDetail = ref({})
const UserOptions = ref([])
const editDialogVisible = ref(false)
const dialogType = ref('add')
const editFormRef = ref(null)
const discountOptions = ref([])

// 用户选择弹窗相关
const userSelectorVisible = ref(false)
const selectorType = ref('query')  // 'query' 或 'edit' 用于区分是查询还是编辑

// 编辑表单
const editForm = reactive({
  user_id: undefined,
  discount_id: undefined,
  id: undefined,
  use_times: 0,
  max_use_times: 0,
  expire_at: undefined
})

// 表单验证规则
const editRules = {
  user_id: [{ required: true, message: '请选择用户', trigger: 'change' }],
  discount_id: [{ required: true, message: '请选择代金券', trigger: 'change' }]
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr || dateStr === '1970-01-01T08:01:40+08:00' || dateStr === '0001-01-01T00:00:00Z') return '-'
  const date = new Date(dateStr)
  if (isNaN(date.getTime())) return '-'
  const year = date.getFullYear()
  // 过滤掉1970年的日期（通常是零值）
  if (year === 1970) return '-'
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 获取状态文本
const getStatusText = (row) => {
  const now = Date.now()
  const expireAt = row.expireAt ? new Date(row.expireAt).getTime() : 0
  
  // 检查是否已用完
  if (row.useTimes >= row.maxUseTimes && row.maxUseTimes > 0) {
    return '已用完'
  }
  // 检查是否已过期（排除1970年的零值日期）
  if (expireAt > 0 && expireAt < now && new Date(row.expireAt).getFullYear() !== 1970) {
    return '已过期'
  }
  return '可使用'
}

// 获取状态标签类型
const getStatusType = (row) => {
  const now = Date.now()
  const expireAt = row.expireAt ? new Date(row.expireAt).getTime() : 0
  
  if (row.useTimes >= row.maxUseTimes && row.maxUseTimes > 0) {
    return 'info'
  }
  if (expireAt > 0 && expireAt < now && new Date(row.expireAt).getFullYear() !== 1970) {
    return 'warning'
  }
  return 'success'
}

// 获取拥有者列表
const fetchHoldersList = async () => {
  if (!queryParams.user_id) {
    ElMessage.warning('请选择用户ID进行查询')
    return
  }
  
  loading.value = true
  try {
    const params = { ...queryParams }
    // 清除空参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const res = await getUserVoucherList(params)
    console.log('拥有者列表数据:', res.data)
    if (res.data.code === 200) {
      holdersList.value = res.data.data?.data || []
      total.value = res.data.data?.all_count || 0
      console.log('解析后的列表数据:', holdersList.value)
    }
  } catch (error) {
    console.error('获取拥有者列表失败:', error)
    ElMessage.error('获取拥有者列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.page = 1
  fetchHoldersList()
}

// 重置查询
const resetQuery = () => {
  queryParams.code_id = ''
  queryParams.username = ''
  queryParams.page = 1
  holdersList.value = []
  total.value = 0
}

// 分页
const handleSizeChange = (size) => {
  queryParams.count = size
  fetchHoldersList()
}

const handleCurrentChange = (page) => {
  queryParams.page = page
  fetchHoldersList()
}

// 查看详情
const handleView = (row) => {
  currentDetail.value = { ...row }
  detailDialogVisible.value = true
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 打开查询用户选择器
const openQueryUserSelector = () => {
  selectorType.value = 'query'
  userSelectorVisible.value = true
}

// 打开编辑用户选择器
const openEditUserSelector = () => {
  selectorType.value = 'edit'
  userSelectorVisible.value = true
}

// 确认用户选择
const confirmUserSelection = (user) => {
  if (!user) {
    ElMessage.warning('请选择一个用户')
    return
  }
  
  if (selectorType.value === 'query') {
    queryParams.user_id = user.user_id
  } else {
    editForm.user_id = user.user_id
  }
  
  // 将选中的用户添加到 UserOptions 中（如果不存在）
  if (!UserOptions.value.find(u => u.user_id === user.user_id)) {
    UserOptions.value.push(user)
  }
  
  userSelectorVisible.value = false
  ElMessage.success('用户选择成功')
}

// 清除查询用户
const clearQueryUser = () => {
  queryParams.user_id = undefined
}

// 清除编辑用户
const clearEditUser = () => {
  editForm.user_id = undefined
}

// 获取查询用户名称
const getQueryUserName = () => {
  const user = UserOptions.value.find(u => u.user_id === queryParams.user_id)
  return user ? `${user.user_name} (ID: ${user.user_id})` : `用户ID: ${queryParams.user_id}`
}

// 获取编辑用户名称
const getEditUserName = () => {
  const user = UserOptions.value.find(u => u.user_id === editForm.user_id)
  return user ? `${user.user_name} (ID: ${user.user_id})` : `用户ID: ${editForm.user_id}`
}

// 获取代金券列表
const fetchDiscountList = async () => {
  try {
    const res = await getDiscountCodeList({
      discount_type: 'coupon',
      page: 1,
      count: 10
    })
    if (res.data.code === 200) {
      discountOptions.value = res.data.data?.data || []
    }
  } catch (error) {
    console.error('获取代金券列表失败:', error)
  }
}

// 添加代金券
const handleAdd = () => {
  dialogType.value = 'add'
  editDialogVisible.value = true
  Object.assign(editForm, {
    user_id: queryParams.user_id,
    discount_id: undefined,
    id: undefined,
    use_times: 0,
    max_use_times: 0,
    expire_at: undefined
  })
  editFormRef.value?.resetFields()
}

// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  editDialogVisible.value = true
  
  // 处理过期时间
  let expireTime = undefined
  if (row.expireAt && row.expireAt !== '1970-01-01T08:01:40+08:00' && row.expireAt !== '0001-01-01T00:00:00Z') {
    const date = new Date(row.expireAt)
    if (!isNaN(date.getTime()) && date.getFullYear() !== 1970) {
      expireTime = Math.floor(date.getTime() / 1000)
    }
  }
  
  Object.assign(editForm, {
    user_id: row.UserId,
    discount_id: row.discountId,
    id: row.Id,
    use_times: row.useTimes || 0,
    max_use_times: row.maxUseTimes || 0,
    expire_at: expireTime
  })
}

// 删除
const handleDelete = (row) => {
  const discountName = row.discount?.name || '该代金券'
  ElMessageBox.confirm(`确认删除用户ID ${row.UserId} 的代金券 ${discountName} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteUserVoucher({
        user_id: row.UserId,
        id: row.Id
      })
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        fetchHoldersList()
      } else {
        ElMessage.error(res.data.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }).catch(() => {})
}

// 提交表单
const submitEditForm = () => {
  editFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (dialogType.value === 'add') {
          // 使用 allocateVoucher 接口为用户添加代金券
          res = await allocateVoucher({
            user_id: editForm.user_id,
            code_id: editForm.discount_id
          })
        } else {
          res = await updateUserVoucher({
            user_id: editForm.user_id,
            id: editForm.id,
            discount_id: editForm.discount_id,
            use_times: editForm.use_times,
            max_use_times: editForm.max_use_times,
            expire_at: editForm.expire_at
          })
        }
        
        if (res.data.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
          editDialogVisible.value = false
          fetchHoldersList()
        } else {
          ElMessage.error(res.data.message || '操作失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    }
  })
}

// 初始化
onMounted(() => {
  fetchDiscountList()
  if (queryParams.user_id) {
    fetchHoldersList()
  }
})
</script>

<style scoped>
.voucher-holders-container {
  padding: 0;
}

.filter-container {
  margin-bottom: 20px;
  border-radius: 8px;
}

.search-form {
  margin-bottom: 15px;
}

.action-bar {
  display: flex;
  gap: 12px;
}

.table-container {
  border-radius: 8px;
}

.amount {
  color: #f56c6c;
  font-weight: bold;
  font-size: 14px;
}

.pagination {
  margin-top: 24px;
  justify-content: flex-end;
}

/* 用户选择器样式 */
.user-selector-inline {
  display: flex;
  align-items: center;
}

.user-selector-wrapper {
  width: 100%;
}

.selected-user-display {
  margin-bottom: 12px;
  padding: 8px 12px;
  background: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-selector-dialog .selector-search {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #ebeef5;
}

.selector-pagination {
  margin-top: 16px;
  justify-content: flex-end;
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row):hover {
  background-color: #f5f7fa;
}

:deep(.current-row) {
  background-color: #ecf5ff !important;
}
</style>

