gaoluyang
3 天以前 00ef76a2e286e338fa3c648ce183e3533ce006ad
src/views/basicInformation/index.vue
@@ -1,10 +1,7 @@
<template>
  <div> <el-form :inline="true" :model="queryParams" class="search-form">
      <el-form-item label="搜索" v-if="tabName === 'supplier' || tabName === 'customer'">
        <el-input v-model="queryParams.searchAll" placeholder="供应商/识别码/详细地址" clearable />
      </el-form-item>
      <el-form-item label="搜索" v-if="tabName === 'coal' || tabName === 'coalQualityMaintenance'">
        <el-input v-model="queryParams.searchAll" placeholder="请输入搜索信息" clearable />
      <el-form-item label="搜索" v-if="shouldShowSearch">
        <el-input v-model="queryParams.searchAll" :placeholder="searchPlaceholder" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
@@ -21,12 +18,25 @@
      <el-row :gutter="24" class="table-toolbar">
        <el-button type="primary" :icon="Plus" @click="handleAdd">新建</el-button>
        <el-button type="danger" :icon="Delete" @click="handleDelete">删除</el-button>
        <el-button type="info" :icon="Download" @click="handleExport" v-show="tabName === 'supplier' || tabName === 'customer'">导出</el-button>
      </el-row>
      <!-- 表格组件 -->
        <el-button type="info" :icon="Download" @click="handleExport" v-show="canExport">导出</el-button>
      </el-row> <!-- 表格组件 -->
      <div>
        <data-table :loading="loading" :table-data="tableData" :columns="columns"
          @selection-change="handleSelectionChange" @edit="handleEdit" :show-selection="true" :border="true" />
          @selection-change="handleSelectionChange" @edit="handleEdit" :show-selection="true" :border="true">          <!-- 字段名称列的自定义插槽 - 显示为标签 -->
          <template v-if="tabName === 'coalQualityMaintenance'" #coalFields="{ row }">
            <template v-if="typeof row.coalFields === 'string' && row.coalFields.includes(',')">
              <el-tag v-for="(field, index) in row.coalFields.split(',')" :key="index" type="primary" size="small"
                style="margin-right: 4px; margin-bottom: 2px;">
                {{ getFieldDisplayName(field.trim()) }}
              </el-tag>
            </template>
            <template v-else>
              <el-tag type="primary" size="small">
                {{ getFieldDisplayName(row.coalFields) || '--' }}
              </el-tag>
            </template>
          </template>
        </data-table>
      </div>
      <pagination v-if="total > 0" :page="pageNum" :limit="pageSizes" :total="total" @pagination="handPagination"
        :layout="'total, prev, pager, next, jumper'" />
@@ -38,20 +48,23 @@
        :addOrEdit="addOrEdit" @beforeClose="handleBeforeClose" />
      <Coal v-if="tabName === 'coal'" v-model:copyForm="copyForm" v-model:coalDialogFormVisible="dialogFormVisible"
        :form="form" :title="title" :addOrEdit="addOrEdit" @submit="handleSubmit" />
      <coalQualityMaintenance v-if="tabName === 'coalQualityMaintenance'"
      <coalQualityMaintenance v-if="tabName === 'coalQualityMaintenance'" v-model:copyForm="copyForm"
        v-model:coalQualityMaintenanceDialogFormVisible="dialogFormVisible" :form="form" :title="title"
        :addOrEdit="addOrEdit" @submit="handleSubmit" />
      <coalMeiZhiZiDuanWeiHu v-if="tabName === 'coalMeiZhiZiDuanWeiHu'"
        v-model:coalMaintenanceFieldDialogVisible="dialogFormVisible" :form="form" :title="title"
        :addOrEdit="addOrEdit" @submit="handleSubmit" />
      <coalMeiZhiZiDuanWeiHu v-if="tabName === 'coalMeiZhiZiDuanWeiHu'" v-model:copyForm="copyForm"
        v-model:coalMaintenanceFieldDialogVisible="dialogFormVisible" :form="form" :title="title" :addOrEdit="addOrEdit"
        @submit="handleSubmit" />
    </el-card>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed } from "vue";
