<template>
  <div class="app-container">
    <el-card shadow="never" class="mb-2">
      <!-- 订单信息 -->
      <el-descriptions title="订单信息" :column="2" border class="custom-descriptions">
        <el-descriptions-item label="订单编号">{{ orderDetail.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="关联单号">{{ orderDetail.parentOrderNo }}</el-descriptions-item>
        <el-descriptions-item label="项目/平台订单号" v-if="crrcExtInfo.crrcOrderNo">{{ crrcExtInfo.crrcOrderNo }}</el-descriptions-item>
        <el-descriptions-item label="发货单编号">{{ orderDetail.shipmentNo }}</el-descriptions-item>
        <el-descriptions-item label="订单总金额">{{ orderDetail.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="支付状态">
          <dict-tag :options="payment_status" :value="orderDetail.paymentStatus" />
        </el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <dict-tag :options="order_status" :value="orderDetail.orderStatus" />
        </el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ orderDetail.orderTime }}</el-descriptions-item>
        <el-descriptions-item label="确认时间">{{ orderDetail.confirmTime }}</el-descriptions-item>
        <!-- <el-descriptions-item label="发货时间">{{ orderDetail.shippingTime }}</el-descriptions-item> -->
        <el-descriptions-item label="签收时间">{{ orderDetail.receivingTime }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 订单详情信息 -->
    <el-card shadow="never" class="mb-2" v-if="!orderDetail.dataSource">
      <template #header>
        <span>订单基本信息</span>
      </template>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="detail-item">
            <span class="label">归属公司：</span>
            <span>{{ companyInfo.companyCode || '--' }},{{ companyInfo.companyName || '--' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">业务人员：</span>
            <span>{{ orderDetail.businessStaff }}</span>
          </div>
          <div class="detail-item">
            <span class="label">发票类型：</span>
            <span>{{ orderDetail.invoiceType }}</span>
          </div>
          <div class="detail-item">
            <span class="label">发货仓库：</span>
            <span>{{ warehouseInfo.warehouseName || '--' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">采购事由：</span>
            <span>{{ orderDetail.purchaseReason }}</span>
          </div>
          <div class="detail-item">
            <span class="label">订单备注：</span>
            <span>{{ orderDetail.remark }}</span>
          </div>
          <div class="detail-item">
            <span class="label">附件：</span>
            <span>{{ orderDetail.attachmentPath || '' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="detail-item">
            <span class="label">客户名称：</span>
            <span>{{ customerInfo.customerNo || '--' }},{{ customerInfo.customerName || '--' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">客服人员：</span>
            <span>{{ orderDetail.customerService }}</span>
          </div>
          <div class="detail-item">
            <span class="label">支付方式：</span>
            <span>{{ getDictLabel(pay_method, orderDetail.payType) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">费用类型：</span>
            <span>{{ getDictLabel(fee_type, orderDetail.expenseType) }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="detail-item">
            <span class="label">所属项目：</span>
            <span>{{ orderDetail.dataSourceStr }}</span>
          </div>
          <div class="detail-item">
            <span class="label">业务部门：</span>
            <span>{{ orderDetail.businessDept }}</span>
          </div>
          <div class="detail-item">
            <span class="label">下单部门：</span>
            <span>{{ orderDetail.userDeptName }}</span>
          </div>
          <div class="detail-item">
            <span class="label">订单状态：</span>
            <span>{{ getDictLabel(order_status, orderDetail.orderStatus) }}</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 收货信息 -->
    <el-card shadow="never" class="mb-2" v-if="!orderDetail.dataSource">
      <template #header>
        <span>收货信息</span>
      </template>
      <el-descriptions :column="2" border class="custom-descriptions">
        <el-descriptions-item label="收货人姓名">{{ shippingAddress.consignee }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ shippingAddress.phone }}</el-descriptions-item>
        <el-descriptions-item label="收货地址">{{ shippingAddress.provincialCityCountry }} {{ shippingAddress.address }}</el-descriptions-item>
      </el-descriptions>
    </el-card>
    <!-- 分配信息 -->
    <el-card shadow="never" class="mb-2">
      <template #header>
        <span>分配信息</span>
      </template>
      <el-descriptions :column="2" border class="custom-descriptions">
        <el-descriptions-item label="名称">{{ orderDetail.assigneeName }}</el-descriptions-item>
        <el-descriptions-item label="分配备注">{{ orderDetail.assigneeRemark }}</el-descriptions-item>
      </el-descriptions>
    </el-card>
    <!-- 项目订单扩展信息 -->
    <el-card v-if="orderDetail.dataSource" shadow="never" class="mb-2">
      <template #header>
        <span>项目订单扩展信息</span>
      </template>
      <el-descriptions :column="3" border class="custom-descriptions">
        <el-descriptions-item label="收货人">{{ crrcExtInfo.receiverName || '--' }}</el-descriptions-item>
        <el-descriptions-item label="收货人手机号" :span="2">{{ crrcExtInfo.mobile || '--' }}</el-descriptions-item>
        <el-descriptions-item label="收货人邮箱">{{ crrcExtInfo.email || '--' }}</el-descriptions-item>
        <el-descriptions-item label="收货地址" :span="2">
          {{ crrcExtInfo.provinceName || '' }}-{{ crrcExtInfo.cityName || '' }}-{{ crrcExtInfo.countyName || '' }}-{{ crrcExtInfo.townName || '' }}-{{
            crrcExtInfo.detailAddress || ''
          }}
        </el-descriptions-item>
        <el-descriptions-item label="下单人姓名">{{ crrcExtInfo.buyerName || '--' }}</el-descriptions-item>
        <el-descriptions-item label="下单人手机号" :span="2">{{ crrcExtInfo.buyerMobile || '--' }}</el-descriptions-item>
        <el-descriptions-item label="采购单位名称" :span="3">{{ crrcExtInfo.purchaserName || '--' }}</el-descriptions-item>
        <el-descriptions-item label="采购部门名称" :span="3">{{ crrcExtInfo.purchaserDeptName || '--' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 商品明细 -->
    <el-card shadow="never" class="mb-2">
      <template #header>
        <span>商品明细</span>
      </template>
      <el-table :data="productList" border style="width: 100%">
        <el-table-column label="产品图片" width="100">
          <template #default="scope">
            <el-image v-if="scope.row.productImage" :src="scope.row.productImage" style="width: 60px; height: 60px" fit="cover" />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="productNo" label="商品编号" />

        <el-table-column prop="productName" label="商品信息" min-width="150" />
        <el-table-column prop="taxRate" label="税率" align="center">
          <template #default="scope"> 增值税{{ scope.row.taxRate }}% </template>
        </el-table-column>
        <el-table-column prop="productUnit" label="单位" />
        <el-table-column prop="minSellingPrice" label="最低售价" />
        <el-table-column prop="orderPrice" label="含税单价" />
        <el-table-column prop="subtotal" label="小计" />
        <el-table-column prop="orderQuantity" label="采购数量" />
        <el-table-column prop="quantitySent" label="已发货数量" />
        <el-table-column prop="unsentQuantity" label="未发货数量" />
      </el-table>
    </el-card>
    <div class="mt-2 text-right" style="margin-right: 8px; margin-bottom: 10px">
      <span
        >商品数：{{ totalQuantity }} , 其中有 <span style="color: #f56c6c">{{ totalQuantitySent }} 已经发货</span></span
      >
    </div>
    <!-- 信息汇总 -->
    <el-card shadow="never" class="mb-2">
      <template #header>
        <div class="card-header">
          <span>信息汇总</span>
        </div>
      </template>

      <el-table :data="summaryData" border style="width: 100%">
        <el-table-column prop="quantity" label="商品数量" align="center" />
        <el-table-column prop="shippingFee" label="运费" align="center" />
        <el-table-column prop="totalAmount" label="订单总金额" align="center" />
        <el-table-column prop="payableAmount" label="应付款金额" align="center" />
      </el-table>
    </el-card>
    <!-- 发货对话框 -->
    <DeliverDialog
      v-model="showDeliverDialog"
      :order-id="currentOrderId"
      :order-no="currentOrderNo"
      :operate-type="operateType"
      @success="handleDeliverSuccess"
    />

    <!-- 编辑发货信息对话框 -->
    <EditDeliverDialog v-model="showEditDeliverDialog" :deliver-id="editDeliverId" @success="handleDeliverSuccess" />
    <!-- 发货信息 -->
    <el-card shadow="never" class="mb-2" v-show="orderDetail.orderStatus != '0'">
      <template #header>
        <div class="card-header">
          <span>发货信息:共{{ orderDeliverList.length }}个包裹</span>
          <el-button type="primary" v-if="orderDetail.orderStatus == '2' || orderDetail.orderStatus == '3'" @click="handleAddDeliver(orderDetail)"
            >添加发货信息</el-button
          >
        </div>
      </template>
      <el-card v-for="deliver in orderDeliverList" :key="deliver.id">
        <div class="mb-2" style="background: #f3f3f3; padding: 10px">
          <el-row :gutter="20" justify="space-between" align="middle">
            <el-col :span="18">
              <div style="display: flex; flex-wrap: wrap; gap: 16px">
                <span>发货单号:{{ (deliver as any).deliverCode || '--' }}</span>
                <span>发货时间:{{ (deliver as any).createTime || '--' }}</span>
                <span>发货方式:{{ getDictLabel(deliver_method, deliver.deliverMethod || '--') }}</span>
                <span v-if="deliver.deliverMethod == '0'">收货人:{{ deliver.deliverMan || '--' }}</span>
                <span>手机:{{ deliver.phone || deliver.consigneePhone }}</span>
                <span style="margin-left: 30px" v-if="deliver.deliverMethod == '1'">物流单号:{{ deliver.logisticNo || '--' }}</span>
                <span style="margin-left: 20px">发货备注:{{ deliver.deliverRemark || '--' }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div style="text-align: right">
                <el-button type="primary" @click="handleEditDeliver(deliver)">编辑发货信息</el-button>
                <el-button type="primary" v-if="deliver.deliverMethod == '0'" @click="handleEditLogistics(deliver)">变更物流状态</el-button>
                <el-button type="primary" @click="handleViewLogistics(orderDetail)">查看物流</el-button>
              </div>
            </el-col>
          </el-row>
        </div>
        <el-table :data="deliver.deliverProductList" border style="width: 100%">
          <el-table-column label="产品编号" prop="productNo" align="center" />
          <el-table-column label="商品名称" prop="productName" align="center" />
          <el-table-column label="单位" prop="productUnit" align="center" />
          <el-table-column label="发货数量" prop="deliverNum" align="center" />
        </el-table>
      </el-card>
    </el-card>

    <!-- A10备货信息 -->
    <el-card shadow="never" class="mb-2">
      <template #header>
        <div class="card-header">
          <span>A10备货信息</span>
        </div>
      </template>

      <el-table border style="width: 100%">
        <el-table-column label="副点人员编号" align="center" />
        <el-table-column label="单据编号" align="center" />
        <el-table-column label="清货人员编号" align="center" />
        <el-table-column label="配货人员编号" align="center" />
        <el-table-column label="快递编号" align="center" />
        <el-table-column label="快递单号" align="center" />
        <el-table-column label="付款方式" align="center" />
        <el-table-column label="库存记录单号" align="center" />
        <el-table-column label="回签信息" align="center" />
      </el-table>
    </el-card>

    <!-- 底部按钮 -->
    <div class="text-center mt-4">
      <el-button @click="goBack">返回</el-button>
    </div>
    <!-- 物流详情对话框 -->
    <LogisticsDetail v-model="showLogisticsDialog" :order-id="logisticsOrderId" />
    <!-- 订单状态日志抽屉 -->
    <AddOrderStatusLogDrawer ref="statusLogDrawerRef" />
  </div>
</template>

<script setup name="SendDetail" lang="ts">
import { ref, computed, onMounted } from 'vue';
import DeliverDialog from './deliverDialog.vue';
import EditDeliverDialog from './editDeliverDialog.vue';
import AddOrderStatusLogDrawer from './addOrderStatusLogDrawer.vue';
import { useRoute, useRouter } from 'vue-router';
import { getOrderMain } from '@/api/order/orderMain';
import { OrderMainVO } from '@/api/order/orderMain/types';
import { listOrderProduct } from '@/api/order/orderProduct';
import { OrderProductVO } from '@/api/order/orderProduct/types';
import { DeliverProductVO } from '@/api/order/deliverProduct/types';
import { listOrderDeliver } from '@/api/order/orderDeliver';
import { OrderDeliverVO } from '@/api/order/orderDeliver/types';
import { listDeliverProduct } from '@/api/order/deliverProduct';
import { getShippingAddress } from '@/api/customer/customerFile/shippingAddress';
import { ShippingAddressVO } from '@/api/customer/customerFile/shippingAddress/types';
import { getWarehouse } from '@/api/company/warehouse';
import { WarehouseVO } from '@/api/company/warehouse/types';
import { getCompany } from '@/api/company/company';
import { CompanyVO } from '@/api/company/company/types';
import { getCustomerInfo } from '@/api/customer/customerFile/customerInfo';
import { CustomerInfoVO } from '@/api/customer/customerFile/customerInfo/types';
import { getInvoiceType } from '@/api/customer/invoiceType';
import { InvoiceTypeVO } from '@/api/customer/invoiceType/types';
import { selectNewOneLog } from '@/api/order/orderStatusLog';
import { getDept } from '@/api/system/dept';
import { getOrderMainCrrcExt } from '@/api/order/orderMainCrrcExt';
import { OrderMainCrrcExtVO } from '@/api/order/orderMainCrrcExt/types';
import LogisticsDetail from './logisticsDetail.vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { order_status, payment_status, fee_type, pay_method, deliver_method } = toRefs<any>(
  proxy?.useDict('order_status', 'payment_status', 'fee_type', 'pay_method', 'deliver_method')
);
const route = useRoute();
const router = useRouter();

// 订单详情
const orderDetail = ref<OrderMainVO>({} as OrderMainVO);

// 仓库信息
const warehouseInfo = ref<WarehouseVO>({} as WarehouseVO);

// 公司信息
const companyInfo = ref<CompanyVO>({} as CompanyVO);

// 客户信息
const customerInfo = ref<CustomerInfoVO>({} as CustomerInfoVO);

// 发票类型信息
const invoiceTypeInfo = ref<InvoiceTypeVO>({} as InvoiceTypeVO);

// 商品明细列表
const productList = ref<OrderProductVO[]>([]);

// 发货包裹列表
const orderDeliverList = ref<OrderDeliverVO[]>([]);
const deliverProductList = ref<DeliverProductVO[]>([]);

// 收货地址信息
const shippingAddress = ref<ShippingAddressVO>({} as ShippingAddressVO);

// 中车订单扩展信息
const crrcExtInfo = ref<OrderMainCrrcExtVO>({} as OrderMainCrrcExtVO);

const operateType = ref('add');

// 发货对话框
const showDeliverDialog = ref(false);
const currentOrderId = ref<string | number>();
const currentOrderNo = ref<string>();

// 编辑发货对话框
const showEditDeliverDialog = ref(false);
const editDeliverId = ref<string | number>();

const showLogisticsDialog = ref(false);
const logisticsOrderId = ref<string | number>();

// 订单状态日志抽屉
const statusLogDrawerRef = ref<any>(null);

/** 发货成功回调 */
const handleDeliverSuccess = () => {
  getOrderDetail();
};

// 计算商品总数（所有商品的采购数量之和）
const totalQuantity = computed(() => {
  return productList.value.reduce((sum, item) => {
    return sum + (Number(item.orderQuantity) || 0);
  }, 0);
});

// 计算已发货总数（所有商品的已发货数量之和）
const totalQuantitySent = computed(() => {
  return productList.value.reduce((sum, item) => {
    return sum + (Number(item.quantitySent) || 0);
  }, 0);
});

// 计算发货单编号列表（从 orderDeliverList 中提取 deliverCode 用逗号拼接）
const shipmentNoList = computed(() => {
  if (!orderDeliverList.value || orderDeliverList.value.length === 0) {
    return orderDetail.value.shipmentNo || '--';
  }
  const deliverCodes = orderDeliverList.value
    .map((deliver) => (deliver as any).deliverCode)
    .filter((code) => code)
    .join(',');
  return deliverCodes || '--';
});

// 获取部门详细信息
const getDeptDetail = async (deptId: string) => {
  try {
    const res = await getDept(deptId);
    return res.data?.deptName || deptId;
  } catch (error) {
    return deptId;
  }
};

// 获取订单详情
const getOrderDetail = async () => {
  const orderId = route.query.id || route.params.id;
  if (!orderId) {
    proxy?.$modal.msgError('订单ID不能为空');
    return;
  }

  try {
    const res = await getOrderMain(orderId as any);
    orderDetail.value = res.data;

    // 获取商品明细
    if (orderDetail.value.orderProductList) {
      productList.value = orderDetail.value.orderProductList;
    } else if (orderDetail.value.id) {
      await getProductList(orderDetail.value);
    }

    // 获取发货商品明细
    if (orderDetail.value.deliverProductList) {
      deliverProductList.value = orderDetail.value.deliverProductList;
    } else if (orderDetail.value.id) {
      await getDeliverProductList(orderDetail.value);
    }

    // 获取发货单及关联的物流商品信息
    if (orderDetail.value.id) {
      await getOrderDeliverListData(orderDetail.value.id);
    }

    // 获取收货地址
    if (orderDetail.value.shippingAddressId) {
      await getShippingAddressDetail(orderDetail.value.shippingAddressId);
    }

    // 获取仓库信息
    if (orderDetail.value.warehouseId) {
      await getWarehouseDetail(orderDetail.value.warehouseId);
    }

    // 获取公司信息
    if (orderDetail.value.companyId) {
      await getCompanyDetail(orderDetail.value.companyId);
    }

    // 获取客户信息
    if (orderDetail.value.customerId) {
      await getCustomerDetail(orderDetail.value.customerId);
    }
    if (orderDetail.value.userDept) {
      orderDetail.value.userDeptName = await getDeptDetail(orderDetail.value.userDept);
    }

    // 获取中车订单扩展信息
    //如果data.parentOrderId存在，则使用data.parentOrderId查询，否则使用data.id查询
    if (orderDetail.value.parentOrderId) {
      try {
        const extRes = await getOrderMainCrrcExt(orderDetail.value.parentOrderId);
        crrcExtInfo.value = extRes.data || ({} as OrderMainCrrcExtVO);
      } catch (error) {
        console.error('获取中车订单扩展信息失败:', error);
      }
    } else if (orderDetail.value.id) {
      try {
        const extRes = await getOrderMainCrrcExt(orderDetail.value.id);
        crrcExtInfo.value = extRes.data || ({} as OrderMainCrrcExtVO);
      } catch (error) {
        console.error('获取中车订单扩展信息失败:', error);
      }
    }

    // 获取发票类型信息
    // if (orderDetail.value.invoiceType) {
    //   await getInvoiceTypeDetail(orderDetail.value.invoiceType);
    // }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    proxy?.$modal.msgError('获取订单详情失败');
  }
};

/** 发货按钮操作 */
const handleAddDeliver = (row?: OrderMainVO) => {
  if (!row?.id) {
    proxy?.$modal.msgWarning('订单ID不能为空');
    return;
  }
  operateType.value = 'add';
  currentOrderId.value = row.id;
  currentOrderNo.value = row.orderNo;
  showDeliverDialog.value = true;
};

/** 编辑发货信息操作 */
const handleEditDeliver = (deliver: any) => {
  if (!deliver?.id) {
    proxy?.$modal.msgWarning('发货信息ID不能为空');
    return;
  }
  editDeliverId.value = deliver.id;
  showEditDeliverDialog.value = true;
};

const handleViewLogistics = (row?: OrderMainVO) => {
  if (!row?.id) {
    proxy?.$modal.msgWarning('订单ID不能为空');
    return;
  }
  logisticsOrderId.value = row.id;

  showLogisticsDialog.value = true;
};

/** 变更物流状态 */
const handleEditLogistics = async (row?: any) => {
  if (!row?.orderId) {
    proxy?.$modal.msgWarning('订单ID不能为空');
    return;
  }

  // 补充客户信息
  row.customerId = orderDetail.value.customerId;
  row.customerNo = orderDetail.value.customerCode;

  let currentOrderStatus = '';

  try {
    const res = await selectNewOneLog({
      orderId: row.orderId,
      customerId: row.customerId,
      logisticNos: row.deliverCode
    });

    if (res.code == 200 && res.data) {
      row.images = res.data.images;
      currentOrderStatus = res.data.statusName || '';
    }
  } catch (error) {
    console.error('查询物流失败:', error);
  }

  // 4. 使用获取到的状态打开弹窗
  statusLogDrawerRef.value?.openDrawer(row, currentOrderStatus);
};

// 获取商品明细列表
const getProductList = async (orderDetail: OrderMainVO) => {
  try {
    productList.value = orderDetail.orderProductList || [];
  } catch (error) {
    console.error('获取商品明细失败:', error);
  }
};

// 获取发货商品明细列表
const getDeliverProductList = async (orderDetail: OrderMainVO) => {
  try {
    deliverProductList.value = orderDetail.deliverProductList || [];
  } catch (error) {
    console.error('获取发货商品明细失败:', error);
  }
};

// 获取发货单列表
const getOrderDeliverListData = async (orderId: string | number) => {
  try {
    const res = await listOrderDeliver({ orderId, pageNum: 1, pageSize: 100 });
    const deliverList = (res as any).rows || res.data || [];

    // 为每条发货记录获取商品明细
    for (const deliver of deliverList) {
      if (deliver.id) {
        try {
          const productRes = await listDeliverProduct({ deliverId: deliver.id, pageNum: 1, pageSize: 100 });
          deliver.deliverProductList = (productRes as any).rows || productRes.data || [];
        } catch (error) {
          console.error(`获取发货单${deliver.id}的商品明细失败:`, error);
          deliver.deliverProductList = [];
        }
      }
    }

    orderDeliverList.value = deliverList;
  } catch (error) {
    console.error('获取发货单列表失败:', error);
  }
};

// 获取收货地址详情
const getShippingAddressDetail = async (addressId: string | number) => {
  try {
    const res = await getShippingAddress(addressId);
    shippingAddress.value = res.data;
  } catch (error) {
    console.error('获取收货地址失败:', error);
  }
};

// 获取中车订单扩展信息
const getCrrcExtDetail = async (orderId: string | number) => {
  try {
    const res = await getOrderMainCrrcExt(orderId);
    crrcExtInfo.value = res.data || ({} as OrderMainCrrcExtVO);
  } catch (error) {
    console.error('获取中车订单扩展信息失败:', error);
  }
};

// 计算商品总金额（所有商品的小计之和）
const totalAmount = computed(() => {
  return productList.value.reduce((sum, item) => {
    return sum + (Number(item.subtotal) || 0);
  }, 0);
});

// 计算应付款金额（订单总金额 + 运费）
const payableAmount = computed(() => {
  const shipping = Number(orderDetail.value.shippingFee) || 0;
  return totalAmount.value + shipping;
});
// 汇总数据（用于表格显示）
const summaryData = computed(() => {
  return [
    {
      quantity: totalQuantity.value,
      shippingFee: `￥${(Number(orderDetail.value.shippingFee) || 0).toFixed(2)}`,
      totalAmount: `￥${totalAmount.value.toFixed(2)}`,
      payableAmount: `￥${payableAmount.value.toFixed(2)}`
    }
  ];
});

// 获取仓库详情
const getWarehouseDetail = async (warehouseId: string | number) => {
  try {
    const res = await getWarehouse(warehouseId);
    warehouseInfo.value = res.data;
  } catch (error) {
    console.error('获取仓库信息失败:', error);
  }
};

// 获取公司详情
const getCompanyDetail = async (companyId: string | number) => {
  try {
    const res = await getCompany(companyId);
    companyInfo.value = res.data;
  } catch (error) {
    console.error('获取公司信息失败:', error);
  }
};

// 获取客户详情
const getCustomerDetail = async (customerId: string | number) => {
  try {
    const res = await getCustomerInfo(customerId);
    customerInfo.value = res.data;
  } catch (error) {
    console.error('获取客户信息失败:', error);
  }
};

// 获取发票类型详情
const getInvoiceTypeDetail = async (invoiceTypeId: string | number) => {
  try {
    const res = await getInvoiceType(invoiceTypeId);
    invoiceTypeInfo.value = res.data;
  } catch (error) {
    console.error('获取发票类型信息失败:', error);
  }
};

// 字典label工具
function getDictLabel(dictList: any[], value: string) {
  if (!dictList || !Array.isArray(dictList)) return value || '--';
  const found = dictList.find((item) => item.value === value);
  return found ? found.label : value || '--';
}

// 返回
const goBack = () => {
  router.back();
};

// 打印
const handlePrint = () => {
  window.print();
};

onMounted(() => {
  getOrderDetail();
});

// 监听路由 query 中的 id 变化
watch(
  () => route.query.id, // 监听 id 的变化
  (newOrderId) => {
    if (newOrderId) {
      getOrderDetail();
    }
  }
);
</script>

<style scoped lang="scss">
.mb-2 {
  margin-bottom: 16px;
}

.mt-4 {
  margin-top: 32px;
}

.text-center {
  text-align: center;
}

.detail-item {
  padding: 8px 0;
  line-height: 1.8;

  .label {
    color: #909399;
    margin-right: 8px;
  }
}

:deep(.custom-descriptions .el-descriptions__label) {
  width: 160px;
  /* 可选：强制不换行 */
  white-space: nowrap;
}
:deep(.custom-descriptions .el-descriptions__content) {
  /* 内容区域自动占剩余空间 */
  flex: 1;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 40px;
}

@media print {
  .el-button {
    display: none;
  }
}
</style>
