import axios from "axios";
//获取设备列表
export async function getDevices(){
  const body: any = {
    case: '',
    name: '',
    productId: '',
  };
  const ret: { records: any[]; total: number; type:number } = await axios.post(
    '/api/iot/devices',
    // '/api/iot/device/list'
    {
      pageIndex: 1,
      pageSize: 1000
    }
  );
  return ret;
}

export async function getMqttUrl () {
  const ret:any = await axios.get('/api/iot/mqtt/url');
  return ret;
}

//获取设备属性列表
export async function getDeviceProperties(deviceId:string){
  // const ret:any = await axios.get(`/api/iot/device/properties?id=${deviceId}`);
  const ret:any = await axios.post(`/api/iot/device/properties/${deviceId}`);
  return ret;
}

export async function subscribeProperties(devices:{deviceId:string; token:string;properties:string[]}[]){
  const ret:any = await axios.post(`/api/iot/subscribe/properties`,{
    devices
  });
  return ret;
}

export async function unsubscribeProperties(token:string){
  const ret:any = await axios.post(`/api/iot/unsubscribe/properties`,{
    token
  });
  return ret;
}

//获取sql数据源列表
export async function getSqlSourceList(){
  const ret:any = await axios.post(
    '/api/iot/data/sql/sources',
    {
      params: {
        current: 1,
        pageSize: 100,
      },
    }
  );
  return ret;
}

//执行查数据库操作 eg:SELECT id, fullpath FROM "directory" ;
export type SqlType = 'list' | 'get' | 'exec' | 'add' | 'update' | 'delete';
export async function doSqlCode(sql:{method?:SqlType, dbid?:string,sql?:string,pageSize?:number,current?:number}) {
  let _sql = sql.sql 
  if(sql.method==='list'){
    _sql+= ` LIMIT ${sql.pageSize||20}`+(sql.current>1?(' OFFSET '+(sql.current-1)*sql.pageSize):'');
  }
  console.log("doSqlGet",_sql);

  const ret = await axios.post(
    `/api/iot/data/sql/${sql.method}`,{
      dbid:sql.dbid,
      sql:_sql,
    }
  );
  return ret;
}

//数据库操作
//增 INSERT INTO tbl_name SET col_name1=value1,col_name2=value2,......;
//删 DELETE FROM users WHERE name = 'John';
//改 UPDATE tbl_name SET col_name1=value1,col_name2=value2,...... WHERE some_column=some_value;