// ===== 核心依赖导入 =====
import { ref, reactive, onMounted, computed, getCurrentInstance } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Edit, Delete, Download } from "@element-plus/icons-vue";
// ===== 组件导入 =====
import DataTable from "@/components/Table/ETable.vue";
import Pagination from "@/components/Pagination";
import Supplier from "./mould/supplier.vue";
@@ -59,54 +72,89 @@
import Coal from "./mould/coal.vue";
import coalQualityMaintenance from "./mould/coalQualityMaintenance.vue";
import coalMeiZhiZiDuanWeiHu from "./mould/coalMeiZhiZiDuanWeiHu.vue";
const { proxy } = getCurrentInstance()
import { getSupply, addOrEditSupply, delSupply } from "@/api/basicInformation/supplier.js";
// ===== API 服务导入 =====
import { getSupply, delSupply } from "@/api/basicInformation/supplier.js";
import { getCoalInfo, delCoalInfo } from "@/api/basicInformation/coal.js";
import { getCoalQuality, delCoalQuality } from "@/api/basicInformation/coalQualityMaintenance.js";
import { testUserList } from "@/api/tool/publicInterface.js";
import { getAreaOptions } from "@/api/system/area.js";
import { getCustomerList, delCustomer } from "@/api/basicInformation/customer.js";
import { coalField, deleteCoalField } from "@/api/basicInformation/coalFieldMaintenance.js";
import { getCoalFieldList, getCoalPlanList } from "@/api/basicInformation/coalQualityMaintenance";
// 弹窗
const coalMaintenanceFieldDialogVisible = ref(false);
const coalQualityMaintenanceDialogFormVisible = ref(false);
const customerDialogFormVisible = ref(false);
const coalDialogFormVisible = ref(false);
const supplierDialogFormVisible = ref(false);
const { proxy } = getCurrentInstance();
// ===== 响应式状态管理 =====
// 弹窗控制状态
const dialogFormVisible = ref(false);
const form = ref({});
const title = ref("");
const copyForm = ref({});
// 用户列表数据
const addOrEdit = ref("add");
// 数据缓存映射
const userList = ref([]);
// 用户映射表,用于快速查找
const userMap = ref({});
// 地址映射表,用于快速查找地址名称
const addressMap = ref({});
// 当前标签
const userMap = ref({}); // 用户ID -> 用户名映射表
const addressMap = ref({}); // 地址ID -> 地址信息映射表
const coalFieldList = ref([]); // 煤质字段列表
// 页面状态控制
const tabName = ref("supplier");
// 状态变量
const loading = ref(false);
const total = ref(0);
const activeTab = ref("supplier");
// 分页状态管理
const pageNum = ref(1);
const pageSizes = ref(10);
const activeTab = ref("supplier");
const total = ref(0);
// 表格状态管理
const selectedRows = ref([]);
const tableData = ref([]);
const columns = ref();
// 查询参数
const queryParams = reactive({
});
const queryParams = reactive({});
// 地址选择数据
const addressSelectOptions = ref([]);
const fetchAreaOptions = async () => {
  addressSelectOptions.value = [];
  const res = await getAreaOptions();
  if (res.code === 200) {
    addressSelectOptions.value = res.data;
    buildAddressMap(res.data); // 构建地址映射表
  }
}
// 构建地址映射表,用于快速查找地址名称
// ===== 配置常量 =====
// 标签页配置
const tabs = reactive([
  { name: "supplier", label: "供应商信息" },
  { name: "customer", label: "客户信息" },
  { name: "coal", label: "煤种信息" },
  { name: "coalQualityMaintenance", label: "煤质方案" },
  { name: "coalMeiZhiZiDuanWeiHu", label: "煤质字段" }
]);
// ===== 工具函数 =====
/**
 * 获取地址选择数据并构建映射表
 * @description 异步获取地址数据,构建快速查找的映射表
 */
const fetchAreaOptions = async () => {
  try {
    addressSelectOptions.value = [];
    const res = await getAreaOptions();
    if (res.code === 200) {
      addressSelectOptions.value = res.data;
      buildAddressMap(res.data);
    }
  } catch (error) {
    console.error('获取地址选项失败:', error);
  }
};
/**
 * 构建地址映射表
 * @param {Array} areaData - 地址数据
 * @description 递归构建地址映射表,支持多级地址查找
 */
