import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_wallet/generated/l10n.dart';
import 'package:flutter_wallet/tools/YSBip.dart';
import 'package:flutter_wallet/tools/YSNetWork.dart';
import 'package:intl/intl.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:math' as math;
import 'package:provider/provider.dart';
import 'package:local_auth/local_auth.dart';
import 'package:local_auth_android/local_auth_android.dart';
import 'package:local_auth_ios/local_auth_ios.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:qrscan/qrscan.dart' as scanner;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:web3dart/credentials.dart';

import 'YSAlertView.dart';
import 'YSSqflite.dart';


enum FillInType{
  choose,
  input,
  none,
  file,
}

double ysHeight(BuildContext context) => MediaQuery.of(context).size.height;
double ysWidth(BuildContext context) => MediaQuery.of(context).size.width;
double ysTOP(BuildContext context) => MediaQuery.of(context).padding.top;
double ysBottom(BuildContext context) => MediaQuery.of(context).padding.bottom;
double ystabBarHeight = 70;
String accessToken = "sk.eyJ1IjoiYmxvY2tjYXJib24iLCJhIjoiY2xrcm81enRyMmx6dTNra2VhZnMwcmNneCJ9.inGPH4-QFL6UX1NsDHKeiA";


hsp(int number){
  return ScreenUtil().setHeight(number);
}
zsp(int number){
  return ScreenUtil().setSp(number);
}

///手机号验证
bool isChinaPhoneLegal(String str) {
  return RegExp(r"^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$").hasMatch(str);
}

///邮箱验证
bool isEmail(String str) {
  return RegExp(r"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$").hasMatch(str);
}
///验证URL
bool isUrl(String value) {
  return RegExp(r"^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+").hasMatch(value);
}
///验证数字
bool isNumber(String value) {
  return RegExp(r'^-?[0-9.]+$').hasMatch(value);
}


///验证车牌
bool isCarNumber(String value) {
  ////1、这条正则可以校验 普通汽车的车牌、新能源客（货）车车牌
  // const carNoReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$)|([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/; //普通车牌 | 新能源货车 | 新能源小客车 车牌校验规则
  // //2、普通车车牌校验
  // const carCardP = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/;
  //  //3、新能源车牌校验
  // const carCardD = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/;
  // //4、农用车辆及拖拉机车牌号验证：
  // const carCardD = /^(([\u4e00-\u9fa5][a-zA-Z]|[\u4e00-\u9fa5]{2}\d{2}|[\u4e00-\u9fa5]{2}[a-zA-Z])[-]?|([wW][Jj][\u4e00-\u9fa5]{1}[-]?)|([a-zA-Z]{2}))([A-Za-z0-9]{5}|[DdFf][A-HJ-NP-Za-hj-np-z0-9][0-9]{4}|[0-9]{5}[DdFf])$/
  return RegExp(r"^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$)|([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))").hasMatch(value);
}

///验证中文
bool isChinese(String value) {
  return RegExp(r"[\u4e00-\u9fa5]").hasMatch(value);
}

///验证身份证
bool isIdCard(String value) {
  return RegExp(r"\d{17}[\d|x]|\d{15}").hasMatch(value);
}

bool isPassword(String value) {
  return RegExp(r"(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{7,})\w+").hasMatch(value);
}

class LogUtil {
  static const _separator = "=";
  static const _split =
      "$_separator$_separator$_separator$_separator$_separator$_separator$_separator$_separator$_separator";
  static const _title = "Yl-Log";
  static const _isDebug = true;
  static const int _limitLength = 800;
  static const String _startLine = "$_split$_title$_split";
  static const String _endLine = "$_split$_separator$_separator$_separator$_split";



  //仅Debug模式可见
  static void d(dynamic obj) {
    if (_isDebug) {
      _log(obj.toString());
    }
  }

  static void v(dynamic obj) {
    _log(obj.toString());
  }

