<template>
  <el-dialog
    v-model="visible"
    title="用户订单"
    width="1100px"
    :close-on-click-modal="false"
    @close="handleClose"
    @open="handleOpen"
  >
    <div class="user-info" v-if="user">
      <el-avatar :src="user.avatar" :size="40">
        <el-icon><User /></el-icon>
      </el-avatar>
      <div class="user-detail">
        <div class="nickname">{{ user.nickname || '-' }}</div>
        <div class="uid">UID: {{ user.id }}</div>
      </div>
    </div>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="queryParams" class="search-form">
      <el-form-item label="订单状态">
        <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 120px">
          <el-option label="待支付" :value="0" />
          <el-option label="已支付" :value="1" />
          <el-option label="已取消" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单编号">
        <el-input v-model="queryParams.orderNum" placeholder="订单编号" clearable style="width: 180px" />
      </el-form-item>
      <el-form-item label="下单时间">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="width: 240px"
          @change="handleDateChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 订单列表 -->
    <el-table :data="orderList" v-loading="loading" border stripe max-height="400">
      <el-table-column prop="orderNum" label="订单编号" min-width="180" />

      <el-table-column label="商品信息" min-width="200">
        <template #default="{ row }">
          <div class="goods-info">
            <el-image
              :src="row.goodsImgurl"
              style="width: 50px; height: 50px"
              fit="cover"
              :preview-src-list="row.goodsImgurl ? [row.goodsImgurl] : []"
            />
            <div class="goods-detail">
              <div class="goods-title">{{ row.goodsTitle || '-' }}</div>
              <div class="goods-price">单价: ¥{{ row.goodsPrice?.toFixed(2) || '0.00' }}</div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="num" label="数量" width="80" align="center" />

      <el-table-column label="订单金额" width="120" align="right">
        <template #default="{ row }">
          <div class="order-money">
            <div class="total">¥{{ row.orderZheTotal?.toFixed(2) || '0.00' }}</div>
            <div class="original" v-if="row.orderTotal !== row.orderZheTotal">
              原价: ¥{{ row.orderTotal?.toFixed(2) }}
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="支付方式" width="120">
        <template #default="{ row }">
          <div class="pay-info">
            <div v-if="row.useMoney > 0">余额: ¥{{ row.useMoney?.toFixed(2) }}</div>
            <div v-if="row.useIntegral > 0">积分: {{ row.useIntegral }}</div>
            <div v-if="row.useScore > 0">钻石: {{ row.useScore }}</div>
            <div v-if="row.useCoupon">优惠券: {{ row.useCoupon }}</div>
            <div v-if="!row.useMoney && !row.useIntegral && !row.useScore && !row.useCoupon">
              {{ row.payTypeText || '-' }}
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="prizeNum" label="中奖数" width="80" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.prizeNum > 0" type="success" size="small">{{ row.prizeNum }}</el-tag>
          <span v-else class="text-muted">0</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)" size="small">
            {{ row.statusText || getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="createdAt" label="下单时间" width="170" />

      <el-table-column prop="payTime" label="支付时间" width="170">
        <template #default="{ row }">
          {{ row.payTime || '-' }}
        </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="fetchData"
      @current-change="fetchData"
      class="pagination"
    />

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { User } from '@element-plus/icons-vue'
import { getUserOrders, type UserListItem, type UserOrderQuery, type UserOrderItem } from '@/api/business/user'

interface Props {
  modelValue: boolean
  user: UserListItem | null
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const loading = ref(false)
const orderList = ref<UserOrderItem[]>([])
const total = ref(0)
const dateRange = ref<[string, string] | null>(null)

const queryParams = reactive<UserOrderQuery>({
  status: undefined,
  orderNum: undefined,
  startTime: undefined,
  endTime: undefined,
  page: 1,
  pageSize: 20
})

// 获取状态标签类型
const getStatusType = (status: number) => {
  const types: Record<number, string> = {
    0: 'warning',  // 待支付
    1: 'success',  // 已支付
    2: 'info'      // 已取消
  }
  return types[status] || ''
}

// 获取状态文本
const getStatusText = (status: number) => {
  const texts: Record<number, string> = {
    0: '待支付',
    1: '已支付',
    2: '已取消'
  }
  return texts[status] || '未知'
}

// 日期范围变化
const handleDateChange = (val: [string, string] | null) => {
  if (val) {
    queryParams.startTime = val[0]
    queryParams.endTime = val[1]
  } else {
    queryParams.startTime = undefined
    queryParams.endTime = undefined
  }
}

// 获取数据
const fetchData = async () => {
  if (!props.user) return

  loading.value = true
  try {
    const res = await getUserOrders(props.user.id, queryParams)
    orderList.value = res.data?.list || []
    total.value = res.data?.total || 0
  } catch (error) {
    console.error('获取用户订单失败', error)
    orderList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  queryParams.status = undefined
  queryParams.orderNum = undefined
  queryParams.startTime = undefined
  queryParams.endTime = undefined
  dateRange.value = null
  queryParams.page = 1
  fetchData()
}

// 对话框打开时
const handleOpen = () => {
  handleReset()
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 16px;
}

.user-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.nickname {
  font-weight: 500;
  font-size: 14px;
}

.uid {
  font-size: 12px;
  color: #909399;
}

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

.goods-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.goods-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.goods-title {
  font-weight: 500;
}

.goods-price {
  font-size: 12px;
  color: #909399;
}

.order-money .total {
  color: #e6a23c;
  font-weight: 500;
}

.order-money .original {
  font-size: 12px;
  color: #909399;
  text-decoration: line-through;
}

.pay-info {
  font-size: 12px;
  line-height: 1.6;
}

.text-muted {
  color: #909399;
}

.pagination {
  margin-top: 16px;
  justify-content: flex-end;
}
</style>
