import {createSQLiteContext} from '@/uni_modules/uni-sqlContext'
import {selectSqlOptions,executeSqlOptions, executeSqlOptionsResult,selectSqlOptionsResult,transactionResult, ICreateSQLiteContextError } from '@/uni_modules/uni-sqlContext/utssdk/interface.uts'



// 数据库名称
const dbName = 'QT800'

// 数据库地址,推荐以下划线为开头   _doc/xxx.db
// 如果路径不为_downloads/xxx.db,在手机中会找不到文件夹(强烈建议：不要修改路径)
const dbPath = '/www/static/db/qt_app_800'


// 普通函数
// 查询获取数据库里的数据 sql:'SELECT * FROM dbTable WHERE lname = 'lvalue''
// 查询 SELECT * FROM 、 dbTable 是表名、 WHERE 查找条件 lname,lvalue 是查询条件的列名和列值
// @param {Object} dbTable:表名
// @param {Object} lname:列名
// @param {Object} lvalue:列中的属性值
export function selectTableData (
  dbTable: string,
  lname?: string,
  lvalue?: string,
  cc?: string,
  dd?: string,
):Promise<UTSJSONObject>
{
  if (dbTable !== null) {
    // 第一个是表单名称，后两个参数是列表名，用来检索
	var sql = '';
    if (lname !== null && cc !== null) {
      // 两个检索条件
      sql = `SELECT * FROM ${dbTable} WHERE ${lname} = '${lvalue}' AND ${cc} = '${dd}'`
    }
    if (lname !== null && cc == null) {
      // 一个检索条件
       sql = `SELECT * FROM ${dbTable} WHERE ${lname} = '${lvalue}'`
      // console.log(sql);
    }
    if (lname == null) {
       sql = `SELECT * FROM ${dbTable}`
    }
	const sqlite = createSQLiteContext(dbName);
	
	return new Promise<UTSJSONObject>((resolve, reject) => {
	  const selectSqlOptions ={		
		  sql: sql,
		  success: (e: selectSqlOptionsResult) => {
		    console.log(e)
			
		  },
		  fail: (e: selectSqlOptionsResult) => {
		    console.error(e)
		  }		
	  } as selectSqlOptions
	
	  const info = sqlite.selectSql(selectSqlOptions) as selectSqlOptionsResult
	  
	  console.log(info)	
	  const ret = {
		  errMsg: info?.errMsg ?? '',
		  data: info?.data ?? ['']
	  } as UTSJSONObject
	  resolve(ret)
	});	
		
  } else {
    return new Promise<UTSJSONObject>((resolve, reject) => {
		const ret = {
			  errMsg: '错误查询',
			  data : ['表名不存在']
		} as UTSJSONObject
        resolve(ret);		
    })
  }
 } 
  // 箭头函数
  // 根据条件向表格里添加数据  有数据更新、无数据插入
  // (建表时需要设置主键) 例如 --- "roomid" varchar(50) PRIMARY KEY
  // @param {Object} dbTable:表名
  // @param {Object} data : 插入表中的值结构
  // @param {Object} condition : 插入表中对应的列的属性名称结构
  export function insertOrReplaceData(dbTable: string, data: string, condition?: string): Promise<UTSJSONObject> {
    // 判断有没有传参
    if (dbTable !== null && data !== null) {
      if (condition == null) {
        var sql = `INSERT OR REPLACE INTO ${dbTable} VALUES(${data})`
      } else {
        var sql = `INSERT OR REPLACE INTO ${dbTable} (${condition}) VALUES(${data})`
      }
	  const sqlite = createSQLiteContext(dbName);
      // console.log(sql);
      return new Promise((resolve, reject) => {		
		const executeSqlOptions ={
				  sql: sql,
				  success: (e: executeSqlOptionsResult) => {
				    console.log(e)
					
				  },
				  fail: (e: executeSqlOptionsResult) => {
				    console.error(e)
				  }		
		} as executeSqlOptions
		
		const info = sqlite.executeSql(executeSqlOptions) as executeSqlOptionsResult
		console.log(info)
		const ret = {
			errMsg: info?.errMsg ?? '',
			data: info?.data ?? ['']
		} as UTSJSONObject
		resolve(ret)
      })
    } else {
      return new Promise((resolve, reject) => {
        reject('错误添加')
      })
    }
  }
  
  // 普通函数
  // 向表格里添加数据 sql:'INSERT INTO dbTable VALUES('x','x','x')'   对应新增
  // 或者 sql:'INSERT INTO dbTable ('x','x','x') VALUES('x','x','x')'   具体新增
  // 插入 INSERT INTO  、 dbTable 是表名、根据表头列名插入列值
  // @param {Object} dbTable:表名
  // @param {Object} data : 插入表中的值结构
  // @param {Object} condition : 插入表中对应的列的属性名称结构
  export function insertTableData(dbTable: string, data: string, condition?: string) : Promise<UTSJSONObject>{
    // 判断有没有传参
    if (dbTable !== null && data !== null) {
      // 判断传的参是否有值
      var bol = JSON.stringify(data) == '{}'
      if (!bol) {
		var sql = ''  
        if (condition == null) {
          sql = `INSERT INTO ${dbTable} VALUES (${data})`
        } else {
          sql = `INSERT INTO ${dbTable} (${condition}) VALUES(${data})`
        }
        console.log(sql)
        const sqlite = createSQLiteContext(dbName);
        return new Promise((resolve, reject) => {
           const executeSqlOptions ={
           		  sql: sql,
           		  success: (e: executeSqlOptionsResult) => {
           		    console.log(e)
           			
           		  },
           		  fail: (e: executeSqlOptionsResult) => {
           		    console.error(e)
           		  }		
           } as executeSqlOptions
		   
		   const info = sqlite.executeSql(executeSqlOptions) as executeSqlOptionsResult
		   console.log(info)
		   const ret = {
		   	errMsg: info?.errMsg ?? '',
		   	data: info?.data ?? ['']
		   } as UTSJSONObject
		   sqlite.close();
		   resolve(ret)
        })
      } else {
        return new Promise((resolve, reject) => {
          reject('错误添加')
        })
      }
    } else {
      return new Promise((resolve, reject) => {
        reject('错误添加')
      })
    }
  }
  
  // 普通函数
  // 修改数据表里的数据 sql:"UPDATE dbTable SET 列名 = '列值',列名 = '列值' WHERE lname = 'lvalue'"
  // 修改 UPDATE 、 dbTable 是表名, data: 要修改的列名=修改后列值, lname,lvalue 是查询条件的列名和列值
  // @param {Object} dbTable:表名
  // @param {Object} data : 修改表中的值结构
  // @param {Object} lname:列名
  // @param {Object} lvalue:列中的属性值
  export function updateTableData(dbTable: string, data: string, lname?: string, lvalue?: string) : Promise<UTSJSONObject> {
    var sql = ''
	if (lname == null) {
      sql = `UPDATE ${dbTable} SET ${data}`
    } else {
      sql = `UPDATE ${dbTable} SET ${data} WHERE ${lname} = '${lvalue}'`
    }
	const sqlite = createSQLiteContext(dbName);
    // WHERE 前面是要修改的列名、列值，后面是条件的列名、列值
    return new Promise((resolve, reject) => {
      const executeSqlOptions ={
      		  sql: sql,
      		  success: (e: executeSqlOptionsResult) => {
      		    console.log(e)
      			
      		  },
      		  fail: (e: executeSqlOptionsResult) => {
      		    console.error(e)
      		  }		
      } as executeSqlOptions
	  
	  const info = sqlite.executeSql(executeSqlOptions) as executeSqlOptionsResult
	  console.log(info)
	  const ret = {
	  	errMsg: info?.errMsg ?? '',
	  	data: info?.data ?? ['']
	  } as UTSJSONObject
	  sqlite.close();
	  resolve(ret)
	  
    })
  }
  
  // 箭头函数
  // 获取指定数据条数  sql:"SELECT * FROM dbTable ORDER BY 'id' DESC LIMIT 15 OFFSET 'num'"
  // dbTable 表名, ORDER BY 代表排序默认正序, id 是排序的条件 DESC 代表倒序，从最后一条数据开始拿
  // LIMIT 15 OFFSET '${num}',这句的意思是跳过 num 条拿 15 条数据, num 为跳过多少条数据是动态值
  // 例 初始num设为0，就从最后的数据开始拿15条，下次不拿刚获取的数据，所以可以让num为15，这样就能一步一步的拿完所有的数据
  // @param {Object} dbTable:表名
  // @param {Object} id:数据id
  /**
   * @param {Object} num 例子如下：
   * select * from boot limit 10 offset 0;
   * select * from boot limit 10 offset 10;
   * select * from boot limit 10 offset 20;
   * select * from boot limit 10 offset 30;
   * 比如说每页数量为 10 条，然后我们分别获区第1、2、3、4页的数据
   *
   */
  export function pullSQL(dbTable: string, id: string, num: number) : Promise<UTSJSONObject> {
	var sql = `SELECT * FROM ${dbTable} ORDER BY '${id}' DESC LIMIT 15 OFFSET '${num}'` 
	const sqlite = createSQLiteContext(dbName); 
    return new Promise((resolve, reject) => {
      const selectSqlOptions ={
      		  sql: sql,
      		  success: (e: selectSqlOptionsResult) => {
      		    console.log(e)
      			
      		  },
      		  fail: (e: selectSqlOptionsResult) => {
      		    console.error(e)
      		  }		
      } as selectSqlOptions
      	
      const info = sqlite.selectSql(selectSqlOptions) as selectSqlOptionsResult
      
      console.log(info)	
      const ret = {
      		  errMsg: info?.errMsg ?? '',
      		  data: info?.data ?? ['']
      } as UTSJSONObject
      resolve(ret)
    })
  }
