<template>
  <div class="points-order-list-container">
    <h2 class="page-title">积分商城订单</h2>
    
    <!-- 工具栏 -->
    <el-card shadow="never" class="toolbar-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-space>
            <el-button type="primary" icon="Search" @click="loadList">查询</el-button>
            <el-button icon="Refresh" @click="resetFilters">重置</el-button>
          </el-space>
        </el-col>
        <el-col :span="18">
          <el-space style="justify-content: flex-end; width: 100%;">
            <el-input 
              v-model="filters.orderNo" 
              placeholder="订单号" 
              clearable 
              style="width: 180px" 
              @keyup.enter="loadList"
            />
            <el-input 
              v-model="filters.productName" 
              placeholder="产品名称" 
              clearable 
              style="width: 180px" 
              @keyup.enter="loadList"
            />
            <el-select 
              v-model="filters.review" 
              placeholder="审核状态" 
              clearable 
              style="width: 130px" 
              @change="loadList"
            >
              <el-option label="待审核" :value="0" />
              <el-option label="审核通过" :value="1" />
              <el-option label="审核未通过" :value="2" />
            </el-select>
            <el-select 
              v-model="filters.status" 
              placeholder="发货状态" 
              clearable 
              style="width: 130px" 
              @change="loadList"
            >
              <el-option label="待发货" :value="0" />
              <el-option label="已发货" :value="1" />
              <el-option label="已完成" :value="2" />
              <el-option label="已取消" :value="3" />
            </el-select>
          </el-space>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 列表 -->
    <el-card shadow="never" class="table-card">
      <el-table v-loading="loading" :data="list" stripe>
        <template #empty>
          <div class="custom-empty-state">
            <el-icon class="empty-icon"><Document /></el-icon>
            <div class="empty-text">暂无订单数据</div>
          </div>
        </template>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="orderNo" label="订单号" width="220" />
        <el-table-column prop="productName" label="产品名称" width="200" />
        <el-table-column prop="productImage" label="产品图片" width="100">
          <template #default="{ row }">
            <el-image 
              v-if="row.productImage" 
              :src="row.productImage" 
              style="width: 60px; height: 60px"
              fit="cover"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="pointsPrice" label="积分单价" width="100" align="center" />
        <el-table-column prop="quantity" label="数量" width="80" align="center" />
        <el-table-column prop="totalPoints" label="总积分" width="100" align="center" />
        <el-table-column prop="receiverName" label="收件人" width="100" />
        <el-table-column prop="receiverPhone" label="收件电话" width="130" />
        <el-table-column prop="receiverAddress" label="收件地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="review" label="审核状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getReviewType(row.review)" size="small">
              {{ getReviewText(row.review) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="发货状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="info" 
              size="small" 
              link 
              @click="handleDetail(row)"
            >
              详情
            </el-button>
            <el-button 
              type="primary" 
              size="small" 
              link 
              @click="handleReview(row)"
              :disabled="row.review === 1 || row.review === 2"
            >
              审核
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              link 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadList"
          @current-change="loadList"
        />
      </div>
    </el-card>

    <!-- 订单详情弹框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="订单详情" 
      width="800px"
      :close-on-click-modal="false"
    >
      <el-descriptions v-if="orderDetail" :column="2" border>
        <el-descriptions-item label="订单号" :span="2">
          {{ orderDetail.orderNo }}
        </el-descriptions-item>
        <el-descriptions-item label="产品名称" :span="2">
          {{ orderDetail.productName }}
        </el-descriptions-item>
        <el-descriptions-item label="产品图片" :span="2">
          <el-image 
            v-if="orderDetail.productImage" 
            :src="orderDetail.productImage" 
            style="width: 120px; height: 120px"
            fit="cover"
          />
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="积分单价">
          {{ orderDetail.pointsPrice }} 积分
        </el-descriptions-item>
        <el-descriptions-item label="数量">
          {{ orderDetail.quantity }}
        </el-descriptions-item>
        <el-descriptions-item label="总积分" :span="2">
          <span style="color: #f56c6c; font-weight: bold;">{{ orderDetail.totalPoints }} 积分</span>
        </el-descriptions-item>
        <el-descriptions-item label="审核状态" :span="2">
          <el-tag :type="getReviewType(orderDetail.review)" size="small">
            {{ getReviewText(orderDetail.review) }}
          </el-tag>
          <span v-if="orderDetail.review === 2 && orderDetail.reviewFail" style="margin-left: 10px; color: #f56c6c;">
            （{{ orderDetail.reviewFail }}）
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="发货状态" :span="2">
          <el-tag :type="getStatusType(orderDetail.status)" size="small">
            {{ getStatusText(orderDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="收件人姓名">
          {{ orderDetail.receiverName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="收件人电话">
          {{ orderDetail.receiverPhone || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="收件地址" :span="2">
          {{ orderDetail.receiverAddress || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="快递公司" :span="2">
          {{ orderDetail.expressCompany || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="快递单号" :span="2">
          {{ orderDetail.expressNo || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">
          {{ orderDetail.createTime || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">
          {{ orderDetail.updateTime || '-' }}
        </el-descriptions-item>
      </el-descriptions>
      <div v-else class="loading-container">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span style="margin-left: 10px;">加载中...</span>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 审核弹框 -->
    <el-dialog 
      v-model="reviewDialogVisible" 
      title="订单审核" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="reviewForm" label-width="120px">
        <el-form-item label="订单号">
          <el-input v-model="reviewForm.orderNo" disabled />
        </el-form-item>
        <el-form-item label="收件人姓名">
          <el-input v-model="reviewForm.receiverName" disabled />
        </el-form-item>
        <el-form-item label="收件人电话">
          <el-input v-model="reviewForm.receiverPhone" disabled />
        </el-form-item>
        <el-form-item label="收件地址">
          <el-input v-model="reviewForm.receiverAddress" type="textarea" :rows="2" disabled />
        </el-form-item>
        <el-form-item label="审核结果" required>
          <el-radio-group v-model="reviewForm.review">
            <el-radio :label="1">审核通过</el-radio>
            <el-radio :label="2">审核不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item 
          v-if="reviewForm.review === 2" 
          label="审核失败说明" 
          required
        >
          <el-input 
            v-model="reviewForm.reviewFail" 
            type="textarea" 
            :rows="4"
            placeholder="请输入审核失败的原因"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitReview"
          :loading="reviewLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Loading } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { API_ENDPOINTS } from '@/config/api'

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const list = ref([])

const filters = reactive({
  orderNo: '',
  productName: '',
  review: null,
  status: null
})

const detailDialogVisible = ref(false)
const detailLoading = ref(false)
const orderDetail = ref(null)

const reviewDialogVisible = ref(false)
const reviewLoading = ref(false)
const reviewForm = reactive({
  id: null,
  orderNo: '',
  receiverName: '',
  receiverPhone: '',
  receiverAddress: '',
  review: 1,
  reviewFail: ''
})

const loadList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    if (filters.orderNo && filters.orderNo.trim()) {
      params.orderNo = filters.orderNo.trim()
    }
    if (filters.productName && filters.productName.trim()) {
      params.productName = filters.productName.trim()
    }
    if (filters.review !== null && filters.review !== undefined) {
      params.review = filters.review
    }
    if (filters.status !== null && filters.status !== undefined) {
      params.status = filters.status
    }
    
    const response = await request.get(API_ENDPOINTS.POINTS_ORDER_LIST, { params })
    
    if (response.code === 200) {
      const data = response.data || {}
      list.value = data.list || data.records || []
      total.value = data.total || 0
    } else {
      ElMessage.error(response.message || response.msg || '加载失败')
      list.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载失败:', error)
    ElMessage.error('加载失败: ' + (error.message || '未知错误'))
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const resetFilters = () => {
  filters.orderNo = ''
  filters.productName = ''
  filters.review = null
  filters.status = null
  currentPage.value = 1
  loadList()
}

const getReviewText = (review) => {
  const texts = { 0: '待审核', 1: '审核通过', 2: '审核未通过' }
  return texts[review] || '未知'
}

const getReviewType = (review) => {
  const types = { 0: 'warning', 1: 'success', 2: 'danger' }
  return types[review] || ''
}

const getStatusText = (status) => {
  const texts = { 0: '待发货', 1: '已发货', 2: '已完成', 3: '已取消' }
  return texts[status] || '未知'
}

const getStatusType = (status) => {
  const types = { 0: 'warning', 1: 'info', 2: 'success', 3: 'danger' }
  return types[status] || ''
}

const handleReview = (row) => {
  reviewForm.id = row.id
  reviewForm.orderNo = row.orderNo || ''
  reviewForm.receiverName = row.receiverName || ''
  reviewForm.receiverPhone = row.receiverPhone || ''
  reviewForm.receiverAddress = row.receiverAddress || ''
  reviewForm.review = 1
  reviewForm.reviewFail = ''
  reviewDialogVisible.value = true
}

const submitReview = async () => {
  if (!reviewForm.review) {
    ElMessage.warning('请选择审核结果')
    return
  }
  
  if (reviewForm.review === 2 && !reviewForm.reviewFail?.trim()) {
    ElMessage.warning('审核不通过时必须填写审核失败说明')
    return
  }
  
  reviewLoading.value = true
  try {
    const params = {
      review: reviewForm.review
    }
    if (reviewForm.review === 2) {
      params.reviewFail = reviewForm.reviewFail.trim()
    }
    
    const response = await request.post(
      `${API_ENDPOINTS.POINTS_ORDER_REVIEW}/${reviewForm.id}`,
      null,
      { params }
    )
    
    if (response.code === 200) {
      ElMessage.success('审核成功')
      reviewDialogVisible.value = false
      loadList()
    } else {
      ElMessage.error(response.message || response.msg || '审核失败')
    }
  } catch (error) {
    console.error('审核失败:', error)
    ElMessage.error(error.response?.data?.message || error.message || '审核失败')
  } finally {
    reviewLoading.value = false
  }
}

const handleDetail = async (row) => {
  detailDialogVisible.value = true
  detailLoading.value = true
  orderDetail.value = null
  
  try {
    const response = await request.get(`${API_ENDPOINTS.POINTS_ORDER_DETAIL}/${row.id}`)
    
    if (response.code === 200) {
      orderDetail.value = response.data
    } else {
      ElMessage.error(response.message || response.msg || '获取订单详情失败')
      detailDialogVisible.value = false
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error(error.response?.data?.message || error.message || '获取订单详情失败')
    detailDialogVisible.value = false
  } finally {
    detailLoading.value = false
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个订单吗？删除后订单将不再显示。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await request.delete(`${API_ENDPOINTS.POINTS_ORDER_DELETE}/${row.id}`)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadList()
    } else {
      ElMessage.error(response.message || response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.response?.data?.message || error.message || '删除失败')
    }
  }
}

onMounted(() => loadList())
</script>

<style scoped>
.points-order-list-container {
  padding: 20px;
}

.page-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.toolbar-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}
</style>