  static void _log(String msg) {
    if (kDebugMode) {
      print(_startLine);
    }
    _logEmpyLine();
    if(msg.length<_limitLength){
      if (kDebugMode) {
        print(msg);
      }
    }else{
      segmentationLog(msg);
    }
    _logEmpyLine();
    if (kDebugMode) {
      print(_endLine);
    }
  }

  static void segmentationLog(String msg) {
    var outStr = StringBuffer();
    for (var index = 0; index < msg.length; index++) {
      outStr.write(msg[index]);
      if (index % _limitLength == 0 && index!=0) {
        if (kDebugMode) {
          print(outStr);
        }
        outStr.clear();
        var lastIndex = index+1;
        if(msg.length-lastIndex<_limitLength){
          var remainderStr = msg.substring(lastIndex,msg.length);
          if (kDebugMode) {
            print(remainderStr);
          }
          break;
        }
      }
    }
  }

  static void _logEmpyLine(){
    if (kDebugMode) {
      print("");
    }
  }
}

class YSFileWriteRead{

  // 获取文件
  Future<File> getLocalFile() async {
    final directory = await getExternalStorageDirectory();
    File file = File('${directory!.path}/walletLog2.txt');
    bool isExists = await file.exists();
    if(!isExists){
      file.create();
    }
    return file;
  }

  // 写入内容
  void writeContent(String content) async {
    File file = await getLocalFile();
    String counterString = file.readAsStringSync()??'';
    file.writeAsString(counterString.isNotEmpty?'$counterString\n\n${DateTime.now()}========$content':'${DateTime.now()}========$content');
    Map dict = await YSNetWork.httpNetwork2(api: 'logs?log=$content', request: {});
    if(dict.isNotEmpty){}
  }
  Future<String> readContent() async {
    File file = await getLocalFile();
    LogUtil.d('writeContent=======${file.path}');
    String content = await file.readAsString();
    LogUtil.d(content);
    // file.delete();
    return content;
  }
}

ysShowBottomAlertView(BuildContext context,Widget widget,{bool isBarr = false,bool isCancel = true}) {
  showModalBottomSheet(
      context: context,
      isScrollControlled: isCancel,
      isDismissible: isCancel,
      backgroundColor: Colors.transparent,
      barrierColor: !isBarr?Colors.transparent:Colors.black54,
      builder: (context){
        return widget;
      }
  );
}

ysShowCenterAlertView(BuildContext context,Widget widget,{bool isTrans = false,bool isBarr = false}) {
  showGeneralDialog(
      context: context,
      barrierDismissible: isBarr,
      barrierLabel: '',
      barrierColor: isTrans==true?Colors.transparent:Colors.black54,
      pageBuilder: (context,animation,scAnimation){
        return widget;
      }
  );
}



class YSData {

  // String word = '';
  String name = '';
  String password = '';
  bool isManager = false;
  bool isLoad = false;

  List typeArray = [];
  String typeId = 'ys';
  String exName = '';
  String rpc = '';
  String tokenTable = '';
  List tokenArray = [];
  List allTokenArray = [];
  List priceArray = [];
  Map wallet = {};
  Map balanceMap = {};
  List coinArray = [];
  late BuildContext context;
  int chooseIndex = 0;

  String contAddress = '';
  String contName = '';
  String pancakeAddress = '0x10ED43C718714eb63d5aA57B78B54704E256024E';

  int dataRefresh = 0;

  // String get exName => exName;
  // set exName(String value) {
  //   exName = value;
  // }


  YSData._internal();
  //保存单例
  static final YSData _singleton = YSData._internal();
  //工厂构造函数
  factory YSData()=> _singleton;
}

class YSUserRecord {

  String them = 'dart';
  String language = 'zh';
  String price = '1';
  String unit = 'dollar';
  String lock = '1';
  String install = '';
  String priceType = '1';

