import relationalStore from '@ohos.data.relationalStore';
import CommonConstants from '../common/constants/CommonConstants';
import ElectricSolderingIronPreset from '../viewmodel/device/ElectricSolderingIronPreset';

/**
 * 电烙铁预设数据库model
 */
class ElectricSolderingIronPresetModel {

  private rdbStore: relationalStore.RdbStore |undefined = undefined
  private tableName: string = 'ElectricSolderingIronPreset'

  /**
   * 初始化表
   */
  async initTaskDB(context:Context){
    // 1.rdb配置
    const config = {
      name: CommonConstants.RDB_NAME,
      securityLevel: relationalStore.SecurityLevel.S1
    }as relationalStore.StoreConfig
    try {
      // 获取数据库存储对象
      this.rdbStore = await relationalStore.getRdbStore(context, config);
    } catch (err) {
      console.info('hhtest', `getRdbStore err ${JSON.stringify(err)}`);
    }
    // 2.初始化SQL语句
    const sql = `CREATE TABLE IF NOT EXISTS ElectricSolderingIronPreset (
                  ID INTEGER PRIMARY KEY AUTOINCREMENT,
                  SET_NAME VARCHAR NOT NULL,
                  SET_VALUE INTEGER NOT NULL,
                  UNIT_STRING VARCHAR NOT NULL
                 )`
    // 3.获取rdb
    relationalStore.getRdbStore(context, config, (err, rdbStore) => {
      if(err){
        console.log('hhtest', '获取rdbStore失败！')
        return
      }
      // 执行Sql
      rdbStore.executeSql(sql).then(()=>{
        console.log('hhtest', '创建电烙铁预设表成功！')
      }).catch((err: object)=>{
        console.log('hhtest', '创建失败')
      })
      // 保存rdbStore
      this.rdbStore = rdbStore
    })
  }

  /**
   * 添加电烙铁预设
   * @param preset 预设信息
   * @returns 预设id
   */
  async addPreset(preset: ElectricSolderingIronPreset): Promise<number | undefined> {
    return this.rdbStore?.insert(this.tableName, {SET_NAME: preset.setName, SET_VALUE: preset.setValue, UNIT_STRING: preset.unitString} as relationalStore.ValuesBucket)
  }

  /**
   * 查询电烙铁预设列表
   */
  async getPresetList(): Promise<ElectricSolderingIronPreset[]> {
    // 1.构建查询条件
    let predicates = new relationalStore.RdbPredicates(this.tableName)
    // 2.查询
    let result: relationalStore.ResultSet | undefined = await this.rdbStore?.query(predicates, ['ID', 'SET_NAME', 'SET_VALUE', 'UNIT_STRING'])
    // 3.解析查询结果
    // 3.1.定义一个数组，组装最终的查询结果
    let presets: ElectricSolderingIronPreset[] = []
    // 3.2.遍历封装
    while(result && !result?.isAtLastRow){
      // 3.3.指针移动到下一行
      result.goToNextRow()
      // 3.4.获取数据
      let id = result.getLong(result.getColumnIndex('ID'))
      let setName = result.getString(result.getColumnIndex('SET_NAME'))
      let setValue = result.getLong(result.getColumnIndex('SET_VALUE'))
      let unitString = result.getString(result.getColumnIndex('UNIT_STRING'))
      // 3.5.封装到数组
      presets.push({id, setName, setValue, unitString})
    }
    return presets
  }

  /**
   * 根据id更新电烙铁预设
   * @param preset 预设
   */
  async updatePreset(preset: ElectricSolderingIronPreset): Promise<number | undefined> {

    // 1.要更新的数据
    let data: relationalStore.ValuesBucket = {SET_NAME: preset.setName as string, SET_VALUE: preset.setValue as number, UNIT_STRING: preset.unitString as string}
    // 2.更新的条件
    if (preset && preset.id!) {
      let predicates = new relationalStore.RdbPredicates(this.tableName)
      predicates.equalTo('ID', preset.id!)
      // 3.更新操作
      return this.rdbStore?.update(data, predicates)
    }
    return 0
  }

  /**
   * 根据id删除电烙铁预设
   * @param id 预设id
   */
  async deletePresetById(id: number): Promise<number | undefined> {
    // 1.删除的条件
    let predicates = new relationalStore.RdbPredicates(this.tableName)
    predicates.equalTo('ID', id)
    // 2.删除操作
    return this.rdbStore?.delete(predicates)
  }
}

let electricSolderingIronPresetModel = new ElectricSolderingIronPresetModel();

export default electricSolderingIronPresetModel as ElectricSolderingIronPresetModel;
