<template>
  <div class="app-container order-page">
    <el-card class="box-card mb20 border-none modern-card" shadow="never">
      <!-- 1. 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px" class="search-form">
        <el-form-item label="客户单号">
          <el-input v-model="queryParams.customerSn" placeholder="请输入客户单号搜索" clearable size="small" style="width: 200px" />
        </el-form-item>
        <el-form-item label="订单号">
          <el-input v-model="queryParams.orderNo" placeholder="请输入订单号搜索" clearable size="small" style="width: 200px" />
        </el-form-item>
        <el-form-item label="用户名/ID">
          <el-input v-model="queryParams.buyerName" placeholder="输入" clearable size="small" style="width: 150px" />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="queryParams.orderStatus" placeholder="全部" clearable size="small" style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="待付款" value="0" />
            <el-option label="已完成" value="1" />
            <el-option label="已关闭" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleQuery">搜索</el-button>
          <el-button size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 2. 列表内容 -->
    <el-card class="box-card border-none modern-card" shadow="never">
      <!-- 状态页签 -->
      <div class="tabs-container mb20">
        <div 
          v-for="tab in statusTabs" 
          :key="tab.value" 
          class="tab-item" 
          :class="{ active: activeStatus === tab.value }"
          @click="handleTabClick(tab.value)"
        >
          <div class="tab-content">
            <span class="tab-label">{{ tab.label }}</span>
            <span class="tab-count">({{ tab.count }})</span>
          </div>
        </div>
      </div>

      <!-- 订单列表头部 -->
      <div class="order-list-header mb10">
        <div class="col-product">商品信息</div>
        <div class="col-user">用户信息</div>
        <div class="col-source">订单来源</div>
        <div class="col-p-type">商品类型</div>
        <div class="col-o-type">订单类型</div>
        <div class="col-receivable">应收</div>
        <div class="col-remark">订单备注</div>
        <div class="col-status">订单状态</div>
        <div class="col-action">操作</div>
      </div>

      <!-- 订单列表主体 -->
      <div v-loading="loading" class="order-list">
        <div v-for="order in orderList" :key="order.orderNo" class="order-item mb20">
          <!-- 订单页眉 -->
          <div class="order-item-header">
            <div class="header-left">
              <span class="label">订单编号：</span>
              <span class="value">{{ order.orderNo }}</span>
              <el-icon class="copy-icon" @click="copyText(order.orderNo)"><i-ep-document-copy /></el-icon>
              <span class="label ml20">下单时间：</span>
              <span class="value">{{ order.createTime }}</span>
            </div>
            <div class="header-right">
              <span class="label">实付款（元）：</span>
              <span class="total-price">{{ order.paidAmount }}元</span>
            </div>
          </div>
          
          <!-- 订单内容 -->
          <div class="order-item-content">
            <div class="col-product product-info">
              <img :src="order.productImg || 'https://via.placeholder.com/60'" class="p-img" />
              <div class="p-details">
                <div class="p-name">{{ order.productName || '未知商品' }}</div>
                <div class="p-price-grid">
                  <span>总价：{{ order.totalAmount }}</span>
                  <span>定金：{{ order.deposit || 0 }}</span>
                  <span>尾款：{{ order.balance || 0 }}</span>
                  <span>数量：{{ order.quantity || 1 }}</span>
                </div>
              </div>
            </div>
            
            <div class="col-user user-info">
              <el-avatar :size="32" :src="order.userAvatar || 'https://via.placeholder.com/32'" />
              <div class="user-desc">
                <div class="u-name">{{ order.buyerName }}</div>
                <div class="u-id">ID: {{ order.buyerId }}</div>
                <div class="u-phone">手机号：{{ order.phone || '-' }}</div>
              </div>
            </div>
            
            <div class="col-source">{{ order.source || '小程序' }}</div>
            <div class="col-p-type">{{ order.orderType === 1 ? '岗位' : order.orderStatus === 2 ? '培训' : '商品' }}</div>
            <div class="col-o-type">{{ order.deposit ? '定金' : '全款' }}</div>
            <div class="col-receivable">{{ order.totalAmount }}</div>
            <div class="col-remark">{{ order.remark || '无' }}</div>
            
            <div class="col-status">
              <span :class="getStatusClass(order.orderStatus)">{{ getStatusLabel(order.orderStatus) }}</span>
            </div>
            
            <div class="col-action">
              <el-link type="primary" :underline="false" @click="handleDetail(order)">订单详情</el-link>
              <el-link type="primary" :underline="false" class="ml10" @click="handleCancel(order)">取消订单</el-link>
              <el-link type="primary" :underline="false" class="ml10" v-if="String(order.orderStatus) === '1'" @click="openRefundDialog(order)">退款</el-link>
              <el-link type="primary" :underline="false" class="ml10" v-if="String(order.orderStatus) === '3'" @click="openAuditDialog(order)">审核</el-link>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />
      </div>
    </el-card>

    <!-- 退款确认弹窗 -->
    <el-dialog :show-close="false" v-model="refundDialogVisible" width="400px">
      <div class="dialog-title">请确认如下信息：</div>
      <div class="refund-info-box">
        <div class="info-row">
          <div class="label">订单号</div>
          <div class="value">{{ currentOrder.orderNo }}</div>
        </div>
        <div class="info-row">
          <div class="label">订单商品</div>
          <div class="value">{{ currentOrder.productName || '未知商品' }}</div>
        </div>
        <div class="info-row">
          <div class="label">实付金额</div>
          <div class="value">￥{{ currentOrder.paidAmount }}元</div>
        </div>
        <div class="info-row">
          <div class="label">退款金额</div>
          <div class="value">￥{{ currentOrder.paidAmount }}元</div>
        </div>
      </div>
      <template #footer>
         <div style="text-align: center; margin-top: 20px;">
           <el-button type="primary" @click="confirmRefund" style="width: 120px;">确认退款</el-button>
         </div>
      </template>
    </el-dialog>

    <!-- 审核信息确认弹窗 -->
    <el-dialog title="信息确认" v-model="auditDialogVisible" width="500px">
      <el-form :model="auditForm" label-width="140px" class="audit-form mt20">
        <el-form-item label="订单实付金额：">
          ￥{{ currentOrder.paidAmount }}元
        </el-form-item>
        <el-form-item label="用户申请退款原因：">
          {{ currentOrder.remark || '无' }}
        </el-form-item>
        <el-form-item label="退款金额：">
          ￥{{ currentOrder.paidAmount }}元
        </el-form-item>
        <el-form-item label="是否退款：">
          <el-select v-model="auditForm.status" style="width: 200px">
            <el-option label="同意退款" value="1" />
            <el-option label="拒绝退款" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="拒绝退款原因：" v-if="auditForm.status === '2'">
          <el-input type="textarea" v-model="auditForm.rejectReason" placeholder="多行输入" :rows="3" style="width: 200px" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align: center;">
          <el-button type="primary" @click="confirmAudit">确定</el-button>
          <el-button @click="auditDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listOrder, delOrder, updateOrder, getOrderStatistics } from '@/api/system/order';