  YSUserRecord._internal();
  //保存单例
  static final YSUserRecord _singleton = YSUserRecord._internal();
  //工厂构造函数
  factory YSUserRecord()=> _singleton;
}

class YSUnitNotifier with ChangeNotifier {
  String unit = 'dollar';

  String get value => unit;
  void setUnit(String value)
  {
    YSUserRecord().unit = value;
    YSSharedPreferences.setStringValue('unit', value);
    unit = value;
    notifyListeners();
  }
}

double unitNumber() {
  double number = 1;
  if(YSUserRecord().unit=='dollar'){
    number = 1;
  }else if(YSUserRecord().unit=='RMB'){
    number = 7.2706;
  }
  return number;
}

checkAddress() async{
  // LogUtil.d('checkAddress======${YSData().typeId}');
  // return;
  YSSqflite sqflite = YSSqflite().init();
  List array = await sqflite.rawQuery();
  // LogUtil.d('element=======$array');
  if(YSData().typeId!='TRON-HD')return;
  //TM7KhUSZVyeHVMXsopbkoWMuvMGRH6iF2U
  for (var element in array) {
    if('${element['public']}'.substring(0,1)!='T'){//'${element['public']}'.substring(0,1)!='T'  element['public']=='TM7KhUSZVyeHVMXsopbkoWMuvMGRH6iF2U'
      Map tronMap = YSBipManager.getTronCode2(element['private']);
      sqflite.rawUpdate(YSWalletDbData(element['name'], element['password'], element['word'],
          element['private'], '${tronMap['pubicKey']}', element['chooseType']), element['sort'], '${element['id']}');
    }
  }
  array = await sqflite.rawQuery();
  // ignore: use_build_context_synchronously
  YSSqflite.notifier(YSData().context, array);
  // LogUtil.d('element=======$array');
}

addToken(BuildContext context,{int kind = 0}) async{
  YSSqflite2 sqflite2 = YSSqflite2().init();
  Map type = {};
  for (var element in YSData().typeArray) {
    if(element['id']==YSData().typeId){
      type = element;
    }
  }
  // LogUtil.d('getMindToken=========${YSData().wallet}');
  // sqflite2.rawDelete(type['id']);
  List tokenArray = await sqflite2.rawQuery();
  // LogUtil.d('getMindToken=========${YSData().tokenTable}');
  bool isHave = tokenArray.any((element) => '${element['symbol']}'=='${type['id']}');
  // LogUtil.d('addToken======$isHave');
  if(isHave==false){
    sqflite2.rawInsert(
        hid: '${type['id']??''}',
        name: type['name']??'',
        gas: '',
        decimal: '18',
        rice_usd: '',
        percent_change_24h: '',
        address: YSData().wallet['public'],
        total_supply: '',
        icon_url: '${type['icon']??''}',
        symbol: '${type['id']??''}'
    );
  }
  tokenArray = await sqflite2.rawQuery();
  if(kind==0){
    YSData().dataRefresh++;
    // LogUtil.d('getMindToken=========$tokenArray');
    // ignore: use_build_context_synchronously
    YSSqflite2.notifier(context, tokenArray);
  }else{
    // ignore: use_build_context_synchronously
    getMindToken(context);
  }
}

