<template>
  <div class="voucher-history-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 label="关联信息ID">
          <el-input v-model="queryParams.id" placeholder="请输入关联信息ID" clearable style="width: 180px" />
        </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="success" @click="fetchHistoryList">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
  
      </div>
    </el-card>

    <!-- 使用记录列表 -->
    <el-card class="table-container" shadow="never">
      <el-table
        v-loading="loading"
        :data="historyList"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column prop="id" label="记录ID" width="80" fixed="left" />
        <el-table-column label="用户ID" width="100">
          <template #default="{ row }">
            <el-link v-if="row.user_id" type="primary" :underline="false" @click="router.push({ path: '/user/detail', query: { user_id: row.user_id } })">{{ row.user_id }}</el-link>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="email" label="邮箱" min-width="200" />
        <el-table-column prop="discount_id" label="代金券ID" width="120" v-if="!codeId" />
        <el-table-column prop="discount_name" label="代金券名称" min-width="180" v-if="!codeId" />
        <el-table-column label="优惠金额" width="120">
          <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 label="订单金额" width="120">
          <template #default="{ row }">
            <span>¥{{ row.order_amount ? (row.order_amount / 100).toFixed(2) : '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单ID" width="150">
          <template #default="{ row }">
            <el-link v-if="row.order_id" type="primary" :underline="false" @click="router.push({ path: '/order/list', query: { key: row.order_id } })">{{ row.order_id }}</el-link>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="使用状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="使用时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.used_at) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(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="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="记录ID">{{ currentDetail.id }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentDetail.user_id }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ currentDetail.username }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ currentDetail.email }}</el-descriptions-item>
        <el-descriptions-item label="代金券ID">{{ currentDetail.discount_id }}</el-descriptions-item>
        <el-descriptions-item label="代金券名称">{{ 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="订单金额">
          <span>¥{{ currentDetail.order_amount ? (currentDetail.order_amount / 100).toFixed(2) : '0.00' }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="订单ID" :span="2">{{ currentDetail.order_id || '-' }}</el-descriptions-item>
        <el-descriptions-item label="使用状态">
          <el-tag :type="getStatusType(currentDetail.status)">
            {{ getStatusText(currentDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="使用时间">{{ formatDate(currentDetail.used_at) }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ formatDate(currentDetail.created_at) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">{{ formatDate(currentDetail.updated_at) }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentDetail.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button type="primary" @click="detailDialogVisible = false">确定</el-button>
      </template>
    </el-dialog>
    <!-- 用户选择弹窗 -->
    <UserSelector
      v-model:visible="userSelectorVisible"
      @select="confirmUserSelection"
    />

    <!-- 统计卡片 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="6">
        <el-card shadow="hover">
          <el-statistic title="总使用次数" :value="statistics.totalCount">
            <template #suffix>次</template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <el-statistic title="总优惠金额" :value="(statistics.totalAmount / 100).toFixed(2)">
            <template #prefix>¥</template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <el-statistic title="成功使用" :value="statistics.successCount">
            <template #suffix>次</template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <el-statistic title="失败/取消" :value="statistics.failedCount">
            <template #suffix>次</template>
          </el-statistic>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Download } from '@element-plus/icons-vue'
import { getUserVoucherHistory, getDiscountCodeList } from '@/api/admin/discount'
import { getUserList } from '@/api/admin/user'
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,
  id: '',
  page: 1,
  count: 10
})

watch(() => props.codeId, (newVal) => {
  if (newVal) {
    queryParams.code_id = newVal
    fetchHistoryList()
  }
})

// 状态数据
const loading = ref(false)
const historyList = ref([])
const total = ref(0)
const detailDialogVisible = ref(false)
const currentDetail = ref({})
// const userOptions = ref([])
const discountOptions = ref([])
const selectorType = ref('query') 
const userSelectorVisible = ref(false)
const UserOptions = ref([])

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  const year = date.getFullYear()
  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')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

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

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

// 统计数据
const statistics = computed(() => {
  const stats = {
    totalCount: historyList.value.length,
    totalAmount: 0,
    successCount: 0,
    failedCount: 0
  }
  
  historyList.value.forEach(item => {
    if (item.status === 1) {
      stats.successCount++
      stats.totalAmount += item.discount_amount || 0
    } else if (item.status === 2 || item.status === 3) {
      stats.failedCount++
    }
  })
  
  return stats
})
// 获取查询用户名称
const getQueryUserName = () => {
  const user = UserOptions.value.find(u => u.UserId === queryParams.user_id)
  return user ? `${user.UserName} (ID: ${user.UserId})` : `用户ID: ${queryParams.user_id}`
}

// 获取使用记录列表
const fetchHistoryList = async () => {
  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 getUserVoucherHistory(params)
    console.log('使用记录数据:', res.data)
    if (res.data.code === 200) {
      historyList.value = res.data.data?.list || []
      total.value = res.data.data?.all_count || 0
    } else {
      ElMessage.error(res.data.message || '获取使用记录失败')
    }
  } catch (error) {
    console.error('获取使用记录失败:', error)
    ElMessage.error('获取使用记录失败')
  } finally {
    loading.value = false
  }
}
// 清除查询用户
const clearQueryUser = () => {
  queryParams.user_id = undefined
}
// 重置用户搜索
const resetUserSearch = () => {
  userSearchParams.key = ''
  userSearchParams.page = 1
  // fetchUserSelectorList()
}


// 打开查询用户选择器
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.UserId
  } else {
    // 编辑表单选择
    editForm.user_id = user.UserId
  }
  
  // 将选中的用户添加到 UserOptions 中（如果不存在）
  if (!UserOptions.value.find(u => u.UserId === user.UserId)) {
    UserOptions.value.push(user)
  }
  
  userSelectorVisible.value = false
  ElMessage.success('用户选择成功')
}

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

// 重置查询
const resetQuery = () => {
  queryParams.user_id = undefined
  queryParams.code_id = undefined
  queryParams.id = ''
  queryParams.page = 1
  fetchHistoryList()
}

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

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

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

// 导出
const handleExport = () => {
  if (historyList.value.length === 0) {
    ElMessage.warning('暂无数据可导出')
    return
  }
  
  ElMessage.info('导出功能开发中...')
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    const res = await getUserList({
      page: 1,
      count: 10,
      key: ''
    })
    UserOptions.value = res.data.data?.data || []
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

// 获取代金券列表
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)
  }
}

// 初始化
onMounted(() => {
  fetchUserList()
  fetchDiscountList()
  // 默认加载第一页数据
  // fetchHistoryList()
})
</script>

<style scoped>
.voucher-history-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;
}

:deep(.el-statistic__head) {
  color: #606266;
  font-size: 14px;
}

:deep(.el-statistic__number) {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}
</style>

