import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter_wallet/tools/YSTools.dart';
import 'package:provider/provider.dart';
import 'package:sqflite/sqflite.dart';

import 'YSNetWork.dart';

String sqName = 'walletDb';

class YSSqflite{
  Database? db;
  String? tabName = YSData().exName.replaceAll('-', '').replaceAll(' ', '');
  YSSqflite init({String? name}) {
    final file = YSSqflite();
    open(name);
    return file;
  }

  //判断表是否存在
  isTableExits(String tableName) async {
    db ??= await openDatabase('$sqName.db');
    var sql ="SELECT * FROM sqlite_master WHERE TYPE = 'table' AND NAME = '$tableName'";
    var res = await db!.rawQuery(sql);
    var returnRes = res.isNotEmpty;
    return returnRes;
  }

  open(String? name) async {
    if (await isTableExits(name??tabName!)==false) {
      execute(name);
    }
  }
  ///创建表
  execute(String? name) async{
    db ??= await openDatabase('$sqName.db');
    await db!.execute(
      'CREATE TABLE ${name??tabName} (id INTEGER PRIMARY KEY, name TEXT, password TEXT, word TEXT, private TEXT, public TEXT,chooseType INTEGER,sort INTEGER)'
    );
  }
  ///插入数据
  Future<int> rawInsert(YSWalletDbData data,{String? name}) async{
    db ??= await openDatabase('$sqName.db');
    List list = await rawQuery();
    bool isHas = list.any((element) => element['public']==data.public);
    if(isHas){
      ysFlutterToast('该钱包已存在');
      return 0;
    }else{
      int id = await db!.rawInsert(
          'INSERT INTO ${name??tabName}(name, password, word, private, public, chooseType, sort) VALUES("${data.name}","${data.password}","${data.word}",'
              '"${data.private}","${data.public}","${data.chooseType}","${list.length}")'
      );
      return id;
    }

  }
  ///查询数据
  Future<List> rawQuery({String? name}) async{
    try{
      db ??= await openDatabase('$sqName.db');
      List<Map> list = await db!.rawQuery('SELECT * FROM ${name??tabName}');
      List array = jsonDecode(jsonEncode(list));
      array.sort((a, b) => a['sort'].compareTo(b['sort']));
      return array;
    }catch(e){
      return [];
    }
  }
  ///更新数据
  Future<int> rawUpdate(YSWalletDbData data,int sort,String id,{String? name}) async{
    db ??= await openDatabase('$sqName.db');
    int count = await db!.rawUpdate(
        'UPDATE ${name??tabName} SET name = ?, password = ? , word = ?, private = ?, public = ? ,chooseType = ? ,sort = ? WHERE id = $id',
        [data.name, data.password, data.word,data.private,data.public,data.chooseType,sort]
    );
    return count;
  }
  ///删除数据
  Future<int> rawDelete(String id) async{
    db ??= await openDatabase('$sqName.db');
    int count = await db!.rawDelete('DELETE FROM $tabName WHERE id = ?', [id]);
    return count;
  }


  Future<int> delete() async{
    db ??= await openDatabase('$sqName.db');
    final status = await db?.delete(tabName!)??0;
    return status;
  }


  static notifier(BuildContext context,List array) {
    YSData().isLoad = true;
    Provider.of<YSWalletNotifier>(context, listen: false) .setValue(array);
  }
}


class YSSqflite2{
  Database? db;
  YSSqflite2 init() {
    final file = YSSqflite2();
    open();
    YSData().tokenTable = '${YSData().typeId}${YSData().wallet['id']}'.replaceAll('-', '').replaceAll(' ', '');
    return file;
  }

  //判断表是否存在
  isTableExits(String tableName) async {
    db ??= await openDatabase('$sqName.db');
    var sql ="SELECT * FROM sqlite_master WHERE TYPE = 'table' AND NAME = '${YSData().tokenTable}'";
    var res = await db!.rawQuery(sql);
    var returnRes = res.isNotEmpty;
    return returnRes;
  }