getMindToken(BuildContext context) async{
  // YSSqflite2 sqflite2 = YSSqflite2().init();
  // List tokenArray = await sqflite2.rawQuery();
  // LogUtil.d('getMindToken=========$tokenArray');
  // YSData().dataRefresh++;
  // // ignore: use_build_context_synchronously
  // YSSqflite2.notifier(context, tokenArray);
  // return;
  // LogUtil.d('getMindToken=========$context');
  Map request = {'chain_id':YSData().typeId,'page':1,'count':10,'address':YSData().wallet['public']};
  Map dict = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.get, api: 'mytokens', parameter: request);
  if(dict.isNotEmpty){
    List array = dict['data']['list']??[];
    YSSqflite2 sqflite2 = YSSqflite2().init();
    List tokenArray = await sqflite2.rawQuery();
    LogUtil.d('tokenArray=========$tokenArray');
    LogUtil.d(YSData().allTokenArray);
    for (var element in array) {
      if('${element['contract_address']}'.isNotEmpty){
        bool isHas = tokenArray.any((elementSub) => elementSub['address']==element['contract_address']);
        if(!isHas){
          List array2 = YSData().allTokenArray.where((elementSub) => elementSub['address']==element['contract_address']).toList();
          LogUtil.d('tokenArray=========11$array2');
          if(array2.isNotEmpty){
            Map token = array2.first;
            sqflite2.rawInsert(
                hid: '${token['hid']}',
                name: token['name'],
                gas: '${token['gas']}',
                decimal: '${token['decimal']}',
                rice_usd: '${token['price_usd']}',
                percent_change_24h: '${token['percent_change_24h']}',
                address: token['address'],
                total_supply: '${token['total_supply']}',
                icon_url: token['icon_url'],
                symbol: token['symbol']
            );
          }else{
            // addToken(context);
          }
        }
      }
    }
    YSData().dataRefresh++;
    tokenArray = await sqflite2.rawQuery();
    // LogUtil.d('getMindToken=========$context');
    // ignore: use_build_context_synchronously
    YSSqflite2.notifier(YSData().context, tokenArray);
  }
}

///单例类
class YSMapUntil {

  // 工厂方法构造函数 - 通过UserModel()获取对象1
  factory YSMapUntil() => _getInstance();

  // instance的getter方法 - 通过UserModel.instance获取对象2
  static YSMapUntil get instance => _getInstance();

  // 静态变量_instance，存储唯一对象
  static YSMapUntil? _instance;

  // 获取唯一对象
  static YSMapUntil _getInstance() {
    _instance ??= YSMapUntil._internal();
    return _instance!;
  }

  YSMapUntil._internal();

}

extension HexColor on Color {
  /// String is in the format "aabbcc" or "ffaabbcc" with an optional leading "#".
  static Color fromHex(String hexString) {
    final buffer = StringBuffer();
    if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');
    buffer.write(hexString.replaceFirst('#', ''));
    return Color(int.parse(buffer.toString(), radix: 16));
  }

  /// Prefixes a hash sign if [leadingHashSign] is set to `true` (default is `true`).
  String toHex({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}'
      '${alpha.toRadixString(16).padLeft(2, '0')}'
      '${red.toRadixString(16).padLeft(2, '0')}'
      '${green.toRadixString(16).padLeft(2, '0')}'
      '${blue.toRadixString(16).padLeft(2, '0')}';
}

Future<bool> permissionHandler(String serviceStr) async{
  if(serviceStr=='location'){
    if (await Permission.location.request().isGranted||await Permission.locationWhenInUse.request().isGranted) {
      return true;
    }else if (await Permission.location.request().isPermanentlyDenied&&await Permission.locationWhenInUse.request().isPermanentlyDenied) {
      return false;
    }else{
      Map<Permission, PermissionStatus> statuses = await [Permission.location,Permission.locationWhenInUse].request();
      if(statuses[Permission.location]!.isGranted || statuses[Permission.locationWhenInUse]!.isGranted){
        return true;
      }
    }
  }
  return false;
}

timeFormat(int time,{String format = 'yyyy-MM-dd HH:mm:ss'}) {
  // LogUtil.d('timeFormat1=====>$time');
  DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(time);
  // LogUtil.d('timeFormat2=====>$dateTime');
  String dateString = DateFormat(format).format(dateTime).toString();
  // LogUtil.d('timeFormat3=====>$dateString');
  return dateString;
}

class CustomerNotification extends Notification {
  CustomerNotification();
}

class CustomerValueNotification extends Notification {
  final Map value;
  CustomerValueNotification(this.value);
}

class LanguageValueNotification extends Notification {
  final int type;
  LanguageValueNotification(this.type);
}

class YSNumberView2 extends StatefulWidget {
  final ValueSetter numberSetter;
  final int number;
  const YSNumberView2({Key? key, required this.numberSetter, this.number = 1}) : super(key: key);

