<template>
  <!-- 对账单选择抽屉 -->
  <el-drawer v-model="drawerVisible" size="70%" direction="rtl" :close-on-click-modal="true" :close-on-press-escape="true" destroy-on-close>
    <template #header>
      <div class="drawer-header">
        <span class="order-title">对账单信息</span>
      </div>
    </template>

    <div class="drawer-content">
      <!-- 对账单明细列表 -->
      <el-table ref="tableRef" :data="tableData" border @selection-change="handleSelectionChange" style="width: 100%" v-loading="loading">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="statementOrderNo" label="对账单号" min-width="140" align="center" />
        <el-table-column prop="statementAmount" label="对账金额" align="center">
          <template #default="scope">
            {{ Number(scope.row.statementAmount || 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="orderNo" label="订单编号" min-width="140" align="center" />
        <el-table-column prop="amount" label="金额" min-width="100" align="center">
          <template #default="scope">
            {{ Number(scope.row.amount || 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="orderTime" label="下单日期" min-width="110" align="center" />
        <el-table-column prop="userName" label="下单人" min-width="100" align="center" />
        <el-table-column prop="userDept" label="部门" min-width="120" align="center" />
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px"
      />
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup name="StatementOrderDrawer" lang="ts">
import { getCustomerOrderDetails, getStatementProductList } from '@/api/bill/statementOrder';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 抽屉显示状态
const drawerVisible = ref(false);
const loading = ref(false);
const tableRef = ref<any>();
const tableData = ref<any[]>([]);
const selectedStatements = ref<any[]>([]);
const total = ref(0);
const customerId = ref<string | number>();

const queryParams = ref({
  pageNum: 1,
  pageSize: 10
});

const mergedProductList = ref<any[]>([]);

/** 打开抽屉 */
const open = (customerIdParam: string | number, preSelectedStatements?: any[]) => {
  customerId.value = customerIdParam;
  selectedStatements.value = preSelectedStatements || [];
  drawerVisible.value = true;

  // 查询数据
  loadData();
};

/** 加载数据 */
const loadData = async () => {
  if (!customerId.value) {
    console.error('customerId为空');
    return;
  }

  loading.value = true;
  try {
    const res = await getCustomerOrderDetails(customerId.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;
    }

    tableData.value = rows;
    total.value = totalCount;
  } catch (error) {
    console.error('加载数据失败:', error);
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

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

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

  try {
    const items = selectedStatements.value
      .map((order) => ({
        statementOrderId: order.statementOrderId,
        orderId: order.orderId
      }))
      .filter((item) => item.statementOrderId != null && item.orderId != null);

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

    const res = await getStatementProductList(items);
    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.quantity || item.num || item.orderQuantity,
        unitPrice: item.price || item.unitPrice || item.salePrice || item.orderPrice,
        productUnit: item.productUnit || item.unitName || '',
        unitName: item.productUnit || item.unitName || '',
        type: item.productType || item.type || '',
        orderId: item.orderId,
        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 = async () => {
  if (selectedStatements.value.length === 0) {
    proxy?.$modal.msgWarning('请至少选择一条订单明细');
    return;
  }

  // 传递订单列表、明细列表和产品列表
  emit('success', {
    statements: selectedStatements.value,
    details: selectedStatements.value,
    products: mergedProductList.value
  });
  drawerVisible.value = false;
};

/** 分页大小改变 */
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  queryParams.value.pageNum = 1;
  loadData();
};

/** 分页页码改变 */
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  loadData();
};

/** 取消 */
const handleCancel = () => {
  drawerVisible.value = false;
};

/** 重置数据 */
const resetData = () => {
  tableData.value = [];
  selectedStatements.value = [];
  mergedProductList.value = [];
  total.value = 0;
  customerId.value = undefined;
  queryParams.value = {
    pageNum: 1,
    pageSize: 10
  };
};

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

defineExpose({
  open
});
</script>

<style scoped lang="scss">
.drawer-header {
  display: flex;
  align-items: center;
  gap: 10px;

  .order-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}

.drawer-content {
  padding: 0 20px 20px;
  height: calc(100% - 60px);
  overflow-y: auto;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
