<template>
  <!-- 客户订单抽屉 -->
  <el-drawer v-model="drawer.visible" title="对账单信息" size="68%" direction="rtl" :before-close="handleDrawerClose" :close-on-click-modal="true">
    <div class="drawer-content">
      <el-table ref="tableRef" v-loading="loading" :data="orderList" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="orderCode" label="订单编号" min-width="150" align="center" />
        <el-table-column prop="deliverCode" label="发货单编号" min-width="150" align="center" />
        <el-table-column prop="totalAmount" label="金额" min-width="100" align="center">
          <template #default="scope">
            {{ scope.row.totalAmount ? Number(scope.row.totalAmount).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="orderTime" label="下单日期" min-width="120" align="center" />
        <el-table-column prop="createName" label="下单人" min-width="100" align="center" />
        <el-table-column prop="createDeptName" label="部门" min-width="150" align="center" />
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleDrawerClose(() => (drawer.visible = false))">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup name="OrderMainDrawer" lang="ts">
import { listOrderMain } from '@/api/order/orderMain';
import { getCustomerDeliverOrders, getCustomerOrderProductList } from '@/api/order/orderDeliver';
import { OrderMainVO, OrderMainQuery } from '@/api/order/orderMain/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const emit = defineEmits(['success']);

const drawer = reactive<DialogOption>({
  visible: false,
  title: '对账单信息'
});

const loading = ref(false);
const orderList = ref<OrderMainVO[]>([]);
const selectedOrders = ref<OrderMainVO[]>([]);
const mergedProductList = ref<any[]>([]);
const total = ref(0);
const tableRef = ref<any>();
const custId = ref<string | number>();

const queryParams = ref<OrderMainQuery>({
  pageNum: 1,
  pageSize: 10,
  customerId: undefined
});

/** 打开抽屉 */
const open = async (
  customerId: string | number,
  preSelectedOrders?: OrderMainVO[],
  preProductList?: any[],
  preloadedOrderList?: OrderMainVO[],
  preloadedTotalCount?: number
) => {
  custId.value = customerId;

  // 先重置所有状态（包括表格选中）
  reset();
  queryParams.value.customerId = customerId;
  drawer.visible = true;

  // 如果有预加载的订单列表，直接使用，否则请求API
  if (preloadedOrderList && preloadedOrderList.length > 0) {
    orderList.value = preloadedOrderList;
    total.value = preloadedTotalCount || 0;
    loading.value = false;
  } else {
    // 获取订单列表
    await getList();
  }

  // 只有当传入了preSelectedOrders且非空时，才恢复选中状态
  if (preSelectedOrders && preSelectedOrders.length > 0) {
    selectedOrders.value = [...preSelectedOrders];
    mergedProductList.value = preProductList ? [...preProductList] : [];

    // 恢复表格选中状态
    await nextTick();
    restoreSelection(preSelectedOrders);
  }
};

/** 获取订单列表 */
const getList = async () => {
  if (!custId.value) {
    console.error('customerId为空');
    return;
  }

  loading.value = true;
  try {
    const res = await getCustomerDeliverOrders(custId.value, {
      pageNum: queryParams.value.pageNum,
      pageSize: queryParams.value.pageSize
    });

    // 解析数据 - 支持多种返回格式
    let rows: any[] = [];
    let totalCount = 0;

    if (res.rows) {
      rows = res.rows;
      totalCount = res.total || 0;
    } else if (res.data && res.data.rows) {
      rows = res.data.rows;
      totalCount = res.data.total || 0;
    } else if (res.data && Array.isArray(res.data)) {
      rows = res.data;
      totalCount = res.data.length;
    } else if (Array.isArray(res)) {
      rows = res;
      totalCount = res.length;
    }

    orderList.value = rows;
    total.value = totalCount;

    // 数据加载完成后，清空表格选中状态（避免自动恢复之前的选中）
    await nextTick();
    tableRef.value?.clearSelection();
  } catch (error) {
    console.error('加载数据失败:', error);
    orderList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

/** 加载数据 */
const loadData = async () => {};

/** 恢复选中状态 */
const restoreSelection = (preSelectedOrders: OrderMainVO[]) => {
  if (!tableRef.value || !orderList.value.length) {
    return;
  }

  // 根据订单ID恢复选中状态
  preSelectedOrders.forEach((preOrder) => {
    const row = orderList.value.find((order) => order.id === preOrder.id);
    if (row) {
      tableRef.value.toggleRowSelection(row, true);
    }
  });
};

/** 表格选择变化 */
const handleSelectionChange = async (selection: OrderMainVO[]) => {
  selectedOrders.value = selection;
  // 合并选中订单的产品列表
  await mergeProductList();
};

/** 合并选中订单的产品列表 */
const mergeProductList = async () => {
  if (selectedOrders.value.length === 0) {
    mergedProductList.value = [];
    return;
  }

  try {
    // 提取所有选中订单的ID
    const orderIds = selectedOrders.value.map((order) => order.id).filter((id) => id !== undefined);

    if (orderIds.length === 0) {
      mergedProductList.value = [];
      return;
    }

    // 调用接口获取订单商品列表
    const res = await getCustomerOrderProductList(orderIds);
    const productList = res.rows || [];

    // 构建产品列表
    const newProductList: any[] = [];
    productList.forEach((item: any) => {
      const product: any = {
        id: undefined,
        statementOrderId: undefined,
        orderNo: item.orderNo || '',
        productNo: item.productNo || item.skuNo || item.productCode || '',
        itemName: item.productName || item.skuName || item.itemName || item.productFullName || '',
        specifications: item.specifications || item.spec || item.model || item.specModel || '',
        quantity: item.deliverNum,
        unitPrice: item.price || item.unitPrice || item.salePrice || item.orderPrice,
        productUnit: item.productUnit || item.unitName || '',
        subtotal: item.subtotal,
        unitName: item.productUnit || item.unitName || '',
        type: item.productType || item.type || '',
        orderId: item.deliverId,
        categoryId: item.categoryId,
        categoryNo: item.categoryNo || '',
        productId: item.productId || item.id,
        unitId: item.productUnitId || item.unitId
      };
      newProductList.push(product);
    });

    // 更新产品列表
    mergedProductList.value = newProductList;
  } catch (error) {
    console.error('获取订单产品列表失败:', error);
    mergedProductList.value = [];
  }
};

/** 确定选择 */
const handleConfirm = () => {
  if (selectedOrders.value.length === 0) {
    proxy?.$modal.msgWarning('请至少选择一条订单');
    return;
  }

  // 传递订单列表和产品列表
  emit('success', { orders: selectedOrders.value, products: mergedProductList.value });
  drawer.visible = false;
};

/** 重置 */
const reset = () => {
  orderList.value = [];
  selectedOrders.value = [];
  mergedProductList.value = [];
  total.value = 0;
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    customerId: undefined
  };
  tableRef.value?.clearSelection();
};

/** 关闭抽屉前的回调 */
const handleDrawerClose = (done: () => void) => {
  done();
  reset();
};

defineExpose({
  open
});
</script>

<style scoped lang="scss">
.drawer-content {
  padding: 0 20px 20px;
  height: calc(100% - 60px);
  overflow-y: auto;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 20px;
  border-top: 1px solid #e4e7ed;
}
</style>