  @override
  YSNumberView2State createState() => YSNumberView2State();
}

class YSNumberView2State extends State<YSNumberView2> {
  int _number = 1;
  @override
  void initState() {
    _number = widget.number;
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: hsp(100),
      height: hsp(30),
      child: Row(
        children: [
          GestureDetector(
            onTap: (){
              // if(_number<=1)return;
              _number--;
              setState(() {});
              widget.numberSetter(_number);
            },
            behavior: HitTestBehavior.opaque,
            child: Container(
              height: hsp(30),
              width: hsp(30),
              alignment: Alignment.center,
              color: const Color(0xFFF2F3F5),
              child: Icon(Icons.remove,size: hsp(15),color: const Color(0xFF333333),),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: hsp(2),right: hsp(2)),
            color: const Color(0xFFF2F3F5),
            width: hsp(36),
            height: hsp(30),
            alignment: Alignment.center,
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Text('$_number',style: TextStyle(fontSize: zsp(14),color: const Color(0xFF333333)),),
            ),
          ),
          GestureDetector(
            onTap: (){
              _number++;
              setState(() {});
              widget.numberSetter(_number);
            },
            behavior: HitTestBehavior.opaque,
            child: Container(
              height: hsp(30),
              width: hsp(30),
              alignment: Alignment.center,
              color: const Color(0xFFF2F3F5),
              child: Icon(Icons.add,size: hsp(15),color: const Color(0xFF333333),),
            ),
          ),
        ],
      ),
    );
  }
}


class YSNumberView extends StatefulWidget {
  final ValueSetter numberSetter;
  final int number;
  const YSNumberView({Key? key, required this.numberSetter, this.number = 1}) : super(key: key);

  @override
  YSNumberViewState createState() => YSNumberViewState();
}

class YSNumberViewState extends State<YSNumberView> {
  int _number = 1;
  @override
  void initState() {
    _number = widget.number;
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: hsp(100),
      height: hsp(30),
      child: Row(
        children: [
          GestureDetector(
            onTap: (){
              // if(_number<=1)return;
              _number--;
              setState(() {});
              widget.numberSetter(_number);
            },
            behavior: HitTestBehavior.opaque,
            child: Container(
              height: hsp(30),
              width: hsp(30),
              alignment: Alignment.center,
              color: const Color(0xFFF2F3F5),
              child: Icon(Icons.remove,size: hsp(15),color: const Color(0xFF333333),),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: hsp(2),right: hsp(2)),
            color: const Color(0xFFF2F3F5),
            width: hsp(36),
            height: hsp(30),
            alignment: Alignment.center,
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Text('$_number',style: TextStyle(fontSize: zsp(14),color: const Color(0xFF333333)),),
            ),
          ),
          GestureDetector(
            onTap: (){
              _number++;
              setState(() {});
              widget.numberSetter(_number);
            },
            behavior: HitTestBehavior.opaque,
            child: Container(
              height: hsp(30),
              width: hsp(30),
              alignment: Alignment.center,
              color: const Color(0xFFF2F3F5),
              child: Icon(Icons.add,size: hsp(15),color: const Color(0xFF333333),),
            ),
          ),
        ],
      ),
    );
  }
}

networkDelay(VoidCallback callback) {
  Future.delayed(const Duration(seconds: 0)).then((value) {
    callback();
  });
}

String statusString(int status) {
  String statusStr = '';
  switch(status) {
    case 0: statusStr = '待确认';
    break;
    case 1: statusStr = '已采样';
    break;
    case 2: statusStr = '进行中';
    break;
    case 3: statusStr = '待检测';
    break;
    case 4: statusStr = '已完成';
    break;
    case 5: statusStr = '已拒绝';
    break;
  }
  return statusStr;
}