  open() async {
    if (await isTableExits(YSData().tokenTable)==false) {
      execute();
    }
  }
  ///创建表
  execute() async{
    db ??= await openDatabase('$sqName.db');
    await db!.execute(
        'CREATE TABLE ${YSData().tokenTable} (id INTEGER PRIMARY KEY, hid TEXT, name TEXT, gas TEXT, decimal TEXT, rice_usd TEXT, percent_change_24h TEXT, '
            'address TEXT,total_supply TEXT,icon_url TEXT,symbol TEXT)'
    );
  }
  //
  ///插入数据
  Future<int> rawInsert({
    required String hid,
    required String name,
    required String gas,
    required String decimal,
    required String rice_usd,
    required String percent_change_24h,
    required String address,
    required String total_supply,
    required String icon_url,
    required String symbol
  }) async{
    db ??= await openDatabase('$sqName.db');
    int id = await db!.rawInsert(
        'INSERT INTO ${YSData().tokenTable} (hid,name,gas,decimal,rice_usd,percent_change_24h,address,total_supply,icon_url,symbol) '
            'VALUES("$hid","$name","$gas","$decimal","$rice_usd","$percent_change_24h","$address","$total_supply","$icon_url","$symbol")'
    );
    return id;
  }
  ///查询数据
  Future<List> rawQuery() async{
    try{
      db ??= await openDatabase('$sqName.db');
      List<Map> list = await db!.rawQuery('SELECT * FROM ${YSData().tokenTable}');
      List array = jsonDecode(jsonEncode(list));
      YSData().tokenArray = array;
      return array;
    }catch(e){
      LogUtil.d(e);
      return [];
    }
  }
  ///更新数据
  Future<int> rawUpdate(String value,String id) async{
    db ??= await openDatabase('$sqName.db');
    int count = await db!.rawUpdate(
        'UPDATE ${YSData().tokenTable} SET hid = ?,name = ?,gas = ?,decimal = ?,rice_usd = ?,percent_change_24h = ?,total_supply = ? ,icon_url = ? ,symbol = ? WHERE id = $id',
        [value]
    );
    return count;
  }
  ///删除数据
  Future<int> rawDelete(String hid) async{
    db ??= await openDatabase('$sqName.db');
    int count = await db!.rawDelete('DELETE FROM ${YSData().tokenTable} WHERE hid = ?', [hid]);
    return count;
  }


  Future<int> delete() async{
    db ??= await openDatabase('$sqName.db');
    final status = await db?.delete(YSData().tokenTable)??0;
    return status;
  }

  static notifier(BuildContext context,List array) {
    Provider.of<YSTokenNotifier>(context, listen: false) .setValue(array);
  }
}

//{
// hid: 853860756,
// blockchain_id: 1,
// blockchain: null,
// name: HarryPotterObamaSonic10Inu,
// symbol: BITCOIN,
// bl_symbol: BITCOIN,
// gas: 60000,
// decimal: 8,
// precision: 0,
// balance: , p
// rice_usd: 0.0964896898818645,
// percent_change_24h: 106.40984418,
// asset: 0,
// added: 0,
// address: 0x72e4f9f808c49a2a61de9c5896298920dc4eeea9,
// owner_address: ,
// website: ,
// description:
// HarryPotterObamaSonic10Inu,
// update_contract: 0,
// total_supply: 1000000000,
// holder_count: 0,
// published: 0,
// ti_link: ,
// token_status: 0,
// validated: 0,
// icon_url: https://hk.tpstatic.net/token/tokenpocket-1689745640961.jpeg,
// auto_add: 0,
// dapp_code: ,
// token_protocol: 0,
// metadata_type: 0,
// create_time: 2023-05-10T14:33:16+08:00,
// Weight: 1
// }

class YSWalletDbData {
  final String name;
  final String password;
  final String word;
  final String private;
  final String public;
  final int chooseType;

  YSWalletDbData(this.name, this.password, this.word, this.private, this.public, this.chooseType);
}

class YSWalletNotifier with ChangeNotifier {
  List walletArray = [];

  List get value => walletArray;
  void setValue(value)
  {
    walletArray = value;
    LogUtil.d('walletArray====$walletArray');
    notifyListeners();
  }
}

class YSTokenNotifier with ChangeNotifier {
  List tokenArray = [];

  List get value => tokenArray;
  void setValue(value)
  {
    tokenArray = value;
    LogUtil.d('tokenArray====$tokenArray');
    notifyListeners();
  }
}


class YSSqflite3{
  Database? db;
  String? tabName = 'netTable';
  YSSqflite3 init() {
    final file = YSSqflite3();
    open();
    return file;
  }

  //判断表是否存在
  isTableExits() async {
    db ??= await openDatabase('$sqName.db');
    var sql ="SELECT * FROM sqlite_master WHERE TYPE = 'table' AND NAME = '$tabName'";
    var res = await db!.rawQuery(sql);
    var returnRes = res.isNotEmpty;
    return returnRes;
  }