import { OrderVO, OrderQuery } from '@/api/system/order/types';

const router = useRouter();

const loading = ref(false);
const total = ref(0);
const activeStatus = ref('all');

const queryParams = reactive<OrderQuery>({
  pageNum: 1,
  pageSize: 10,
  customerSn: '',
  orderNo: '',
  buyerName: '',
  orderStatus: '',
});

const statusTabs = ref([
  { label: '全部订单', count: 0, value: 'all' },
  { label: '待付款', count: 0, value: '0' },
  { label: '已完成', count: 0, value: '1' },
  { label: '已关闭', count: 0, value: '2' },
  { label: '售后中', count: 0, value: '3' }
]);

const orderList = ref<OrderVO[]>([]);

/** 查询订单统计信息 */
const getStatistics = async () => {
  const res = await getOrderStatistics();
  if (res.data) {
    statusTabs.value.forEach(tab => {
      if (res.data[tab.value] !== undefined) {
        tab.count = res.data[tab.value];
      }
    });
  }
};

/** 查询订单列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listOrder(queryParams);
    orderList.value = res.rows;
    total.value = res.total;
    // 列表更新时同步更新统计
    getStatistics();
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryParams.customerSn = '';
  queryParams.orderNo = '';
  queryParams.buyerName = '';
  queryParams.orderStatus = '';
  activeStatus.value = 'all';
  handleQuery();
};

const handleTabClick = (val: string) => {
  activeStatus.value = val;
  queryParams.orderStatus = val === 'all' ? '' : val;
  handleQuery();
};

const getStatusClass = (status: number | string) => {
  const s = String(status);
  if (s === '1') return 'status-success';
  if (s === '0') return 'status-warning';
  if (s === '3') return 'status-audit';
  return 'status-info';
};

const getStatusLabel = (status: number | string) => {
  const s = String(status);
  const map: any = {
    '0': '待付款',
    '1': '已完成',
    '2': '已关闭',
    '3': '退款审核'
  };
  return map[s] || '未知';
};

const copyText = (text: string) => {
  if (!text) return;
  navigator.clipboard.writeText(text).then(() => {
    ElMessage.success('复制成功');
  });
};

const handleCancel = (order: OrderVO) => {
  ElMessageBox.confirm(
    `确定要取消订单号为 ${order.orderNo} 的订单吗？`,
    '系统提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    await updateOrder({ id: order.id, orderStatus: 2 });
    ElMessage.success('订单取消成功');
    getList();
  }).catch(() => {});
};

const handleDetail = (order: OrderVO) => {
  router.push({
    path: '/system/order/detail',
    query: { id: order.id }
  });
};

const refundDialogVisible = ref(false);
const auditDialogVisible = ref(false);
const currentOrder = ref<any>({});
const auditForm = reactive({
  status: '1',
  rejectReason: ''
});

const openRefundDialog = (order: OrderVO) => {
  currentOrder.value = order;
  refundDialogVisible.value = true;
};

const openAuditDialog = (order: OrderVO) => {
  currentOrder.value = order;
  auditForm.status = '1';
  auditForm.rejectReason = '';
  auditDialogVisible.value = true;
};

const confirmRefund = async () => {
    await updateOrder({ id: currentOrder.value.id, orderStatus: 3 });
    ElMessage.success('已提交退款申请');
    refundDialogVisible.value = false;
    getList();
};

const confirmAudit = async () => {
  const newStatus = auditForm.status === '1' ? 2 : 1; 
  await updateOrder({ id: currentOrder.value.id, orderStatus: newStatus, remark: auditForm.rejectReason });
  ElMessage.success('审核提交成功');
  auditDialogVisible.value = false;
  getList();
};

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.order-page {
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);
  padding: 20px;
}

.border-none { border: none !important; }

/* 搜索表单自定义样式 */
.search-form {
  :deep(.el-form-item) {
    margin-bottom: 0;
  }
}