class YSNumberWithDecimalFormat extends TextInputFormatter {
  YSNumberWithDecimalFormat({this.decimalRange = 3})
      : assert(decimalRange > 0);

  final int decimalRange;

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue,
      TextEditingValue newValue) {
    // 拿到录入后的字符
    String nValue = newValue.text;
    //当前所选择的文字区域
    TextSelection nSelection = newValue.selection;

    // 先来一波过滤，过滤出数字及小数点
    // 匹配包含数字和小数点的字符
    Pattern p = RegExp(r'(\d+\.?)|(\.?\d+)|(\.?)');
    nValue = p.allMatches(nValue)
        .map<String>((Match match) => match.group(0)!)
        .join();

    // 用匹配完的字符判断
    if (nValue.startsWith('.')) { //如果小数点开头，我们给他补个0
      nValue = '0.';
    } else if (nValue.contains('.')) {
      //来验证小数点位置
      if (nValue.substring(nValue.indexOf('.') + 1).length > decimalRange) {
        nValue = oldValue.text;
      } else {
        if (nValue.split('.').length > 2) { //多个小数点，去掉后面的
          List<String> split = nValue.split('.');
          nValue = '${split[0]}.${split[1]}';
        }
      }
    }

    //使光标定位到最后一个字符后面
    nSelection = newValue.selection.copyWith(
      baseOffset: math.min(nValue.length, nValue.length + 1),
      extentOffset: math.min(nValue.length, nValue.length + 1),
    );

    return TextEditingValue(
        text: nValue,
        selection: nSelection,
        composing: TextRange.empty
    );
  }
}

class CurrentLocale with ChangeNotifier {
  Locale locale = const Locale('zh','CN');

  Locale get value => locale;
  void setLocale(value)
  {
    locale = value;
    notifyListeners();
  }
}

FilteringTextInputFormatter YSNumberFormate = FilteringTextInputFormatter.allow(RegExp('[0-9]'));

class YSLanguage{
  changeLanguage(BuildContext context,String type) {
    String countryCode = 'CN';
    if(type=='zh'){
      countryCode = 'CN';
    }else if(type=='en'){
      countryCode = 'US';
    }else if(type=='ja'){
      countryCode = 'JP';
    }else if(type=='ru'){
      countryCode = 'RU';
    }else if(type=='fr'){
      countryCode = 'FR';
    }else if(type=='ko'){
      countryCode = 'KR';
    }
    Provider.of<CurrentLocale>(context, listen: false) .setLocale(Locale(type, countryCode));
  }
}




class YSAuthCheck{

  final LocalAuthentication auth = LocalAuthentication();
  Future<bool> check() async{
    List availableBiometric = await auth.getAvailableBiometrics();
    LogUtil.d(availableBiometric);
    final bool didAuthenticate = await auth.authenticate(
      localizedReason: '扫描指纹进行身份验证',
      options: const AuthenticationOptions(
          useErrorDialogs: false,
          stickyAuth: false,
          sensitiveTransaction: true,
          biometricOnly: true
      ),
      authMessages: const <AuthMessages>[
        IOSAuthMessages(

        ),
        AndroidAuthMessages(
          cancelButton: '取消',
          goToSettingsButton: '去设置',
          goToSettingsDescription: '请设置指纹.',
          signInTitle: '指纹验证',
          biometricHint:'将手指放置在对应位置',
        ),
      ],
    );
    LogUtil.d(didAuthenticate);
    return didAuthenticate;
  }
}




class YSCheck{
  Future<bool> check(BuildContext context) async{
    ysShowBottomAlertView(context, YSChooseCheckView(valueSetter: (value){

    },),isBarr: true);
    return false;
  }
}

class YSCopyPaste {
  static copy(String value) {
    Clipboard.setData(ClipboardData(text: value));
    ysFlutterToast(S.current.YIFUZHIDAOZHANTIEBAN);
  }
  static paste() => Clipboard.getData(Clipboard.kTextPlain);
}

