import 'dart:io';

import 'package:device_info_plus/device_info_plus.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:intl/intl.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:math' as math;

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;
Color ysBgColor = const Color(0xFF23262B);
Color ysTitleColor = const Color(0xFFACB5C5);
Color ysValueColor = Colors.white;
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 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);
}

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("");
    }
  }
}

ysShowBottomAlertView(BuildContext context,Widget widget,{bool isBarr = false}) {
  showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      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 {

  List urgentArray = [];
  String modelId = '';
  double bili = 1.0;
  String detailsId = '0';
  Image image = Image.asset('images/tzh_clear.png',color: Colors.transparent,);

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

///单例类
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;
      }
    }
  }else if(serviceStr=='file'){
    // LogUtil.d(await Permission.photos.request().isGranted&&await Permission.videos.request().isGranted);
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    // int version = int.parse(androidInfo.version.release);
    // LogUtil.d(androidInfo.version.sdkInt);
    // return false;
    if(androidInfo.version.sdkInt > 32){
      if (await Permission.photos.request().isGranted&&await Permission.videos.request().isGranted) {
        return true;
      }else if (await Permission.photos.request().isPermanentlyDenied||await Permission.videos.request().isPermanentlyDenied) {
        return false;
      }else{
        Map<Permission, PermissionStatus> statuses = await [Permission.photos,Permission.videos].request();
        if(statuses[Permission.photos]!.isGranted&&statuses[Permission.videos]!.isGranted){
          return true;
        }
      }
    }else{
      if (await Permission.storage.request().isGranted) {
        return true;
      }else if (await Permission.storage.request().isPermanentlyDenied) {
        return false;
      }else{
        Map<Permission, PermissionStatus> statuses = await [Permission.storage].request();
        if(statuses[Permission.storage]!.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 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 NumberFormat extends TextInputFormatter {

  NumberFormat({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
    );
  }
}