import * as sqlite from '@/utils/sqlite'
import { encrypt, decrypt } from '@/utils/crypto'

// 创建用户表
const createUserTableSql = `
  CREATE TABLE IF NOT EXISTS user (
    id         INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    name       TEXT,
    pwd        TEXT
  );
`

// 创建巡检计划表
const createInspectPlanTableSql = `
  CREATE TABLE IF NOT EXISTS inspectPlan (
    id         INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    planTitle  TEXT,
    planCode   TEXT,
    planCycle  TEXT,
    planUnit   TEXT,
    deviceIds  TEXT,
    createTime INTEGER
  );
`

const createInspectFormTableSql = `
  CREATE TABLE IF NOT EXISTS inspectPlan (
    id          INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    description TEXT,
    deviceId    INTEGER,
    indexId     INTEGER,
    ifNormal    INTEGER,
    picUrl      TEXT
  );
`

// 创建运行记录模板表
const createRecordTableSql = `
  CREATE TABLE IF NOT EXISTS recordTemplate (
      id                 INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
      name               TEXT,
      code               TEXT,
      deviceCategoryName TEXT,
      deviceCategoryId   INTEGER,
      createTime         INTEGER
  );
`

const createRecordAttrTableSql = `
  CREATE TABLE IF NOT EXISTS recordAttr (
      id               INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
      createTime       INTEGER,
      defaultValue     TEXT,
      deviceCategoryId INTEGER,
      name             TEXT,
      type             TEXT,
      requiredFlag     INTEGER,
      isSum            INTEGER,
      isCollection     INTEGER,
      modelAttr        TEXT,
      unitName         TEXT,
      unit             TEXT
  );
`

/**
 * 初始化数据库
 */
export const initAppDatabase = async () => {
  await sqlite.initDB('app')
  await Promise.all([
    sqlite.createTable(createUserTableSql, 'app'),
    sqlite.createTable(createInspectPlanTableSql, 'app'),
    sqlite.createTable(createInspectFormTableSql, 'app'),
    sqlite.createTable(createRecordTableSql, 'app'),
    sqlite.createTable(createRecordAttrTableSql, 'app'),
  ])
}

export const saveUser = async (user) => {
  // #ifdef APP
  await sqlite.deleteData('user', '1=1')
  await sqlite.insertData('user', [{ name: user.name, pwd: encrypt(user.pwd) }], 'app')
  // #endif
}