import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import relationalStore from '@ohos.data.relationalStore';
import util from '@ohos.util';
import { Huanzhelast444Model } from '../models/Huanzhelast444Model'

const huanzhelastFile: string = 'huanzhelas.sqlite';

// 步骤1：将rawfile数据库文件复制到应用沙箱
async function copyDatabase(context: common.Context): Promise<void> {
  try {
    const resourceMgr = context.resourceManager;
    const rawFile = await resourceMgr.getRawFileContent(huanzhelastFile);

    // 将Uint8Array转为ArrayBuffer
    const arrayBuffer = rawFile.buffer;

    // 创建沙箱路径
    const dbPath = context.filesDir + '/' + huanzhelastFile;
    console.info(`[DB] context.filesDir: ${context.filesDir}`);
    console.info(`[DB] dbPath: ${dbPath}`);
    // 确保目录存在
    try {
      fs.accessSync(context.filesDir);
    } catch (e) {
      fs.mkdirSync(context.filesDir);
    }

    // 写入文件
    const file = fs.openSync(dbPath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
    fs.writeSync(file.fd, arrayBuffer);
    fs.closeSync(file);

    // 检查文件是否存在
    try {
      fs.accessSync(dbPath);
      console.info(`[DB] DB file exists after copy: ${dbPath}`);
    } catch (e) {
      console.error(`[DB] DB file does not exist after copy: ${dbPath}`);
    }
  } catch (error) {
    console.error(`Copy database failed: ${error}`);
  }
}

// 步骤2：数据库操作封装类
class HuanzhelasDbHelper {
  private rdbStore: relationalStore.RdbStore | null = null;

  // 初始化数据库连接
  async initDatabase(context: common.Context): Promise<void> {
    await copyDatabase(context);
    const storeConfig: relationalStore.StoreConfig = {
      name: huanzhelastFile,
      securityLevel: relationalStore.SecurityLevel.S1
    };

    try {
      this.rdbStore = await relationalStore.getRdbStore(context, storeConfig);
      console.info('Database connection established');
    } catch (error) {
      console.error(`Init database failed: ${error}`);
    }
  }

  async queryHuanzhelastData():Promise<Array<HuanzhelastEntity>> {
    if (!this.rdbStore) {
      console.error('Database not initialized');
      throw new Error('Database not initialized');
    }
    // const resultSet = await this.rdbStore.querySql('SELECT * FROM t_huanzhelast444', []);
    // if (resultSet.rowCount > 0) {
    //   resultSet.goToFirstRow();
    //   do {
    //     console.info('[DB] Table:', resultSet.getString(0));
    //   } while (resultSet.goToNextRow());
    // }
    // resultSet.close();
    // try {
    //   const predicates = new relationalStore.RdbPredicates('t_huanzhelast444');
    //   console.info('[DB] Querying table: t_huanzhelast444');
    //   const resultSet = await this.rdbStore.query(predicates);
    //
    //   if (resultSet.isClosed) {
    //     console.error('[DB] ResultSet is closed immediately after query!');
    //     return;
    //   }
    //   console.info('[DB] ResultSet columnNames:', resultSet.columnNames);
    //   console.info('[DB] Query finished, rowCount:', resultSet.rowCount);
    //
    //   if (resultSet.rowCount > 0) {
    //     resultSet.goToFirstRow();
    //     do {
    //       // // 打印每一行
    //       // let row: Required = {};
    //       // for (let i = 0; i < resultSet.columnNames.length; i++) {
    //       //   row[resultSet.columnNames[i]] = resultSet.getString(i);
    //       // }
    //       // console.info('[DB] Row:', JSON.stringify(row));
    //       console.info('[DB] Row:');
    //     } while (resultSet.goToNextRow());
    //   } else {
    //     console.warn('[DB] No data found, please check table name and data!');
    //   }
    //   resultSet.close();
    // } catch (e) {
    //   console.error('[DB] Query error:', e);
    //   throw new Error('Database query error');
    // }
    try {///data/app/el2/100/base/com.example.expert/haps/default/files/databases/huanzhelas.sqlite
      const predicates = new relationalStore.RdbPredicates('cn_shangyu_gdxzExpert_bean_City');
      const resultSet = await this.rdbStore.query(predicates);

      const dataList: Array<HuanzhelastEntity> = [];
      if (resultSet.rowCount > 0) {
        resultSet.goToFirstRow();
        do {
          dataList.push(this.parseResultSet(resultSet));
        } while (resultSet.goToNextRow());
      } else {
        console.error(`Query failed: ${predicates}`);
      }
      resultSet.close();
      return dataList;
    } catch (error) {
      console.error(`Query failed: ${error}`);
      throw new Error('Database query error');
    }
  }

  private parseResultSet(resultSet: relationalStore.ResultSet): HuanzhelastEntity {
    return {
      _id: resultSet.getDouble(resultSet.getColumnIndex('_id')),
      id: resultSet.getDouble(resultSet.getColumnIndex('id')),
      fullname: resultSet.getString(resultSet.getColumnIndex('fullname')),
      name: resultSet.getString(resultSet.getColumnIndex('name')),
      parent: resultSet.getDouble(resultSet.getColumnIndex('parent')),
      treePath: resultSet.getString(resultSet.getColumnIndex('treePath'))
    };
  }
}

// 实体类型定义
interface HuanzhelastEntity {
  _id: number;
  id: number;
  fullname: string;
  name: string;
  parent: number;
  treePath: string;
}

export const huanzheDb = new HuanzhelasDbHelper()
