import {
  RESULT_CODE_ERROR,
  RESULT_CODE_SUCCESS,
  RESULT_MSG_ERROR,
} from '@/constants/result-constants';
import { request } from '@/plugins/http-fetch';
import { parseObjLineToHump } from '@/utils/parse-utils';

/**
 * 查询用户会话列表
 * @param query 查询参数
 * @returns object
 */
export async function listSession(query: Record<string, any>) {
  let totalSQL = 'select count(*) as total from session where 1=1 ';
  let rowsSQL = 'select * from session where 1=1 ';

  // 查询
  let querySQL = '';
  if (query.accountId) {
    querySQL += ` and account_id like '%${query.accountId}%' `;
  }
  if (query.ip) {
    querySQL += ` and host like '%${query.ip}%' `;
  }

  // 分页
  const pageNum = (query.pageNum - 1) * query.pageSize;
  const limtSql = ` limit ${pageNum},${query.pageSize} `;

  // 排序
  let sortSql = ' order by login_time ';
  if (query.sortOrder === 'desc') {
    sortSql += ' desc ';
  } else {
    sortSql += ' asc ';
  }

  // 发起请求
  const result = await request({
    url: `/api/rest/databaseManagement/v1/omc_db/session`,
    method: 'get',
    params: {
      totalSQL: totalSQL + querySQL,
      rowsSQL: rowsSQL + querySQL + sortSql + limtSql,
    },
  });

  // 解析数据
  if (result.code === RESULT_CODE_SUCCESS) {
    const data: DataList = {
      total: 0,
      rows: [],
      code: result.code,
      msg: result.msg,
    };
    result.data.data.forEach((item: any) => {
      const itemData = item['session'];
      if (Array.isArray(itemData)) {
        if (itemData.length === 1 && itemData[0]['total'] >= 0) {
          data.total = itemData[0]['total'];
        } else {
          data.rows = itemData.map(v => parseObjLineToHump(v));
        }
      }
    });
    return data;
  }
  return result;
}

/**
 * 强退用户会话
 * @param tokenId 授权标识
 * @returns object
 */
export async function logoutSession(id: string) {
  const result = await request({
    url: `/api/rest/databaseManagement/v1/omc_db/session?WHERE=id='${id}'`,
    method: 'delete',
  });
  // 解析数据
  if (result.code === RESULT_CODE_SUCCESS && result.data.data) {
    let rows = result.data.data.affectedRows;
    if (rows) {
      delete result.data;
      return result;
    } else {
      return { code: RESULT_CODE_ERROR, msg: RESULT_MSG_ERROR };
    }
  }
  return result;
}