  open() async {
    if (await isTableExits()==false) {
      execute();
    }
  }
  ///创建表
  execute() async{
    db ??= await openDatabase('$sqName.db');
    await db!.execute(
        'CREATE TABLE $tabName (id INTEGER PRIMARY KEY, key TEXT, value TEXT)'
    );
  }
  ///插入数据
    Future<int> rawInsert(String key,Object data) async{
    db ??= await openDatabase('$sqName.db');
    String dataStr = jsonEncode(data);
    dataStr = dataStr.replaceAll('"', 'ys');
    rawDelete(key);
    int id = await db!.rawInsert(
        'INSERT INTO $tabName(key,value) VALUES("${key.replaceAll('/', '')}","$dataStr")'
    );
    return id;
  }
  ///查询数据
  Future<Object> rawQuery(String key) async{
    try{
      db ??= await openDatabase('$sqName.db');
      List<Map> list = await db!.rawQuery('SELECT * FROM $tabName');
      List array = jsonDecode(jsonEncode(list));
      List valueList = array.where((element) => element['key']==key.replaceAll('/', '')).toList();
      if(valueList.isNotEmpty){
        Map value = valueList.last;
        String data = value['value'];
        data = data.replaceAll('ys', '"');
        return jsonDecode(data);
      }
      return {};
    }catch(e){
      return {};
    }
  }
  ///更新数据
  Future<int> rawUpdate(String key,Object data) async{
    db ??= await openDatabase('$sqName.db');
    String dataStr = jsonEncode(data);
    dataStr = dataStr.replaceAll('"', 'ys');
    int count = await db!.rawUpdate(
        'UPDATE $tabName SET value = ? WHERE key = ${key.replaceAll('/', '')}',
        [dataStr]
    );
    return count;
  }
  ///删除数据
  Future<int> rawDelete(String key) async{
    db ??= await openDatabase('$sqName.db');
    int count = await db!.rawDelete('DELETE FROM $tabName WHERE key = ?', [key]);
    return count;
  }


  Future<int> delete() async{
    db ??= await openDatabase('$sqName.db');
    final status = await db?.delete(tabName!)??0;
    return status;
  }
}


class YSAlwayAddressTable{
  Database? db;
  String? tabName = 'YSAlwayAddressTable';
  YSAlwayAddressTable init() {
    final file = YSAlwayAddressTable();
    open();
    return file;
  }

  //判断表是否存在
  isTableExits() async {
    db ??= await openDatabase('$sqName.db');
    var sql ="SELECT * FROM sqlite_master WHERE TYPE = 'table' AND NAME = '$tabName'";
    var res = await db!.rawQuery(sql);
    var returnRes = res.isNotEmpty;
    return returnRes;
  }

  open() async {
    if (await isTableExits()==false) {
      execute();
    }
  }
  ///创建表
  execute() async{
    db ??= await openDatabase('$sqName.db');
    await db!.execute(
        'CREATE TABLE $tabName (id INTEGER PRIMARY KEY, address TEXT, name TEXT, remark TEXT, icon TEXT, netId TEXT)'
    );
  }
  ///插入数据
  Future<int> rawInsert(String address,String name,String remark,String icon,String netId) async{
    db ??= await openDatabase('$sqName.db');
    int id = await db!.rawInsert(
        'INSERT INTO $tabName(address,name,remark,icon,netId) VALUES("$address","$name","$remark","$icon","$netId")'
    );
    return id;
  }
  ///查询数据
  Future<List> rawQuery() async{
    try{
      db ??= await openDatabase('$sqName.db');
      List<Map> list = await db!.rawQuery('SELECT * FROM $tabName');
      List array = jsonDecode(jsonEncode(list));
      return array;
    }catch(e){
      LogUtil.d(e);
      return [];
    }
  }
  ///更新数据
  Future<int> rawUpdate(String id,String address,String name,String remark,String icon,String netId) async{
    db ??= await openDatabase('$sqName.db');
    int count = await db!.rawUpdate(
        'UPDATE ${YSData().tokenTable} SET address = ?,name = ?,remark = ? ,icon = ?,netId = ? WHERE id = $id',
        [address,name,remark,icon,netId]
    );
    return count;
  }
  ///删除数据
  Future<int> rawDelete(String id) async{
    db ??= await openDatabase('$sqName.db');
    int count = await db!.rawDelete('DELETE FROM $tabName WHERE id = ?', [id]);
    return count;
  }


  Future<int> delete() async{
    db ??= await openDatabase('$sqName.db');
    final status = await db?.delete(tabName!)??0;
    return status;
  }
}

class YSTansTable{
  Database? db;
  String? tabName = '${YSData().contName.replaceAll(' ', '').replaceAll('-', '')}Tans';
  YSTansTable init() {
    final file = YSTansTable();
    open();
    return file;
  }

  //判断表是否存在
  isTableExits() async {
    db ??= await openDatabase('$sqName.db');
    var sql ="SELECT * FROM sqlite_master WHERE TYPE = 'table' AND NAME = '$tabName'";
    var res = await db!.rawQuery(sql);
    var returnRes = res.isNotEmpty;
    return returnRes;
  }