const buildAddressMap = (areaData) => {
  const buildMap = (list, pathList = []) => {
    list.forEach(item => {
@@ -123,22 +171,32 @@
  buildMap(areaData);
};
// 地址格式化函数
/**
 * 格式化地址数组为显示字符串
 * @param {Array} addressIds - 地址ID数组
 * @returns {string} 格式化后的地址字符串
 * @description 将地址ID数组转换为可读的地址字符串
 */
const formatAddressArray = (addressIds) => {
  // 如果地址映射表还没有准备好,显示 --
  if (!addressMap.value || Object.keys(addressMap.value).length === 0 || !addressIds || !Array.isArray(addressIds) || addressIds.length === 0 || addressIds.every(id => !id)) {
  if (!addressMap.value || Object.keys(addressMap.value).length === 0 ||
      !addressIds || !Array.isArray(addressIds) || addressIds.length === 0 ||
      addressIds.every(id => !id)) {
    return '--';
  }
  const addressNames = addressIds.map(id => {
    return addressMap.value[id]?.name || '--';
  });
  // 如果所有地址名称都是 '--',则返回 '--'
  const addressNames = addressIds.map(id => addressMap.value[id]?.name || '--');
  if (addressNames.every(name => name === '--')) {
    return '--';
  }
  return addressNames.filter(name => name !== '--').join(' / ');
};
// 获取用户列表数据
/**
 * 获取用户列表数据并构建映射表
 * @description 获取用户数据并构建ID到用户名的映射关系
 */
const getUserList = async () => {
  try {
    const res = await testUserList();
@@ -152,39 +210,93 @@
    console.error('获取用户列表失败:', error);
  }
};
onMounted(async () => {
  await handleTabClick({ props: { name: "supplier" } });
  await fetchAreaOptions(); // 先获取地址选择数据并构建映射表
  await getUserList(); // 获取用户列表
/**
 * 获取煤质字段数据
 * @description 获取煤质字段列表,用于字段名称匹配
 */
const coalFieldData = async () => {
  try {
    const { data, code } = await getCoalFieldList();
    if (code === 200) {
      coalFieldList.value = data;
    }
  } catch (error) {
    console.error('获取煤质字段数据失败:', error);
  }
};
/**
 * 根据字段ID获取字段显示名称
 * @param {string|number} fieldId - 字段ID
 * @returns {string} 字段显示名称
 * @description 通过字段ID匹配对应的字段名称
 */
const getFieldDisplayName = (fieldId) => {
  if (!fieldId) return '--';
  const numId = parseInt(fieldId);
  const matchedField = coalFieldList.value.find(item => item.id === numId);
  return matchedField ? matchedField.fieldName : numId;
};
// ===== 计算属性 =====
/**
 * 当前标签页是否支持导出功能
 */
const canExport = computed(() => {
  return ['supplier', 'customer'].includes(tabName.value);
});
const columns = ref();
// 标签页数据
const tabs = reactive([
  { name: "supplier", label: "供应商信息" },
  { name: "customer", label: "客户信息" },
  { name: "coal", label: "煤种信息" },
  { name: "coalQualityMaintenance", label: "煤质方案" },
  { name: "coalMeiZhiZiDuanWeiHu", label: "煤质字段" }
]);
// 是否编辑
const addOrEdit = ref("add");
// 表格数据
const tableData = ref([]);
// supplier 供应商数据
/**
 * 搜索框占位符文本
 */
const searchPlaceholder = computed(() => {
  const placeholderMap = {
    supplier: "供应商/识别码/详细地址",
    customer: "供应商/识别码/详细地址",
    coal: "请输入搜索信息",
    coalQualityMaintenance: "请输入搜索信息",
    coalMeiZhiZiDuanWeiHu: "请输入搜索信息"
  };
  return placeholderMap[tabName.value] || "请输入搜索信息";
});
/**
 * 是否显示搜索框
 */
const shouldShowSearch = computed(() => {
  return ['supplier', 'customer', 'coal', 'coalQualityMaintenance','coalMeiZhiZiDuanWeiHu'].includes(tabName.value);
});
/**
 * 当前选中行数量
 */
const selectedCount = computed(() => selectedRows.value.length);
/**
 * 是否有选中的行
 */
const hasSelectedRows = computed(() => selectedCount.value > 0);
// ===== 表格列配置 =====
/**
 * 供应商表格列配置
 */
const supplierColumns = ref([
  { prop: "supplierName", label: "供应商名称", minWidth: 100 },
  { prop: "taxpayerId", label: "统一人识别号", minWidth: 170 }, {
  { prop: "taxpayerId", label: "统一人识别号", minWidth: 170 },
  {
    prop: "bids",
    label: "经营地址",
    minWidth: 150,
    showOverflowTooltip: true,
    formatter: (row, column, cellValue) => {
      let arr = [
        row.bprovinceId,
        row.bcityId,
        row.bdistrictId,
      ]
      return formatAddressArray(arr);
    formatter: (row) => {
      const addressIds = [row.bprovinceId, row.bcityId, row.bdistrictId];
      return formatAddressArray(addressIds);
    }
  },
  { prop: "businessAddress", label: "经营详细地址", minWidth: 150 },
@@ -196,39 +308,18 @@
    label: "联系人地址",
    minWidth: 150,
    showOverflowTooltip: true,
    formatter: (row, column, cellValue) => {
      let arr = [
        row.cprovinceId,
        row.ccityId,
        row.cdistrictId,
      ]
      return formatAddressArray(arr);
    formatter: (row) => {
      const addressIds = [row.cprovinceId, row.ccityId, row.cdistrictId];
      return formatAddressArray(addressIds);
    }
  }, { prop: "contactAddress", label: "联系人详细地址", minWidth: 120 },
  // {
  //   prop: "maintainerId",
  //   label: "维护人",
  //   minWidth: 80,
  //   formatter: (row, column, cellValue) => {
  //     // 如果用户映射表还没有准备好,显示 --
  //     if (!userMap.value || Object.keys(userMap.value).length === 0) {
  //       return '--';
  //     }
  //     // 如果值为空或null,显示 --
  //     if (cellValue === null || cellValue === undefined || cellValue === '') {
  //       return '--';
  //     }
  //     // 如果用户映射表中有对应的用户名,返回用户名
  //     if (userMap.value[cellValue]) {
  //       return userMap.value[cellValue];
  //     }
  //     // 如果没有匹配的用户,显示 --
  //     return '--';
  //   }
  // },
  },
  { prop: "contactAddress", label: "联系人详细地址", minWidth: 120 },
  { prop: "createTime", label: "维护日期", minWidth: 120 },
]);
// customer 客户数据
/**
 * 客户表格列配置
 */
const customerColumns = ref([
  { prop: "customerName", label: "客户名称", minWidth: 100 },
  { prop: "taxpayerId", label: "统一人识别号", minWidth: 120 },
@@ -237,13 +328,9 @@
    label: "经营地址",
    minWidth: 150,
    showOverflowTooltip: true,
    formatter: (row, column, cellValue) => {
      let arr = [
        row.businessProvinceId,
        row.businessCityId,
        row.businessDistrictId,
      ]
      return formatAddressArray(arr);
    formatter: (row) => {
      const addressIds = [row.businessProvinceId, row.businessCityId, row.businessDistrictId];
      return formatAddressArray(addressIds);
    }
  },
  { prop: "businessAddress", label: "详细地址", minWidth: 150 },
@@ -256,149 +343,189 @@
    label: "联系人地址",
    minWidth: 150,
    showOverflowTooltip: true,
    formatter: (row, column, cellValue) => {
      let arr = [
        row.provinceId,
        row.cityId,
        row.districtId,
      ]
      return formatAddressArray(arr);
    formatter: (row) => {
      const addressIds = [row.provinceId, row.cityId, row.districtId];
      return formatAddressArray(addressIds);
    }
  },
  { prop: "contactAddress", label: "联系人详细地址", minWidth: 150 },
  { prop: "updateTime", label: "维护日期", minWidth: 100 },
]);
// coal 煤种数据
/**
 * 煤种表格列配置
 */
const coalColumns = ref([
  { prop: "coal", label: "煤种名称", minWidth: 200 }, {
  { prop: "coal", label: "煤种名称", minWidth: 200 },
  {
    prop: "maintainerId",
    label: "维护人",
    minWidth: 120,
    formatter: (row, column, cellValue) => {
      // 如果用户映射表还没有准备好,显示 --
      if (!userMap.value || Object.keys(userMap.value).length === 0) {
        return '--';
      }
      // 如果值为空或null,显示 --
      if (cellValue === null || cellValue === undefined || cellValue === '') {
        return '--';
      }
      // 如果用户映射表中有对应的用户名,返回用户名
      if (userMap.value[cellValue]) {
        return userMap.value[cellValue];
      }
      // 如果没有匹配的用户,显示 --
      return '--';
      return userMap.value[cellValue] || '--';
    }
  },
  { prop: "maintenanceDate", label: "维护日期", minWidth: 150 },
]);
// coalQualityMaintenance 煤质维护数据
/**
 * 煤质方案表格列配置
 */
const coalQualityMaintenanceColumns = ref([
  { prop: "coal", label: "煤种名称", minWidth: 200 },
  { prop: "totalMoisture", label: "全水含量百分比 (%)", minWidth: 200 },
  { prop: "analysisMoisture", label: "分析水含量百分比 (%)", minWidth: 200 },
  { prop: "volatileMatter", label: "挥发分百分比 (%)", minWidth: 100 },
  { prop: "sulfurContent", label: "硫含量百分比 (%)", minWidth: 100 },
  { prop: "contacts", label: "固定碳百分比 (%)", minWidth: 100 },
  { prop: "contactAddress", label: "高位发热量", minWidth: 100 },
  { prop: "maintainer", label: "低位发热量", minWidth: 100 },
  { prop: "plan", label: "方案名称", minWidth: 100 },
  {
    prop: "coalFields",
    label: "字段名称",
    minWidth: 200,
    showOverflowTooltip: true,
    slot: true,
    formatter: (row, column, cellValue) => {
      if (Array.isArray(cellValue)) {
        return cellValue.map(item => item);
      }
      return cellValue || '--';
    }
  },
  { prop: "schemeDesc", label: "字段描述", minWidth: 100 },
]);
/**
 * 煤质字段表格列配置
 */
const coalMeiZhiZiDuanWeiHuColumns = ref([
  { prop: "fieldName", label: "字段名称", minWidth: 200 },
  { prop: "fieldDescription", label: "字段描述", minWidth: 200 },
]);
// 标签页点击
// ===== 事件处理函数 =====
/**
 * 标签页切换事件处理
 * @param {Object} tab - 标签页对象
 * @description 处理标签页切换,重置表单和状态,加载对应数据
 */
const handleTabClick = (tab) => {
  // 重置表单和状态
  form.value = {};
  addOrEdit.value = "add";
  loading.value = true;
  tabName.value = tab.props.name;
  tableData.value = [];
  switch (tabName.value) {
    case "supplier":
  // 根据标签页类型设置对应的列配置
  const tabConfig = {
    supplier: () => {
      columns.value = supplierColumns.value;
      dialogFormVisible.value = supplierDialogFormVisible.value;
      getList("supplier");
      break;
    case "customer":
      getList();
    },
    customer: () => {
      columns.value = customerColumns.value;
      dialogFormVisible.value = customerDialogFormVisible.value;
      getList("customer");
      break;
    case "coal":
      getList();
    },
    coal: () => {
      columns.value = coalColumns.value;
      dialogFormVisible.value = coalDialogFormVisible.value;
      getList("coal");
      break;
    case "coalQualityMaintenance":
      getList();
    },
    coalQualityMaintenance: () => {
      columns.value = coalQualityMaintenanceColumns.value;
      dialogFormVisible.value = coalQualityMaintenanceDialogFormVisible.value;
      getList("coalQualityMaintenance");
      break;
    case "coalMeiZhiZiDuanWeiHu":
      getList();
      coalFieldData(); // 加载煤质字段数据
    },
    coalMeiZhiZiDuanWeiHu: () => {
      columns.value = coalMeiZhiZiDuanWeiHuColumns.value;
      dialogFormVisible.value = coalMaintenanceFieldDialogVisible.value;
      getList("coalMeiZhiZiDuanWeiHu");
      break;
      getList();
    }
  };
  // 执行对应的配置函数
  const configFn = tabConfig[tabName.value];
  if (configFn) {
    configFn();
  }
};
// 重置查询
/**
 * 重置查询条件
 * @description 重置查询参数并重新加载数据
 */
const resetQuery = () => {
  Object.keys(queryParams).forEach((key) => {
    if (key !== "pageNum" && key !== "pageSizes") {
      queryParams[key] = "";
    }
  });
  getList()
  getList();
};
// 新增
/**
 * 搜索功能
 * @description 重置页码并执行搜索
 */
const search = () => {
  pageNum.value = 1;
  getList();
};
/**
 * 新增按钮点击处理
 */
const handleAdd = () => {
  addOrEdit.value = "add";
  handleAddEdit(tabName.value);
};
// 新增编辑
const handleAddEdit = (tabName) => {
  addOrEdit.value == "add" ? title.value = "新增" : title.value = "编辑";
  if (tabName === "supplier") {
    dialogFormVisible.value = true;
    title.value = title.value + "供应商信息";
    openDialog();
  } else if (tabName === "customer") {
    dialogFormVisible.value = true;
    title.value = title.value + "客户信息";
    openDialog();
  } else if (tabName === "coal") {
    dialogFormVisible.value = true;
    title.value = title.value + "煤种信息";
    openDialog();
  } else if (tabName === "coalQualityMaintenance") {
    dialogFormVisible.value = true;
    title.value = title.value + "煤质方案维护";
    openDialog();
  } else if (tabName === "coalMeiZhiZiDuanWeiHu") {
    dialogFormVisible.value = true;
    title.value = title.value + "煤质字段维护";
    openDialog();
  }
/**
 * 新增/编辑弹窗处理
 * @param {string} currentTabName - 当前标签页名称
 * @description 根据标签页类型设置弹窗标题并打开弹窗
 */
const handleAddEdit = (currentTabName) => {
  const actionText = addOrEdit.value === "add" ? "新增" : "编辑";
  const tabTitleMap = {
    supplier: "供应商信息",
    customer: "客户信息",
    coal: "煤种信息",
    coalQualityMaintenance: "煤质方案维护",
    coalMeiZhiZiDuanWeiHu: "煤质字段维护"
  };
  title.value = `${actionText}${tabTitleMap[currentTabName] || ''}`;
  openDialog();
};
// 打开弹窗
/**
 * 打开弹窗
 * @description 根据编辑状态决定是否复制表单数据
 */
const openDialog = () => {
  if (addOrEdit.value === "edit") {
    copyForm.value = JSON.parse(JSON.stringify(form.value));
    dialogFormVisible.value = true;
    return;
  } else {
    form.value = {};
  }
  form.value = {};
  dialogFormVisible.value = true;
};
// 分页
/**
 * 分页处理
 * @param {Object} val - 分页参数对象
 */
const handPagination = (val) => {
  pageNum.value = val.page;
  pageSizes.value = val.limit;
  getList();
};
// 提交表单
/**
 * 表单提交处理
 * @param {Object} val - 提交结果对象
 */
const handleSubmit = async (val) => {
  if (val.result.code !== 200) {
    ElMessage.error("操作失败:" + val.result.msg);
@@ -408,179 +535,210 @@
  dialogFormVisible.value = false;
  getList();
};
/**
 * 弹窗显示状态处理
 * @param {boolean} value - 显示状态
 */
const handleDialogFormVisible = (value) => {
  dialogFormVisible.value = value;
};
// 选择行
/**
 * 表格行选择处理
 * @param {Array} selection - 选中的行数据
 */
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};
// 编辑
/**
 * 编辑按钮点击处理
 * @param {Object} row - 行数据
 * @description 处理编辑操作,构建地址数组并打开编辑弹窗
 */
const handleEdit = (row) => {
  form.value = JSON.parse(JSON.stringify(row));
  // 构建供应商业务地址数组
  if (form.value.bprovinceId && form.value.bdistrictId && form.value.bcityId) {
    form.value.bids = [
      row.bprovinceId,
      row.bcityId,
      row.bdistrictId,
    ];
    form.value.bids = [row.bprovinceId, row.bcityId, row.bdistrictId];
  }
  // 构建供应商联系地址数组
  if (form.value.cprovinceId && form.value.cdistrictId && form.value.ccityId) {
    form.value.cids = [
      row.cprovinceId,
      row.ccityId,
      row.cdistrictId,
    ];
    form.value.cids = [row.cprovinceId, row.ccityId, row.cdistrictId];
  }
  // 构建客户业务地址数组
  if (form.value.businessCityId && form.value.businessDistrictId && form.value.businessProvinceId) {
    form.value.bids = [
      row.businessProvinceId,
      row.businessCityId,
      row.businessDistrictId,
    ];
    form.value.bids = [row.businessProvinceId, row.businessCityId, row.businessDistrictId];
  }
  // 构建客户联系地址数组
  if (form.value.cityId && form.value.districtId && form.value.provinceId) {
    form.value.cids = [
      row.provinceId,
      row.cityId,
      row.districtId,
    ];
    form.value.cids = [row.provinceId, row.cityId, row.districtId];
  }
  addOrEdit.value = "edit";
  handleAddEdit(tabName.value);
};
// 批量删除
const handleDelete = () => {
/**
 * 批量删除处理
 * @description 批量删除选中的记录
 */
const handleDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的数据");
    return;
  }
  let arr = reactive([]);
  selectedRows.value.forEach(element => {
    return arr.push(element.id);
  });
  ElMessageBox.confirm("确定删除选中的数据吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        let res;
        if (tabName.value === "supplier") {
          res = await delSupply(arr);
        } else if (tabName.value === "coal") {
          res = await delCoalInfo(arr);
        } else if (tabName.value === "coalQualityMaintenance") {
          res = await delCoalQuality(arr);
        } else if (tabName.value === "customer") {
          res = await delCustomer(arr);
        }
        if (res.code !== 200 && res.meg == "操作成功") {
          ElMessage.error("删除失败:" + res.msg);
          return;
        }
        ElMessage.success("删除成功");
        await getList();
      } catch (e) {
        console.error(e);
        ElMessage.error("删除失败,请稍后再试");
      } finally {
        selectedRows.value = [];
      }
    }).catch(() => {
      ElMessage.info("已取消删除操作");
  const deleteIds = selectedRows.value.map(item => item.id);
  try {
    await ElMessageBox.confirm("确定删除选中的数据吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
}
// 关闭弹窗
    const deleteApiMap = {
      supplier: delSupply,
      coal: delCoalInfo,
      coalQualityMaintenance: () => { throw new Error('delCoalQuality API not imported'); },
      customer: delCustomer,
      coalMeiZhiZiDuanWeiHu: deleteCoalField
    };
    const deleteApi = deleteApiMap[tabName.value];
    if (!deleteApi) {
      ElMessage.error("删除接口未配置");
      return;
    }
    const res = await deleteApi(deleteIds);
    if (res.code !== 200 && res.msg !== "操作成功") {
      ElMessage.error("删除失败:" + res.msg);
      return;
    }
    ElMessage.success("删除成功");
    await getList();
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('删除操作失败:', error);
      ElMessage.error("删除失败,请稍后再试");
    } else {
      ElMessage.info("已取消删除操作");
    }
  } finally {
    selectedRows.value = [];
  }
};
/**
 * 关闭弹窗处理
 */
const handleBeforeClose = () => {
  dialogFormVisible.value = false;
  form.value = {};
};
const handleExport = () => {
  if (tabName.value === "supplier") {
    Export("/supply/export", "供应商信息");
  } else if (tabName.value === "customer") {
    Export("/customer/export", "客户信息");
  } else if (tabName.value === "coal") {
    Export("/supply/export", "煤种信息");
  } else if (tabName.value === "coalQualityMaintenance") {
    Export("/supply/export", "煤质维护信息");
/**
 * 导出功能处理
 */
const handleExport = () => {
  const exportConfig = {
    supplier: { api: "/supply/export", name: "供应商信息" },
    customer: { api: "/customer/export", name: "客户信息" },
    coal: { api: "/supply/export", name: "煤种信息" },
    coalQualityMaintenance: { api: "/supply/export", name: "煤质维护信息" }
  };
  const config = exportConfig[tabName.value];
  if (config) {
    exportData(config.api, config.name);
  }
}
const Export = (api, name) => {
  proxy.download(api, {
    ...queryParams.value
  }, `${name}${new Date().getTime()}.xlsx`)
};
/**
 * 导出数据
 * @param {string} api - 导出接口路径
 * @param {string} name - 导出文件名前缀
 */
const exportData = (api, name) => {
  proxy.download(api, { ...queryParams }, `${name}${new Date().getTime()}.xlsx`);
  ElMessage.success("导出数据:" + name);
};
// 选择接口
// ===== 数据获取函数 =====
/**
 * 根据当前标签页选择对应的API接口
 * @returns {Promise} API调用Promise
 * @description 统一的接口选择函数,根据标签页类型调用对应的API
 */
const selectInterface = () => {
  if (tabName.value === "supplier") {
    return getSupply({
      current: pageNum.value,
      pageSize: pageSizes.value,
      searchAll: queryParams.searchAll,
    });
  } else if (tabName.value === "customer") {
    return getCustomerList({
      current: pageNum.value,
      pageSize: pageSizes.value,
      searchAll: queryParams.searchAll,
    });
  } else if (tabName.value === "coal") {
    return getCoalInfo({
      current: pageNum.value,
      pageSize: pageSizes.value,
      searchAll: queryParams.searchAll,
    });
  } else if (tabName.value === "coalQualityMaintenance") {
    return getCoalQuality({
      current: pageNum.value,
      pageSize: pageSizes.value,
      searchAll: queryParams.searchAll,
    });
  } else if (tabName.value === "coalMeiZhiZiDuanWeiHu") {
    return {
      code: 200,
          data: {
          records: [
            { fieldName: "字段1", fieldDescription: "描述1" },
            { fieldName: "字段2", fieldDescription: "描述2" },
            { fieldName: "字段3", fieldDescription: "描述3" }
          ],
            total: 10
        }
    };
    // return getCoalQuality({
    //   current: pageNum.value,
    //   pageSize: pageSizes.value,
    //   searchAll: queryParams.searchAll,
    // });
  }
}
const search = () => {
  pageNum.value = 1; // 重置页码
  getList();
  const apiParams = {
    current: pageNum.value,
    pageSize: pageSizes.value,
    searchAll: queryParams.searchAll,
  };
  const apiMap = {
    supplier: () => getSupply(apiParams),
    customer: () => getCustomerList(apiParams),
    coal: () => getCoalInfo(apiParams),
    coalQualityMaintenance: () => getCoalPlanList(apiParams),
    coalMeiZhiZiDuanWeiHu: () => coalField(apiParams)
  };
  const apiFunction = apiMap[tabName.value];
  return apiFunction ? apiFunction() : Promise.reject(new Error('未找到对应的API接口'));
};
// 获取列表数据
/**
 * 获取列表数据
 * @description 统一的数据获取函数,处理加载状态和错误处理
 */
const getList = async () => {
  loading.value = true;
  /* if (Object.keys(addressMap.value).length === 0) {
    await fetchAreaOptions();
  } */
  let { data, code } = await selectInterface()
  console.log("获取数据:", code, data);
  if (code !== 200) {
    ElMessage.error("获取数据失败:" + data.msg);
  try {
    loading.value = true;
    const { data, code } = await selectInterface();
    if (code !== 200) {
      ElMessage.error("获取数据失败:" + (data?.msg || '未知错误'));
      return;
    }
    tableData.value = data.records || [];
    total.value = data.total || 0;
  } catch (error) {
    console.error('获取列表数据失败:', error);
    ElMessage.error("获取数据失败,请稍后再试");
  } finally {
    loading.value = false;
    return;
  }
  tableData.value = data.records;
  total.value = data.total;
  loading.value = false;
};
// ===== 生命周期钩子 =====
/**
 * 组件挂载后的初始化操作
 */
onMounted(async () => {
  try {
    // 并行执行初始化操作
    await Promise.all([
      handleTabClick({ props: { name: "supplier" } }),
      fetchAreaOptions(),
      getUserList()
    ]);
  } catch (error) {
    console.error('组件初始化失败:', error);
    ElMessage.error("页面初始化失败,请刷新重试");
  }
});
</script>
<style scoped>