<template>
  <div class="order-detail-container">
    <div class="page-header">
      <el-button link @click="handleBack"
        ><el-icon><ArrowLeft /></el-icon><span>返回</span></el-button
      >
      <span class="page-title">订单详情</span>
    </div>
    <div class="page-content">
      <!-- 订单进度 -->
      <div class="progress-section">
        <div class="progress-steps">
          <div
            v-for="(step, index) in progressSteps"
            :key="index"
            :class="['step-item', { active: index <= currentStep, current: index === currentStep }]"
          >
            <div class="step-icon">
              <el-icon :size="24"><component :is="step.icon" /></el-icon>
            </div>
            <div class="step-info">
              <div class="step-title">{{ step.title }}</div>
              <div class="step-desc">{{ step.desc }}</div>
              <div class="step-time">{{ step.time }}</div>
            </div>
            <div v-if="index < progressSteps.length - 1" class="step-line" :class="{ active: index < currentStep }"></div>
          </div>
        </div>
      </div>
      <!-- 商品信息 -->
      <div class="section">
        <div class="section-title"><i class="title-bar"></i>商品信息</div>
        <el-table :data="productList" border style="width: 100%">
          <el-table-column label="商品信息" min-width="300">
            <template #default="{ row }">
              <div class="product-cell">
                <div class="product-image">
                  <el-image :src="row.image" fit="contain"
                    ><template #error
                      ><div class="image-placeholder">
                        <el-icon :size="30" color="#ccc"><Picture /></el-icon></div></template
                  ></el-image>
                </div>
                <div class="product-info">
                  <div class="product-name">{{ row.name }}</div>
                  <div class="product-spec">{{ row.spec1 }} {{ row.spec2 }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价" width="100" align="center"
            ><template #default="{ row }">¥{{ row.price }}</template></el-table-column
          >
          <el-table-column label="数量" width="150" align="center"
            ><template #default="{ row }"><el-input-number v-model="row.quantity" :min="1" size="small" disabled /></template
          ></el-table-column>
          <el-table-column prop="subtotal" label="小计" width="100" align="center"
            ><template #default="{ row }">¥{{ row.subtotal }}</template></el-table-column
          >
          <el-table-column label="操作" width="80" align="center"
            ><template #default><el-button type="danger" link size="small">清除</el-button></template></el-table-column
          >
        </el-table>
        <div class="product-summary">
          共{{ productList.length }}件商品 运费：¥{{ orderInfo.freight }} 共计<span class="total-price">¥{{ orderInfo.totalAmount }}</span>
        </div>
      </div>
      <!-- 收货地址 -->
      <div class="section">
        <div class="section-title"><i class="title-bar"></i>收货地址</div>
        <div class="address-card">
          <div class="address-detail">{{ orderInfo.address }}</div>
          <div class="address-name">{{ orderInfo.receiverName }}</div>
          <div class="address-phone">{{ orderInfo.receiverPhone }}</div>
        </div>
      </div>
      <!-- 其他信息 -->
      <div class="section">
        <div class="section-title"><i class="title-bar"></i>其他信息</div>
        <div class="info-table">
          <div class="info-row">
            <span class="info-label">配送时间</span><span class="info-value">{{ orderInfo.deliveryTime }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">采购事由</span><span class="info-value">{{ orderInfo.purchaseReason || '-' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">费用类型</span><span class="info-value">{{ orderInfo.costType || '-' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">订单备注</span><span class="info-value">{{ orderInfo.remark || '-' }}</span>
          </div>
        </div>
      </div>
      <!-- 发票信息 -->
      <div class="section">
        <div class="section-title"><i class="title-bar"></i>发票信息</div>
        <div class="info-table">
          <div class="info-row">
            <span class="info-label">发票类型</span><span class="info-value">{{ invoiceInfo.type || '-' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">发票抬头</span><span class="info-value">{{ invoiceInfo.title || '-' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">纳税人识别号</span><span class="info-value">{{ invoiceInfo.taxNo || '-' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">注册地址</span><span class="info-value">{{ invoiceInfo.registerAddress || '-' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">注册电话</span><span class="info-value">{{ invoiceInfo.registerPhone || '-' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">开户银行</span><span class="info-value">{{ invoiceInfo.bankName || '-' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">银行账号</span><span class="info-value">{{ invoiceInfo.bankAccount || '-' }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ArrowLeft, Document, Search, CircleCheck, Picture } from '@element-plus/icons-vue';
import { getOrderInfo, getOrderProducts } from '@/api/pc/enterprise/order';
import { getAddressInfo } from '@/api/pc/enterprise/address';
import { getInvoiceList } from '@/api/pc/enterprise/invoice';
import { ElMessage } from 'element-plus';

const router = useRouter();
const route = useRoute();
const orderId = ref<any>(0);
const currentStep = ref(1);
const loading = ref(false);

const progressSteps = ref([
  { title: '提交审核', icon: Document, desc: '采购一部提交订单审核', time: '2025/02/10 15:51:21' },
  { title: '审核中', icon: Search, desc: '采购一部提交订单审批', time: '2025/02/10 15:51:21' },
  { title: '审核完成', icon: CircleCheck, desc: '交易完成', time: '2025/02/10 15:51:21' }
]);

const productList = ref<any[]>([]);

const orderInfo = reactive({
  freight: '0.00',
  totalAmount: '0.00',
  address: '',
  receiverName: '',
  receiverPhone: '',
  deliveryTime: '',
  purchaseReason: '',
  costType: '',
  remark: ''
});

const invoiceInfo = reactive({
  type: '',
  title: '',
  taxNo: '',
  registerAddress: '',
  registerPhone: '',
  bankName: '',
  bankAccount: ''
});

// 加载订单详情
const loadOrderDetail = async () => {
  try {
    loading.value = true;
    const res = await getOrderInfo(orderId.value);
    if (res.code === 200 && res.data) {
      const order = res.data;
      // 映射订单信息
      orderInfo.freight = order.shippingFee || '0.00';
      orderInfo.totalAmount = order.payableAmount || '0.00';
      orderInfo.deliveryTime = order.expectedDeliveryTime || '';
      orderInfo.purchaseReason = order.purchaseReason || '';
      orderInfo.remark = order.remark || '';

      // 获取商品信息
      const productsRes = await getOrderProducts([orderId.value]);
      if (productsRes.code === 200 && productsRes.rows) {
        productList.value = productsRes.rows.map((p: any) => ({
          id: p.id,
          name: p.productName || '',
          spec1: p.productUnit || '',
          spec2: p.productNo || '',
          price: p.orderPrice || '0.00',
          quantity: p.orderQuantity || 1,
          subtotal: (parseFloat(p.orderPrice || '0') * (p.orderQuantity || 1)).toFixed(2),
          image: p.productImage || ''
        }));
      }

      // 获取收货地址信息
      if (order.shippingAddressId) {
        const addressRes = await getAddressInfo(order.shippingAddressId);
        if (addressRes.code === 200 && addressRes.data) {
          orderInfo.address = addressRes.data.address || '';
          orderInfo.receiverName = addressRes.data.consignee || '';
          orderInfo.receiverPhone = addressRes.data.phone || '';
        }
      }

      // 获取发票信息
      const invoiceRes = await getInvoiceList({ pageNum: 1, pageSize: 1 });
      if (invoiceRes.code === 200 && invoiceRes.rows && invoiceRes.rows.length > 0) {
        const invoice = invoiceRes.rows[0];
        invoiceInfo.type = order.invoiceType || '';
        invoiceInfo.title = order.customerName || '';
        invoiceInfo.taxNo = invoice.taxId || '';
        invoiceInfo.registerAddress = invoice.address || '';
        invoiceInfo.registerPhone = invoice.phone || '';
        invoiceInfo.bankName = invoice.bankName || '';
        invoiceInfo.bankAccount = invoice.bankAccount || '';
      }
    }
  } catch (error) {
    console.error('加载订单详情失败:', error);
    ElMessage.error('加载订单详情失败');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  const paramId = route.params.orderNo || route.params.id;
  console.log('路由参数:', route.params);
  console.log('获取到的参数:', paramId);
  // 直接使用字符串，不转换为数字，避免精度丢失
  orderId.value = paramId as string;
  console.log('订单ID:', orderId.value);
  if (orderId.value) {
    loadOrderDetail();
  } else {
    console.error('订单ID无效，无法加载订单详情');
  }
});
const handleBack = () => {
  router.push('/order/orderManage');
};
</script>

<style scoped lang="scss">
.order-detail-container {
  background: #f5f5f5;
  min-height: 100%;
}
.page-header {
  background: #fff;
  padding: 15px 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  border-bottom: 1px solid #eee;
  .page-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
  }
}
.page-content {
  padding: 20px;
}
.progress-section {
  background: #fff;
  border-radius: 8px;
  padding: 30px 50px;
  margin-bottom: 15px;
  .progress-steps {
    display: flex;
    justify-content: space-between;
    position: relative;
    .step-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      position: relative;
      flex: 1;
      .step-icon {
        width: 50px;
        height: 50px;
        border-radius: 8px;
        background: #f5f5f5;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #999;
        margin-bottom: 10px;
        position: relative;
        z-index: 1;
      }
      &.active .step-icon {
        background: #e60012;
        color: #fff;
      }
      &.current .step-icon::after {
        content: '';
        position: absolute;
        bottom: -5px;
        left: 50%;
        transform: translateX(-50%);
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: #e60012;
      }
      .step-info {
        text-align: center;
        .step-title {
          font-size: 14px;
          color: #999;
          margin-bottom: 5px;
        }
        .step-desc {
          font-size: 12px;
          color: #666;
          margin-bottom: 3px;
        }
        .step-time {
          font-size: 12px;
          color: #999;
        }
      }
      &.active .step-info .step-title {
        color: #333;
      }
      .step-line {
        position: absolute;
        top: 25px;
        left: calc(50% + 30px);
        width: calc(100% - 60px);
        height: 2px;
        background: #eee;
        &.active {
          background: #e60012;
        }
      }
      &:last-child .step-line {
        display: none;
      }
    }
  }
}
.section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 15px;
  .section-title {
    font-size: 16px;
    font-weight: bold;
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 15px;
  }
}
.title-bar {
  display: inline-block;
  width: 3px;
  height: 16px;
  background: #e60012;
  border-radius: 2px;
}
.product-cell {
  display: flex;
  align-items: center;
  gap: 15px;
  .product-image {
    width: 80px;
    height: 80px;
    background: #f5f5f5;
    border-radius: 4px;
    overflow: hidden;
    flex-shrink: 0;
    .el-image {
      width: 100%;
      height: 100%;
    }
    .image-placeholder {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .product-info {
    .product-name {
      font-size: 14px;
      color: #333;
      margin-bottom: 5px;
      line-height: 1.4;
    }
    .product-spec {
      font-size: 12px;
      color: #999;
    }
  }
}
.product-summary {
  text-align: right;
  padding: 15px 0;
  font-size: 14px;
  color: #666;
  .total-price {
    font-size: 18px;
    font-weight: bold;
    color: #e60012;
    margin-left: 5px;
  }
}
.address-card {
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
  .address-detail {
    font-size: 14px;
    color: #333;
    margin-bottom: 8px;
  }
  .address-name {
    font-size: 14px;
    color: #666;
    margin-bottom: 5px;
  }
  .address-phone {
    font-size: 14px;
    color: #666;
  }
}
.info-table {
  .info-row {
    display: flex;
    padding: 10px 0;
    border-bottom: 1px solid #f5f5f5;
    &:last-child {
      border-bottom: none;
    }
    .info-label {
      width: 100px;
      font-size: 14px;
      color: #999;
      flex-shrink: 0;
    }
    .info-value {
      flex: 1;
      font-size: 14px;
      color: #333;
    }
  }
}
</style>
