// 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<string, any>;
}

// 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[];
    };
  };
}
export function CreateData(type: string, param?: ParameterTuple[]): WebApiRequest {
  let req_param: Record<string, any> = {};
  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
  };
}

// 执行数据库操作
export async function ExecDatabase(request: WebApiRequest): Promise<any> {
  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<WebApiResponse>(
      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}`);
    }
  }
}

// 新的数据库执行函数 - 用于直接执行SQL查询
/* export async function ExecDatabase1(sqlQuery: string): Promise<any> {
  try {
    const request: WebApiRequest = {
      req_code: `REQ_${Date.now()}`,
      req_from: 'scada_web_client',
      req_cmd: 'ExecuteQuery',
      req_sql: sqlQuery,
      req_param: {}
    };

    // console.log('发送WebAPI请求(ExecDatabase1):', JSON.stringify(request, null, 2));

    const response = await axios.post<WebApiResponse>(
      'http://192.168.1.182:8080/api/database/command',
      request,
      {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 3000,
      }
    );

    // console.log('WebAPI响应(ExecDatabase1):', response.data);

    if (response.data.success && response.data.res_data?.success) {
      // 正确的数据提取路径
      const innerResData = response.data.res_data.res_data;

      if (innerResData && innerResData.data) {
        const data = innerResData.data;
        const rows = data.rows || data;
        const rowCount = data.rowCount || (Array.isArray(rows) ? rows.length : 0);

        return {
          data: rows,
          total: rowCount,
          success: true
        };
      } else {
        throw new Error('响应数据格式不正确：缺少内层data字段');
      }
    } else {
      const errorMsg = response.data.msg ||
        response.data.res_data?.errorMessage ||
        '数据库操作失败';
      throw new Error(errorMsg);
    }
  } catch (error: any) {
    console.error('数据库请求失败(ExecDatabase1):', 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;
  }
};
