<template>
  <div class="p-2">
    <!-- 订单流程 -->
    <el-card shadow="never" class="mb-2">
      <div class="order-steps">
        <span class="step-title">订单确认</span>
      </div>
    </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 v-if="orderInfo.assigneeName" label="供应商名称">{{ orderInfo.assigneeName }}</el-descriptions-item>
        <el-descriptions-item label="分配备注">{{ orderInfo.assigneeRemark }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 收货地址 -->
    <el-card shadow="never" class="mb-2" v-if="!orderInfo.dataSource">
      <template #header>
        <div class="card-header">
          <span>收货地址</span>
        </div>
      </template>

      <el-form :model="addressInfo" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="收货人姓名">
              <el-input v-model="addressInfo.consignee" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号码">
              <el-input v-model="addressInfo.phone" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="详细地址">
              <el-input v-model="addressInfo.provincialCityCountry" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-input v-model="addressInfo.address" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 项目订单扩展信息 -->
    <el-card v-if="orderInfo.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>
        <div class="card-header">
          <span>商品明细</span>
        </div>
      </template>
      <el-table :data="productList" border style="width: 100%">
        <el-table-column prop="productCode" label="产品编码" width="130" align="center" />
        <el-table-column label="商品图片" align="center">
          <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 label="商品信息">
          <template #default="scope">
            <div>{{ scope.row.productName }}</div>
            <div v-if="scope.row.brandName">品牌: {{ scope.row.brandName }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="taxRate" label="税率" align="center">
          <template #default="scope"> 增值税{{ scope.row.taxRate }}% </template>
        </el-table-column>
        <el-table-column prop="productUnit" label="单位" align="center" />
        <el-table-column prop="minSellingPrice" label="最低售价" align="center" />
        <el-table-column prop="minOrderQuantity" label="起订量" align="center" />
        <el-table-column prop="unitPrice" label="含税单价" align="center">
          <template #default="scope"> ￥{{ Number(scope.row.unitPrice || 0).toFixed(2) }} </template>
        </el-table-column>
        <el-table-column prop="orderQuantity" label="数量" align="center">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.orderQuantity"
              :min="1"
              :precision="0"
              :controls="false"
              disabled
              @change="handleQuantityChange(scope.$index)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="小计" align="center">
          <template #default="scope"> ￥{{ calculateSubtotal(scope.row).toFixed(2) }} </template>
        </el-table-column>
      </el-table>

      <div class="mt-2 text-right">
        <span>商品数：{{ totalQuantity }} 合计金额：￥ {{ totalAmount.toFixed(2) }}</span>
      </div>
    </el-card>

    <!-- 信息汇总 -->
    <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>

    <!-- 底部按钮 -->
    <div class="text-center mt-4">
      <el-button @click="goBack">返回</el-button>
      <el-button type="primary" :loading="buttonLoading" @click="confirmOrder">确认订单</el-button>
    </div>
  </div>
</template>

<script setup name="OrderAffirm" lang="ts">
import { getOrderMain, orderAffirm } from '@/api/order/orderMain';
import { OrderMainVO } from '@/api/order/orderMain/types';
import { getShippingAddress } from '@/api/customer/customerFile/shippingAddress';
import { getCompany } from '@/api/company/company';
import { getWarehouse } from '@/api/company/warehouse';
import { getCustomerInfo } from '@/api/customer/customerFile/customerInfo';
import { getDept } from '@/api/system/dept';
import { useRoute, useRouter } from 'vue-router';
import { getOrderMainCrrcExt } from '@/api/order/orderMainCrrcExt';
import { OrderMainCrrcExtVO } from '@/api/order/orderMainCrrcExt/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pay_method, fee_type } = toRefs<any>(proxy?.useDict('pay_method', 'fee_type'));

const buttonLoading = ref(false);
const loading = ref(true);
// 获取路由和 router 实例
const route = useRoute();
const router = useRouter();
// 订单信息
const orderInfo = ref<any>({});
// 收货地址信息
const addressInfo = ref<any>({});
// 商品列表
const productList = ref<any[]>([]);
// 中车订单扩展信息
const crrcExtInfo = ref<OrderMainCrrcExtVO>({} as OrderMainCrrcExtVO);

// 计算商品总数
const totalQuantity = computed(() => {
  return productList.value.reduce((sum, item) => {
    return sum + (Number(item.orderQuantity) || 0);
  }, 0);
});

// 计算商品总金额
const totalAmount = computed(() => {
  return productList.value.reduce((sum, item) => {
    return sum + calculateSubtotal(item);
  }, 0);
});

// 计算应付款金额（订单总金额 + 运费）
const payableAmount = computed(() => {
  const shipping = Number(orderInfo.value.shippingFee) || 0;
  return totalAmount.value + shipping;
});

// 汇总数据（用于表格显示）
const summaryData = computed(() => {
  return [
    {
      quantity: totalQuantity.value,
      shippingFee: `￥${(Number(orderInfo.value.shippingFee) || 0).toFixed(2)}`,
      totalAmount: `￥${totalAmount.value.toFixed(2)}`,
      payableAmount: `￥${payableAmount.value.toFixed(2)}`
    }
  ];
});

// 计算单个商品小计
const calculateSubtotal = (product: any) => {
  return Number(product.orderQuantity || 0) * Number(product.unitPrice || 0);
};

// 数量变化时重新计算
const handleQuantityChange = (index: number) => {
  // 数量变化时自动重新计算小计
  const product = productList.value[index];
  if (product) {
    // 确保数量至少为1
    if (product.orderQuantity < 1) {
      product.orderQuantity = 1;
    }
  }
};

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

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

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

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

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

// 获取订单详情
const getOrderDetail = async (orderId: string | number) => {
  try {
    loading.value = true;
    const res = await getOrderMain(orderId);
    const data = res.data;

    // 设置订单基本信息
    orderInfo.value = data || {};

    // 获取并设置公司名称
    if (data?.companyId) {
      const companyName = await getCompanyDetail(data.companyId);
      orderInfo.value.companyName = companyName;
    }

    // 获取并设置客户名称
    if (data?.customerId) {
      const customerName = await getCustomerDetail(data.customerId);
      orderInfo.value.customerName = customerName;
    }

    // 获取并设置仓库名称
    if (data?.warehouseId) {
      const warehouseName = await getWarehouseDetail(data.warehouseId);
      orderInfo.value.warehouseName = warehouseName;
    }

    // 获取并设置下单部门名称
    if (data?.userDept) {
      const deptName = await getDeptDetail(data.userDept);
      orderInfo.value.userDeptName = deptName;
    }

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

    // 设置收货地址信息
    if ((data as any)?.shippingAddressVo) {
      addressInfo.value = (data as any).shippingAddressVo;
    } else if (data?.shippingAddressId) {
      // 如果没有地址对象，调用API获取地址详情
      const addressDetail = await getShippingAddressDetail(data.shippingAddressId);
      if (addressDetail) {
        addressInfo.value = addressDetail;
      } else {
        addressInfo.value = { ...addressInfo.value, id: data.shippingAddressId };
      }
    }

    // 设置商品列表 - 支持多种可能的字段名
    let products = [];
    if ((data as any)?.orderProductVoList && (data as any).orderProductVoList.length > 0) {
      products = (data as any).orderProductVoList;
    } else if ((data as any)?.orderProductList && (data as any).orderProductList.length > 0) {
      products = (data as any).orderProductList;
    } else if ((data as any)?.productList && (data as any).productList.length > 0) {
      products = (data as any).productList;
    }

    if (products.length > 0) {
      productList.value = products.map((product: any) => ({
        ...product,
        // 确保有正确的数量字段
        orderQuantity: product.orderQuantity || product.quantity || 1,
        // 确保有正确的单价字段
        unitPrice: product.unitPrice || product.orderPrice || product.price || 0,
        // 确保有正确的产品编码字段
        productCode: product.productCode || product.productNo || product.code || '',
        // 确保有正确的产品名称字段
        productName: product.productName || product.name || '',
        // 确保有正确的单位字段
        unitName: product.unitName || product.unit || ''
      }));
      console.log('商品列表数据:', productList.value); // 调试日志
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    proxy?.$modal.msgError('获取订单详情失败');
  } finally {
    loading.value = false;
  }
};

// 确认订单
const confirmOrder = async () => {
  // 验证商品数量
  for (const product of productList.value) {
    if (!product.orderQuantity || product.orderQuantity <= 0) {
      proxy?.$modal.msgError('商品数量必须大于0');
      return;
    }
  }

  try {
    buttonLoading.value = true;

    // 组装商品数据
    const orderProductBos = productList.value.map((product) => ({
      id: product.id,
      orderQuantity: product.orderQuantity
    }));

    // 调用确认订单接口
    await orderAffirm({
      id: orderInfo.value.id,
      orderProductBos: orderProductBos
    } as any);

    proxy?.$modal.msgSuccess('订单确认成功');

    // 返回订单列表
    router.push('/order-manage/order-list');
  } catch (error) {
    console.error('确认订单失败:', error);
    proxy?.$modal.msgError('确认订单失败，请重试');
  } finally {
    buttonLoading.value = false;
  }
};

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

// 页面加载时获取订单ID并加载订单详情
onMounted(() => {
  const orderId = route.query.id;
  if (orderId) {
    getOrderDetail(orderId as string);
  } else {
    proxy?.$modal.msgError('缺少订单ID参数');
    router.back();
  }
});
// 监听路由 query 中的 id 变化
watch(
  () => route.query.id, // 监听 id 的变化
  (newOrderId) => {
    if (newOrderId) {
      getOrderDetail(newOrderId as string);
    }
  }
);
</script>

<style scoped lang="scss">
.order-steps {
  padding: 10px 0;

  .step-title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.mb-2 {
  margin-bottom: 16px;
}

.mt-2 {
  margin-top: 16px;
}

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

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

.text-center {
  text-align: center;
}
</style>