class  YSCodeImage {
  static codeImage(String codeStr) => QrImageView(
    data: codeStr,
    version: QrVersions.auto,
    size: hsp(170),
  );
  static Future<String> scanCode() async{
    bool isGet = await getCameraPermission();
    if(isGet){
      String? cameraScanResult = await scanner.scan();
      return cameraScanResult??'';
    }else{
      return '';
    }
  }
}

getCameraPermission() async{
  return await Permission.camera.request().isGranted;
}

int getRandomInt(var min,var max){
  final random = Random();
  return int.parse('${random.nextInt((max - min).floor()) + min}');
}

//打乱数组
shuffle(List arr){
  List newArr = [];
  newArr.addAll(arr);
  for (var i = 1; i < newArr.length; i++){
    var j = getRandomInt(0,i);
    var t = newArr[i];
    newArr[i] = newArr[j];
    newArr[j] = t;
  }
  return newArr;
}

class YSSharedPreferences{
  static setStringValue(String key,String value) async{
    SharedPreferences preferences = await SharedPreferences.getInstance();
    preferences.setString(key, value);
  }
  static getStringValue(String key) async{
    SharedPreferences preferences = await SharedPreferences.getInstance();
   return preferences.getString(key)??'';
  }
  static setBoolValue(String key,bool value) async{
    SharedPreferences preferences = await SharedPreferences.getInstance();
    preferences.setBool(key, value);
  }
  static getBoolValue(String key) async{
    SharedPreferences preferences = await SharedPreferences.getInstance();
    return preferences.get(key);
  }
}

String ysTextCut(String text,{int number = 6}) {
  String result = text;
  if(text.length>20){
    String sub1 = text.substring(0,number);
    String sub2 = text.substring(text.length-number,text.length);
    return '$sub1......$sub2';
  }
  return result;
}

class YSImage{
  static network(String src,{double height = double.infinity,double width = double.infinity}) =>
    CachedNetworkImage(
        imageUrl:src,
        height: height,
        width: width,
        fit: BoxFit.fill,
        errorWidget: (context,_,__){
          return  Icon(Icons.error_outline,color: Colors.redAccent,size: height,);
        },
        // placeholder: (context, url) => const CircularProgressIndicator(color: Colors.black,strokeWidth: 2,)
  );
}

toFlex(value,{int range = 2}){
  return (double.parse('$value')).toStringAsFixed(range);
}
toPercentage(value,{int range = 2}){
  return '${(double.parse('$value')*100).toStringAsFixed(range)}%';
}
toDecimalFlex(value,{int decimal = 0,int range = 2}){
  return (double.parse('$value')/pow(10, decimal)).toStringAsFixed(range);
}
toDateFlex(value){
  DateTime date = DateTime.fromMillisecondsSinceEpoch(value);
  String dateStr = '${date.year}-${'${date.month}'.padLeft(2,'0')}-${'${date.day}'.padLeft(2,'0')} ${'${date.hour}'.padLeft(2,'0')}:${'${date.minute}'.padLeft(2,'0')}:${'${date.second}'.padLeft(2,'0')}';
  return dateStr;
}

Map getWalletType(Map wallet) {
  Map type = {};
  // LogUtil.d('getWalletType====${YSData().typeArray}');
  // LogUtil.d('getWalletType====$wallet');
  List array = YSData().typeArray.where((element) => element['name']==wallet['name']).toList();
  if(array.isNotEmpty){
    type = array.first;
  }
  return type;
}



extension FixAutoLines on String {
  String fixAutoLines() {
    return Characters(this).join('\u{200B}');
  }
}

class YSPriceTypeNotifier with ChangeNotifier {
  String type = '1';

  String get value => type;
  void setType(String value)
  {
    YSUserRecord().priceType = value;
    type = value;
    notifyListeners();
  }
}