  open() async {
    if (await isTableExits()==false) {
      execute();
    }
  }
  ///创建表
  execute() async{
    db ??= await openDatabase('$sqName.db');
    await db!.execute(
        'CREATE TABLE $tabName (id INTEGER PRIMARY KEY, from_addr TEXT, to_addr TEXT, hash TEXT, status TEXT, type TEXT,nonce TEXT,amount TEXT)'
    );
  }
  ///插入数据
  Future<int> rawInsert({required String from,required String to,required String hash,required String status,required String type,required String nonce,required String amount}) async{
    db ??= await openDatabase('$sqName.db');
    int id = await db!.rawInsert(
        'INSERT INTO $tabName(from_addr,to_addr,hash,status,type,nonce,amount) VALUES("$from","$to","$hash","$status","$type","$nonce","$amount")'
    );
    return id;
  }
  ///查询数据
  Future<List> rawQuery() async{
    try{
      db ??= await openDatabase('$sqName.db');
      List<Map> list = await db!.rawQuery('SELECT * FROM $tabName');
      List array = jsonDecode(jsonEncode(list));
      return array;
    }catch(e){
      LogUtil.d(e);
      return [];
    }
  }
  ///更新数据
  Future<int> rawUpdate({required String id,required String from,required String to,required String hash,required String status,required String type,required String nonce,required String amount}) async{
    db ??= await openDatabase('$sqName.db');
    int count = await db!.rawUpdate(
        'UPDATE ${YSData().tokenTable} SET from_addr = ?,to_addr = ?,hash = ? ,status = ?,type = ? ,nonce = ? ,amount = ? WHERE id = $id',
        [from,to,hash,status,type,nonce,amount]
    );
    return count;
  }
  ///删除数据
  Future<int> rawDelete(String id) async{
    db ??= await openDatabase('$sqName.db');
    int count = await db!.rawDelete('DELETE FROM $tabName WHERE id = ?', [id]);
    return count;
  }


  Future<int> delete() async{
    db ??= await openDatabase('$sqName.db');
    final status = await db?.delete(tabName!)??0;
    return status;
  }
}

class YSTronTable{
  Database? db;
  String? tabName = 'tronExchange';
  YSTronTable init() {
    final file = YSTronTable();
    open();
    return file;
  }

  //判断表是否存在
  isTableExits() async {
    db ??= await openDatabase('$sqName.db');
    var sql ="SELECT * FROM sqlite_master WHERE TYPE = 'table' AND NAME = '$tabName'";
    var res = await db!.rawQuery(sql);
    var returnRes = res.isNotEmpty;
    return returnRes;
  }

  open() async {
    if (await isTableExits()==false) {
      execute();
    }
  }
  ///创建表
  execute() async{
    db ??= await openDatabase('$sqName.db');
    await db!.execute(
        'CREATE TABLE $tabName (id INTEGER PRIMARY KEY, from_addr TEXT, to_addr TEXT, from_token_addr TEXT, to_token_addr TEXT,amount TEXT, hash TEXT)'
    );
  }
  ///插入数据
  Future<int> rawInsert({required String from_addr,required String to_addr,required String from_token_addr,required String to_token_addr,required String amount,required String hash}) async{
    db ??= await openDatabase('$sqName.db');
    int id = await db!.rawInsert(
        'INSERT INTO $tabName(from_addr,to_addr,from_token_addr,to_token_addr,amount,hash) VALUES("$from_addr","$to_addr","$from_token_addr","$to_token_addr","$amount","$hash")'
    );
    return id;
  }
  ///查询数据
  Future<List> rawQuery() async{
    try{
      db ??= await openDatabase('$sqName.db');
      List<Map> list = await db!.rawQuery('SELECT * FROM $tabName');
      List array = jsonDecode(jsonEncode(list));
      return array;
    }catch(e){
      LogUtil.d(e);
      return [];
    }
  }
  ///更新数据
  Future<int> rawUpdate({required String id,required String from,required String to,required String hash,required String status,required String type,required String nonce,required String amount}) async{
    db ??= await openDatabase('$sqName.db');
    int count = await db!.rawUpdate(
        'UPDATE ${YSData().tokenTable} SET from_addr = ?,to_addr = ?,from_token_addr = ? ,to_token_addr = ?,amount = ? ,hash = ? WHERE id = $id',
        [from,to,hash,status,type,nonce,amount]
    );
    return count;
  }
  ///删除数据
  Future<int> rawDelete(String id) async{
    db ??= await openDatabase('$sqName.db');
    int count = await db!.rawDelete('DELETE FROM $tabName WHERE id = ?', [id]);
    return count;
  }


  Future<int> delete() async{
    db ??= await openDatabase('$sqName.db');
    final status = await db?.delete(tabName!)??0;
    return status;
  }
}