<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh, View } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrderPageApi, deliverOrderApi, cancelOrderApi } from '@/api/order'
import type { OrderItem } from '@/api/order'
import { ORDER_STATUS_MAP } from '@/utils/dict'
import { formatDate } from '@/utils/date'
import SearchBar from '@/components/common/SearchBar.vue'

const loading = ref(false)
const list = ref<OrderItem[]>([])
const total = ref(0)

const query = reactive({
  current: 1,
  size: 10,
  keyword: '',
  status: undefined as 0 | 1 | 2 | 3 | 4 | undefined
})

async function fetchData() {
  loading.value = true
  try {
    const res: any = await getOrderPageApi(query)
    list.value = res.records
    total.value = res.total
  } finally {
    loading.value = false
  }
}

function statusClass(status: number) {
  return status === 1
    ? 'warning'
    : status === 2
      ? 'primary'
      : status === 3
        ? 'success'
        : status === 4
          ? 'info'
          : 'danger'
}

async function handleDeliver(row: any) {
  try {
    const { value } = await ElMessageBox.prompt(
      `请输入【${row.orderNo}】的物流单号`,
      '订单发货',
      { confirmButtonText: '发货', cancelButtonText: '取消' }
    )
    await deliverOrderApi(row.id, { company: '顺丰速运', trackingNo: value })
    ElMessage.success('发货成功')
    fetchData()
  } catch {
    /* cancel */
  }
}

async function handleCancel(row: any) {
  await ElMessageBox.confirm(`确定要取消订单【${row.orderNo}】吗？`, '提示', { type: 'warning' })
  await cancelOrderApi(row.id)
  ElMessage.success('已取消')
  fetchData()
}

onMounted(fetchData)
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <div>
        <h2>订单管理</h2>
        <p class="page-desc">查看和处理用户订单</p>
      </div>
    </div>

    <el-card shadow="never" class="table-card">
      <SearchBar show-divider>
        <el-input
          v-model="query.keyword"
          placeholder="订单号 / 收件人"
          :prefix-icon="Search"
          clearable
          style="width: 240px"
          @keyup.enter="fetchData"
        />
        <el-select v-model="query.status" placeholder="订单状态" clearable style="width: 140px">
          <el-option
            v-for="(s, k) in ORDER_STATUS_MAP"
            :key="k"
            :label="s.text"
            :value="Number(k)"
          />
        </el-select>
        <el-button type="primary" :icon="Search" @click="fetchData">搜索</el-button>
        <el-button :icon="Refresh" @click="query.keyword = ''; query.status = undefined; fetchData()">重置</el-button>
      </SearchBar>

      <el-table v-loading="loading" :data="list" stripe>
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="username" label="用户" width="100" />
        <el-table-column label="金额" width="120" align="right">
          <template #default="{ row }">
            <span class="amount">¥ {{ row.payAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="statusClass(row.status) as any" size="small">
              {{ ORDER_STATUS_MAP[row.status as keyof typeof ORDER_STATUS_MAP].text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="receiverName" label="收件人" width="100" />
        <el-table-column prop="receiverPhone" label="电话" width="140" />
        <el-table-column prop="createTime" label="下单时间" width="170">
          <template #default="{ row }">{{ formatDate(row.createTime) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="{ row }">
            <el-button link type="primary" size="small" :icon="View">详情</el-button>
            <el-button
              v-if="row.status === 1"
              link
              type="success"
              size="small"
              @click="handleDeliver(row)"
            >发货</el-button>
            <el-button
              v-if="row.status < 2"
              link
              type="danger"
              size="small"
              @click="handleCancel(row)"
            >取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="query.current"
          v-model:page-size="query.size"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @current-change="fetchData"
          @size-change="fetchData"
        />
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.amount {
  color: $color-danger;
  font-weight: 600;
}
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding: 16px 20px;
}
</style>
