<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 v-loading="loading" shadow="never" class="mb-2">
      <template #header>
        <span>订单明细</span>
      </template>
      <OrderTreeNode v-if="orderTreeData.id" :order-data="orderTreeData" />
      <el-empty v-else-if="!loading" description="暂无订单数据" />
    </el-card>

    <!-- 底部按钮 -->
    <div class="text-center mt-4">
      <el-button @click="goBack">返回</el-button>
    </div>
    <!-- 物流详情对话框 -->
    <LogisticsDetail v-model="showLogisticsDialog" :order-id="logisticsOrderId" />
  </div>
</template>

<script setup name="SendDetail" lang="ts">
import { ref, computed, onMounted, provide, watch } from 'vue';
import DeliverDialog from './deliverDialog.vue';
import { useRoute, useRouter } from 'vue-router';
import { getOrderMainAndSubOrder } from '@/api/order/orderMain';
import { OrderMainVO, OrderTreeVo } from '@/api/order/orderMain/types';
import OrderTreeNode from './OrderTreeNode.vue';
import { OrderProductVO } from '@/api/order/orderProduct/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')
);

// 向子组件注入字典数据
provide('orderStatusDict', order_status);
provide('paymentStatusDict', payment_status);
provide('feeTypeDict', fee_type);
provide('payMethodDict', pay_method);
const route = useRoute();
const router = useRouter();

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

// 订单树数据
const orderTreeData = ref<OrderTreeVo>({} as OrderTreeVo);
const loading = ref(false);

// 仓库信息
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 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 {
    loading.value = true;
    const res = await getOrderMainAndSubOrder(orderId as any);
    orderDetail.value = res.data;
    orderTreeData.value = res.data;
  } catch (error) {
    console.error('获取订单详情失败:', error);
    proxy?.$modal.msgError('获取订单详情失败');
  } finally {
    loading.value = false;
  }

  // 以下辅助数据异步加载，不阻塞树结构渲染
  loadAuxiliaryData();
};

const loadAuxiliaryData = async () => {
  try {
    if ((orderDetail.value as any).productList) {
      productList.value = (orderDetail.value as any).productList;
    }

    if (orderDetail.value.id) {
      getOrderDeliverListData(orderDetail.value.id);
    }

    if (orderDetail.value.shippingAddressId) {
      getShippingAddressDetail(orderDetail.value.shippingAddressId);
    }
    if (orderDetail.value.warehouseId) {
      getWarehouseDetail(orderDetail.value.warehouseId);
    }
    if (orderDetail.value.companyId) {
      getCompanyDetail(orderDetail.value.companyId);
    }
    if (orderDetail.value.customerId) {
      getCustomerDetail(orderDetail.value.customerId);
    }
    if (orderDetail.value.userDept) {
      getDeptDetail(orderDetail.value.userDept).then((name) => {
        orderDetail.value.userDeptName = name;
      });
    }

    const crrcId = orderDetail.value.parentOrderId || orderDetail.value.id;
    if (crrcId) {
      getOrderMainCrrcExt(crrcId)
        .then((extRes) => {
          crrcExtInfo.value = extRes.data || ({} as OrderMainCrrcExtVO);
        })
        .catch(() => {});
    }
  } catch (error) {
    console.error('加载辅助数据失败:', error);
  }
};

/** 发货按钮操作 */
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 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>