/* 页签样式 */
.tabs-container {
  display: flex;
  background-color: #fff;
  padding: 0 20px;
  border-bottom: 1px solid #e5e6eb;
  .tab-item {
    padding: 15px 25px;
    cursor: pointer;
    text-align: center;
    position: relative;
    transition: all 0.3s;
    
    .tab-content {
      display: flex;
      align-items: center;
      gap: 4px;
      font-size: 14px;
      color: #4e5969;
    }
    
    &.active {
      .tab-content { color: #1d2129; font-weight: 600; }
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 20%;
        width: 60%;
        height: 3px;
        background-color: #409eff;
      }
    }
  }
}

/* 列表头部样式 */
.order-list-header {
  display: flex;
  background-color: #f7f8fa;
  padding: 12px 0;
  font-size: 14px;
  color: #4e5969;
  text-align: center;
  border: 1px solid #e5e6eb;
}

/* 布局宽度定义 */
.col-product { width: 300px; text-align: left; padding-left: 20px; }
.col-user { width: 220px; text-align: left; }
.col-source { width: 100px; }
.col-p-type { width: 100px; }
.col-o-type { width: 100px; }
.col-receivable { width: 100px; }
.col-remark { flex: 1; }
.col-status { width: 120px; }
.col-action { width: 220px; }

/* 订单卡片样式 */
.order-item {
  background-color: #fff;
  border: 1px solid #e5e6eb;
  
  .order-item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #eef7ff;
    padding: 10px 20px;
    font-size: 13px;
    
    .label { color: #86909c; }
    .value { color: #1d2129; font-weight: 500; }
    .copy-icon { margin-left: 5px; cursor: pointer; color: #409eff; }
    .total-price { font-size: 14px; color: #1d2129; font-weight: 600; }
  }
  
  .order-item-content {
    display: flex;
    align-items: center;
    padding: 20px 0;
    text-align: center;
    font-size: 13px;
    color: #4e5969;
    
    & > div {
       border-right: 1px solid #f2f3f5;
       &:last-child { border-right: none; }
    }
  }
}

/* 商品列细节 */
.product-info {
  display: flex;
  gap: 12px;
  .p-img { width: 60px; height: 60px; border-radius: 4px; object-fit: cover; }
  .p-details {
    flex: 1;
    .p-name { color: #409eff; font-weight: 500; margin-bottom: 8px; cursor: pointer; }
    .p-price-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      font-size: 12px;
      color: #86909c;
      gap: 4px;
    }
  }
}

/* 用户列细节 */
.user-info {
  display: flex;
  gap: 10px;
  padding-left: 15px;
  .user-desc {
    .u-name { color: #409eff; font-weight: 500; margin-bottom: 2px; }
    .u-id, .u-phone { font-size: 12px; color: #86909c; }
  }
}

/* 线性状态文字 */
.status-success { color: #52c41a; font-weight: 600; }
.status-warning { color: #faad14; font-weight: 600; }
.status-info { color: #86909c; }
.status-audit { 
  color: #f08235; 
  background-color: #fbe6d5; 
  padding: 4px 10px; 
  border-radius: 4px; 
  font-weight: 500; 
  font-size: 13px;
}

.ml10 { margin-left: 10px; }
.ml20 { margin-left: 20px; }
.mt20 { margin-top: 20px; }
.pagination-container { display: flex; justify-content: flex-end; margin-top: 20px; }

/* 弹窗样式 */
.dialog-title {
  font-weight: 600;
  font-size: 15px;
  margin-bottom: 20px;
  color: #1d2129;
}

.refund-info-box {
  border: 1px solid #e5e6eb;
  border-bottom: none;
  .info-row {
    display: flex;
    border-bottom: 1px solid #e5e6eb;
    font-size: 13px;
    .label {
      width: 100px;
      padding: 12px 15px;
      background-color: #f7f8fa;
      border-right: 1px solid #e5e6eb;
      color: #4e5969;
    }
    .value {
      flex: 1;
      padding: 12px 15px;
      color: #1d2129;
    }
  }
}

.audit-form {
  :deep(.el-form-item__label) {
    font-weight: normal;
    color: #4e5969;
  }
  .el-form-item {
    margin-bottom: 18px;
  }
}
</style>
