// webApiCall.ts import axios from 'axios'; import type { App } from 'vue'; export type ParameterValue = string | number | boolean | Date; export type ParameterTuple = [string, ParameterValue]; // WebAPI 请求接口 export interface WebApiRequest { req_code: string; req_from: string; req_cmd: string; req_sql?: string; req_param?: Record; } // WebAPI 响应接口 export interface WebApiResponse { success: boolean; code: number; msg: string; req_code: string; req_from: string; req_cmd: string; res_data: { success: boolean; errorMessage: string; affectedRows: number; lastInsertId: number; executionTime: number; data: { tableName: string; rowCount: number; columnCount: number; columns: string[]; rows: any[]; }; }; } // 新的 Vue 2 风格的 CreateData 方法 // 与旧项目保持一致 // data 格式: [['参数名', '参数值', '类型', 'output']] // output: '0' 表示否,'1' 表示是 export function CreateData(type: string, name: string, data: any, pageSize?: any, pageList?: any): string { let param_Str = ''; if (type === '7') { // 处理 type 7 的数据 if (data && Array.isArray(data)) { // 修改数据 const modifiedData = data.map((v: any) => { const newV = { ...v }; if (pageSize && Array.isArray(pageSize)) { pageSize.forEach((h: any) => { const val = h.toString(); if (!newV[val]) { newV[val] = ''; } }); } return newV; }); // 将数组转换为JSON字符串 param_Str = JSON.stringify(modifiedData); } else { param_Str = JSON.stringify(data || {}); } } else { // 处理其他类型的数据(type 11, 12等) const param_array: any[] = []; if (data !== undefined && Array.isArray(data)) { for (let i = 0; i < data.length; i++) { // 支持两种格式: // 1. 旧方法格式:['参数名', '参数值', '类型', 'output'] // 2. 简化格式:['参数名', '参数值'] - 自动补充类型和output const paramName = data[i][0]; const paramValue = data[i][1]; // 判断是两元素还是四元素格式 let paramType: string; let isOutput: string | number | boolean; if (data[i].length >= 4) { // 四元素格式:['参数名', '参数值', '类型', 'output'] paramType = data[i][2] || 'string'; isOutput = data[i][3] !== undefined ? data[i][3] : '0'; } else { // 两元素格式:['参数名', '参数值'] - 自动补充 paramType = 'string'; // 默认类型为 string isOutput = '0'; // 默认不是输出参数 } // 处理 null 值:保持为 null,不要转换为空字符串 // 因为存储过程的 WHERE 条件使用 IS NULL 判断,空字符串不会匹配 const finalValue = paramValue === null || paramValue === undefined ? null : paramValue; param_array.push({ name: paramName, value: finalValue, type: paramType, output: isOutput === true || isOutput === 1 || isOutput === '1' ? '1' : '0' // 转换为字符串 '0' 或 '1' }); } param_Str = JSON.stringify(param_array); } else { param_Str = JSON.stringify(data || {}); } } // 构建对象,与旧方法格式一致 const obj: any = { type: type, name: name, param: param_Str, pageSize: pageSize, pageList: pageList, UserID: (window as any).userId || '', // 从全局获取 userId ModularID: window.location.pathname || '' // 使用当前路径 }; // 返回单个对象的 JSON 字符串(不是数组) return JSON.stringify(obj); } // 新的 Vue 2 风格的 ExecDatabase 方法 // 与旧项目保持一致,直接返回 response.data export async function ExecDatabase(num: string): Promise { try { const serverAddress = window.dt_Config?.serverAddress; const timeout = window.dt_Config?.timeout || 30000; // 旧方法使用 request,这里使用 axios.post // 注意:num 是 JSON 字符串,需要解析后发送,或者直接发送字符串 // 根据旧方法,应该是直接发送字符串 const response = await axios.post( serverAddress || '', num, // 直接使用传入的字符串数据(JSON字符串) { headers: { 'Content-Type': 'application/json', }, timeout: timeout, } ); // 直接返回 response.data,与旧方法保持一致 return response.data; } catch (error: unknown) { console.error('数据库请求失败:', error); const errorObj = error as { response?: any; request?: any; message?: string }; if (errorObj.response) { throw new Error(`服务器错误: ${errorObj.response.status} - ${errorObj.response.data?.msg || '未知错误'}`); } else if (errorObj.request) { throw new Error('网络连接失败,请检查服务器地址和网络连接'); } else { throw new Error(`请求配置错误: ${errorObj.message || '未知错误'}`); } } } /* // 原有的 CreateData 方法(保持注释状态) export function CreateData(type: string, param?: ParameterTuple[]): WebApiRequest { let req_param: Record = {}; if (type === '11') { if (param && param.length > 0) { // 定义参数映射关系 const paramMapping: { [key: string]: string } = { 'TableName': 'p_table_name',//表名 'PageNumber': 'p_page_number',//第几页 'PageSize': 'p_page_size',//每页记录数 'FieldsToSelect': 'p_fields_to_select',//选择的字段 'WhereConditions': 'p_where_conditions',//条件 'SortField': 'p_sort_field',//排序字段 'SortDirection': 'p_sort_direction',//排序方向 'GroupByFields': 'p_group_by_fields',//分组字段 // 'TotalRecords': 'p_total_records' //总记录数 }; // 根据参数名称映射到存储过程参数名 param.forEach(([paramName, value]) => { const mappedName = paramMapping[paramName] || paramName; req_param[mappedName] = value; }); } } else if (type === '7') { // 参数化查询 if (param && param.length > 0) { // 构建参数对象 param.forEach(([name, value], index) => { req_param[name] = value; }); } } return { req_code: `REQ_${Date.now()}`, req_from: 'scada_web_client', // req_cmd: 'ExecuteQuery', req_cmd: 'ExecuteStoredProcedure', // req_sql: req_sql, req_sql: 'sp_pagination', req_param: Object.keys(req_param).length > 0 ? req_param : undefined }; } // 原有的 ExecDatabase 方法(保持注释状态) export async function ExecDatabase(request: WebApiRequest): Promise { try { // console.log('发送WebAPI请求:', JSON.stringify(request, null, 2)); const serverAddress = window.dt_Config?.serverAddress const timeout = window.dt_Config?.timeout // console.log('serverAddress:', serverAddress); const response = await axios.post( serverAddress, request, { headers: { 'Content-Type': 'application/json', }, timeout: timeout, } ); const tableName = request.req_param?.p_table_name || '未知表名'; // console.log(`WebAPI响应 (表名: ${tableName}):`, response.data); if (response.data.success && response.data.res_data.success) { return { data: response.data.res_data.data.rows, total: response.data.res_data.data.rowCount, success: true }; } else { throw new Error(response.data.msg || response.data.res_data.errorMessage || '数据库操作失败'); } } catch (error: any) { console.error('数据库请求失败:', error); if (error.response) { throw new Error(`服务器错误: ${error.response.status} - ${error.response.data?.msg || '未知错误'}`); } else if (error.request) { throw new Error('网络连接失败,请检查服务器地址和网络连接'); } else { throw new Error(`请求配置错误: ${error.message}`); } } } */ // 在默认导出中添加全局方法 export default { install(app: App): void { // 添加新的全局方法 app.config.globalProperties.CreateData = CreateData; app.config.globalProperties.ExecDatabase = ExecDatabase; } };