<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>
        <div class="card-header">
          <span>订单基本信息</span>
          <span> 订单日期:{{ orderInfo.orderTime }}</span>
        </div>
      </template>

      <el-form ref="orderMainFormRef" :model="orderInfo" label-width="100px">
        <el-row :gutter="20">
          <!-- 第一行 -->
          <el-col :span="8">
            <el-form-item label="归属公司">
              <el-input :value="orderInfo.companyName || orderInfo.companyId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称">
              <el-input :value="orderInfo.customerName || orderInfo.customerId" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 第二行 -->
          <el-col :span="8">
            <el-form-item label="信用额度">
              <el-input v-model="orderInfo.creditLimit" placeholder="0" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="临时额度">
              <el-input v-model="orderInfo.temporaryQuota" placeholder="0" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="剩余额度">
              <el-input v-model="orderInfo.remainingQuota" placeholder="0" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 第三行 -->
          <el-col :span="8">
            <el-form-item label="业务人员">
              <el-input v-model="orderInfo.businessStaff" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客服人员">
              <el-input v-model="orderInfo.customerService" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务部门">
              <el-input v-model="orderInfo.businessDept" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 第四行 -->
          <el-col :span="8">
            <el-form-item label="发票类型">
              <el-select v-model="orderInfo.invoiceType" placeholder="请选择" style="width: 100%" disabled>
                <el-option label="普通发票" value="1" />
                <el-option label="增值税发票" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="支付方式">
              <el-select v-model="orderInfo.payType" placeholder="请选择" style="width: 100%" disabled>
                <el-option v-for="dict in pay_method" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预收货日">
              <el-date-picker
                v-model="orderInfo.expectedDeliveryTime"
                type="date"
                placeholder="请选择"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 第五行 -->
          <el-col :span="8">
            <el-form-item label="发货仓库">
              <el-input :value="orderInfo.warehouseName || orderInfo.warehouseId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="费用类型">
              <el-select v-model="orderInfo.expenseType" style="width: 100%" disabled>
                <el-option v-for="dict in fee_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="下单部门">
              <el-input :value="orderInfo.userDeptName || orderInfo.userDept" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 第六行 -->
          <el-col :span="24">
            <el-form-item label="采购事由">
              <el-input v-model="orderInfo.purchaseReason" placeholder="请输入采购事由" type="textarea" :rows="2" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 第七行 -->
          <el-col :span="24">
            <el-form-item label="订单备注">
              <el-input v-model="orderInfo.remark" placeholder="请输入订单备注" type="textarea" :rows="2" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 收货地址 -->
    <el-card shadow="never" class="mb-2">
      <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 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';

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

const buttonLoading = ref(false);
const loading = ref(true);

// 订单信息
const orderInfo = ref<any>({});
// 收货地址信息
const addressInfo = ref<any>({});
// 商品列表
const productList = ref<any[]>([]);

// 计算商品总数
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;
    }

    // 设置收货地址信息
    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 route = useRoute();
  const orderId = route.query.id;
  if (orderId) {
    getOrderDetail(orderId as string);
  } else {
    proxy?.$modal.msgError('缺少订单ID参数');
    router.back();
  }
});
</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>
