<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.createTime }}</el-descriptions-item>
        <el-descriptions-item label="申请单号">{{ orderDetail.returnNo }}</el-descriptions-item>

        <!-- 第二行 -->
        <el-descriptions-item label="订单编号">{{ orderDetail.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <dict-tag :options="return_order_status" :value="orderDetail.returnStatus" />
        </el-descriptions-item>

        <!-- 第三行 -->
        <el-descriptions-item label="退货金额">{{ orderDetail.afterSaleAmount }}</el-descriptions-item>
        <el-descriptions-item label="售后完成时间">{{ orderDetail.processingTime }}</el-descriptions-item>

        <!-- 第四行 -->
        <el-descriptions-item label="售后处理方式"> <dict-tag :options="return_type" :value="orderDetail.serviceType" /></el-descriptions-item>
        <el-descriptions-item label="退货原因">{{ orderDetail.returnReason }}</el-descriptions-item>

        <!-- 以下每项独占一行（span=2） -->
        <el-descriptions-item label="问题描述" :span="2">
          {{ orderDetail.problemDescription || '无' }}
        </el-descriptions-item>

        <el-descriptions-item label="售后备注" :span="2">
          {{ orderDetail.remark || '无' }}
        </el-descriptions-item>

        <el-descriptions-item label="凭证照片" :span="2">
          <!-- 确保 split(',') 将字符串转为数组进行遍历 -->
          <div v-if="orderDetail.voucherPhoto">
            <el-image
              v-for="(url, index) in orderDetail.voucherPhoto.split(',')"
              :key="index"
              :src="url"
              :preview-src-list="orderDetail.voucherPhoto.split(',')"
              style="width: 80px; height: 80px; margin-right: 8px; object-fit: cover"
              fit="cover"
            />
          </div>
          <span v-else>无</span>
        </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 prop="productNo" label="商品编号" />
        <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="productName" label="商品名称" min-width="150" />
        <el-table-column prop="productUnit" label="产品类别" />
        <el-table-column prop="productUnit" label="单位" />
        <el-table-column prop="unitPrice" label="单价" />
        <el-table-column prop="returnQuantity" label="退货数量" />
        <el-table-column prop="totalAmount" label="金额" />
      </el-table>
    </el-card>
    <div class="mt-2 text-right" style="margin-right: 20px">
      <span
        >商品数：{{ totalQuantity }}, 合计金额<span style="color: #f56c6c">{{ totalAmount }}</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="" label="签收数量" align="center" />
        <el-table-column prop="" label="已售后数量" align="center" />
        <el-table-column prop="" label="售后数量" align="center" />
        <el-table-column prop="" label="退回运费" align="center" />
        <el-table-column prop="" label="订单总金额" align="center" />
        <el-table-column prop="" label="退货总金额" align="center" />
      </el-table>
    </el-card>

    <!-- 底部按钮 -->
    <div class="text-center mt-4">
      <el-button @click="goBack">返回</el-button>
    </div>
  </div>
</template>

<script setup name="ReturnDetail" lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getOrderReturn } from '@/api/order/orderReturn';
import { OrderReturnVO } from '@/api/order/orderReturn/types';
import { OrderReturnItemVO } from '@/api/order/orderReturnItem/types';
import { getCustomerInfo } from '@/api/customer/customerFile/customerInfo';
import { CustomerInfoVO } from '@/api/customer/customerFile/customerInfo/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { return_order_status, return_type, fee_type, pay_method } = toRefs<any>(
  proxy?.useDict('return_order_status', 'return_type', 'fee_type', 'pay_method')
);
const route = useRoute();
const router = useRouter();

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

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

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

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

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

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

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

    // 获取客户信息
    if (orderDetail.value.customerId) {
      await getCustomerDetail(orderDetail.value.customerId);
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    proxy?.$modal.msgError('获取订单详情失败');
  }
};

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

// 计算商品总金额（所有商品的小计之和）
const totalAmount = computed(() => {
  return productList.value.reduce((sum, item) => {
    return sum + (Number(item.totalAmount) || 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 getCustomerDetail = async (customerId: string | number) => {
  try {
    const res = await getCustomerInfo(customerId);
    customerInfo.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();
});
</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;
}

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