import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wallet/tools/YSLoadData.dart';
import 'package:flutter_wallet/tools/YSSqflite.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'YSTools.dart';
import 'package:http/http.dart' as http;

//https://bakewallet.io
//http://8.222.222.151
//https://bakewallet.info
String base = 'https://bakewallet.info/api/v1/';
String base2 = 'https://bakewallet.info/api';
int outTime = 100000;//10000

enum RequestType{
  put,
  delete,
  get,
  post
}

class YSNetWork{

  static ysRequestHttp(BuildContext context,{required RequestType type,required String api,required dynamic
  parameter,bool isLoading = false,bool isToken = true,required ValueSetter successSetter,VoidCallback? errorSetter})  async{
    if(isLoading==false){
      String url = '$base$api';
      if(api=='cross-configs'||api.contains('cross-txs')){
        url = 'https://cross.bakewallet.org/api/v1/$api';
      }
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String token = prefs.getString('token')??'';
      // LogUtil.d('请求token:$token');
      Map<String, dynamic> httpHeaders = {
        'Accept': 'application/json,*/*',
        'Content-Type': 'application/json',
        if(isToken==true)'Authorization': 'Bearer $token'
      };
      LogUtil.d('请求头 $httpHeaders');
      try {
        LogUtil.d('请求网址:$url\n请求参数:$parameter');
        Response response;
        if(type==RequestType.put){
          response = await Dio().put(url,data: parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
        }else if(type==RequestType.post){
          response = await Dio().post(url,data: parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
        }else if(type==RequestType.delete){
          response = await Dio().delete(url,data: parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
        }else{
          response = await Dio().get(url,queryParameters: Map<String, dynamic>.from(parameter),options: Options(receiveTimeout: outTime,headers: httpHeaders));
        }
        // LogUtil.d('请求网址:$url\n请求结果:${response.data}');
        Map dict = response.data;
        LogUtil.d('请求网址:$url\n请求参数:$parameter\n请求结果:$dict');
        if(dict['code']==10000){
          successSetter(dict);
          if(type==RequestType.get){
            saveDict(api,dict);
          }
        }else if(dict['code']==401){
          ysFlutterToast('${dict['msg']??''}');
          prefs.remove('token');
          // ignore: use_build_context_synchronously
          // Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context){
          //   return const YSLogin();
          // }), (route) => false);
        }else{
          ysFlutterToast('${dict['msg']??''}');
        }
      } catch (error) {
        LogUtil.d('请求网址:$url\n请求参数:$parameter\n网络错误$api:$error');
        if(type==RequestType.get){
          Map loadD = await loadDict(api);
          if(loadD.isNotEmpty){
            successSetter(loadD);
          }else if(api=='chains'){
            successSetter(YSLoadData().typeDict);
          }
        }
        if(errorSetter!=null){
          errorSetter();
        }
      }
    }else{
      ysShowCenterAlertView(context, YSNetWorkView(type: type, api: api,parameter: parameter,isLoading: isLoading,isToken: isToken,imageSetter: (value){},successSetter: (value){
        if(value.isEmpty){
          if(errorSetter!=null){
            errorSetter();
          }
        }else{
          successSetter(value);
        }
      },),isTrans: true);
    }
  }

  static Future<Map> ysRequestHttpNOSet(BuildContext context,{required RequestType type,required String api,required dynamic
  parameter,bool isLoading = false,bool isToken = true})  async{
    String url = '$base$api';
    if(api=='cross-configs'||api.contains('cross-txs')){
      url = 'https://cross.bakewallet.org/api/v1/$api';
    }
    if(api=='tronsign'||api=='createtransfer'||api=='tronswap'||api=='tron/myres'
        ||api=='tron/query/approve'||api=='tron/approve/start'||api=='tron/approve/check'
        ||api=='tron/approve/check'||api=='tron/query/swap'||api=='tron/doswap'){
      url = '$base2/v2/$api';
    }
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String token = prefs.getString('token')??'';
    // LogUtil.d('请求token:$token');
    Map<String, dynamic> httpHeaders = {
      'Accept': 'application/json,*/*',
      'Content-Type': 'application/json',
      if(isToken==true)'Authorization': 'Bearer $token'
    };
    LogUtil.d('请求头 $httpHeaders');
    try {
      LogUtil.d('请求网址:$url\n请求参数:$parameter');
      Response response;
      if(type==RequestType.put){
        response = await Dio().put(url,data: parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
      }else if(type==RequestType.post){
        response = await Dio().post(url,data: parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
      }else if(type==RequestType.delete){
        response = await Dio().delete(url,data: parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
      }else{
        response = await Dio().get(url,queryParameters: Map<String, dynamic>.from(parameter),options: Options(receiveTimeout: outTime,headers: httpHeaders));
      }
      Map dict = response.data;
      LogUtil.d('请求网址:$url\n请求参数:$parameter\n请求结果:$dict');
      if(dict['code']==10000){
        return dict;
      }else if(dict['code']==401){
        ysFlutterToast('${dict['msg']??''}');
        prefs.remove('token');
        // ignore: use_build_context_synchronously
        // Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context){
        //   return const YSLogin();
        // }), (route) => false);
        return {};
      }else{
        ysFlutterToast('${dict['msg']??''}');
        return {};
      }
    } catch (error) {
      LogUtil.d('请求网址:$url\n请求参数:$parameter\n网络错误$api:$error');
      return {};
    }
  }

  static ysRequestHttpNOSet2(BuildContext context,{required RequestType type,required String api,required dynamic
  parameter,bool isLoading = false,bool isToken = true})  async{
    String url = '$base$api';
    if(api=='cross-configs'||api.contains('cross-txs')){
      url = 'https://cross.bakewallet.org/api/v1/$api';
    }
    if(api=='tronsign'||api=='createtransfer'||api=='tronswap'||api=='tron/myres'
        ||api=='tron/query/approve'||api=='tron/approve/start'||api=='tron/approve/check'||api=='tron/approve/check'){
      url = '$base2/v2/$api';
    }
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String token = prefs.getString('token')??'';
    // LogUtil.d('请求token:$token');
    Map<String, dynamic> httpHeaders = {
      'Accept': 'application/json,*/*',
      'Content-Type': 'application/json',
      if(isToken==true)'Authorization': 'Bearer $token'
    };
    LogUtil.d('请求头 $httpHeaders');
    try {
      LogUtil.d('请求网址:$url\n请求参数:$parameter');
      Response response;
      if(type==RequestType.put){
        response = await Dio().put(url,data: parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
      }else if(type==RequestType.post){
        response = await Dio().post(url,data: parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
      }else if(type==RequestType.delete){
        response = await Dio().delete(url,data: parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
      }else{
        response = await Dio().get(url,queryParameters: Map<String, dynamic>.from(parameter),options: Options(receiveTimeout: outTime,headers: httpHeaders));
      }
      Map dict = response.data;
      LogUtil.d('请求网址:$url\n请求参数:$parameter\n请求结果:$dict');
      if(dict['code']==10000){
        if(api=='tron/approve/check'){
          Map data = dict['data']??{};
          if(data.isNotEmpty){
            return dict;
          }else{
            LogUtil.d('ysRequestHttpNOSet2=========$data');
            // ignore: use_build_context_synchronously
            return ysRequestHttpNOSet2(context, type: type, api: api, parameter: parameter);
          }
        }else{
          return dict;
        }
      }else if(dict['code']==401){
        ysFlutterToast('${dict['msg']??''}');
        prefs.remove('token');
        // ignore: use_build_context_synchronously
        // Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context){
        //   return const YSLogin();
        // }), (route) => false);
        // return {};
      }else{
        ysFlutterToast('${dict['msg']??''}');
        // return {};
      }
    } catch (error) {
      LogUtil.d('请求网址:$url\n请求参数:$parameter\n网络错误$api:$error');
      // return {};
    }
  }



  static ysRequestHttp2(BuildContext context,{required RequestType type,required String api,required dynamic parameter,bool isLoading = false,bool isToken = true,required
  ValueSetter imageSetter,required ValueSetter successSetter}) {
    FocusScope.of(context).unfocus();
    ysShowCenterAlertView(context, YSImageUploadView(type: type, api: api,parameter: parameter,isLoading: isLoading,isToken: isToken,imageSetter: (value){
      imageSetter(value);
    },successSetter: (value){
      successSetter(value);
    }),isTrans: true);
  }

  static Future<Map> httpNetwork({required String api,int type = 1,required Map request}) async{
    try{
      var client = http.Client();
      String url = '$base$api';
      if(api=='bitconinp2sh'||api=='bithash'){
        url = '$base2/v2/$api';
      }
      var body = jsonEncode(request);
      LogUtil.d('请求参数=======\n$url\n$body');
      // 发送POST请求
      var response = await client.post(
        Uri.parse(url),
        headers: {'Content-Type': 'application/json'},
        body: body,
      );
      LogUtil.d('请求结果=======\n$url\n${response.body}');
      Map dict = jsonDecode(response.body);
      LogUtil.d('请求结果=======\n$url\n$dict');
      if(dict['code']==10000){
        return dict;
      }else if(dict['code']==5000002){
        ysFlutterToast(dict['message']??'');
      }
      return {};
    }catch(error){
      LogUtil.d(error);
      return {};
    }
  }

  static Future<Map> httpNetwork2({required String api,int type = 1,required Map request,bool isEncode = false}) async{
    try{
      var client = http.Client();
      String url = '$base$api';
      if(api=='bitconinp2sh'||api=='bithash'){
        url = '$base2/v2/$api';
      }
      var body = jsonEncode(request);
      LogUtil.d('请求参数=======\n$url\n$body');
      // 发送POST请求
      var response = await client.get(
        Uri.parse(url),
        headers: {'Content-Type': 'application/json'},
      );
      LogUtil.d('请求结果=======\n$url\n${response.body}');
      Map dict = jsonDecode(response.body);
      LogUtil.d('请求结果=======\n$url\n$dict');
      if(dict['code']==10000){
        return dict;
      }else if(dict['code']==5000002){
        ysFlutterToast(dict['message']??'');
      }
      return {};
    }catch(error){
      LogUtil.d(error);
      return {};
    }
  }

}

void ysFlutterToast(String msg,{bool isCenter = false}){
  Fluttertoast.showToast(
    msg: msg,
    gravity: isCenter?ToastGravity.CENTER:ToastGravity.BOTTOM,
    textColor: Colors.white,
    backgroundColor: Colors.black87,
    timeInSecForIosWeb: 2,
  );
}

class YSNetWorkView extends StatefulWidget {
  final ValueSetter<Map> successSetter;
  final ValueSetter imageSetter;
  final RequestType type;
  final String api;
  final dynamic parameter;
  final bool isLoading;
  final bool isToken;
  final bool isImage;
  const YSNetWorkView({Key? key, required this.type, required this.api, this.parameter, this.isLoading = false, this.isToken = true,
    required this.imageSetter,this.isImage = false, required this.successSetter}) : super(key: key);

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

class YSNetWorkViewState extends State<YSNetWorkView> {
  bool _isError = false;
  @override
  void initState() {
    Future.delayed(const Duration(seconds: 0)).then((value) async{
      Map dict = await _getData();
      widget.successSetter(dict);
    });
    super.initState();
  }
  _getData() async{
    String url = '$base${widget.api}';
    if(widget.api=='cross-configs'||widget.api=='cross-txs'){
      url = 'https://cross.bakewallet.org/api/v1/${widget.api}';
    }
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String token = prefs.getString('token')??'';
    Map<String, dynamic> httpHeaders = {
      'Accept': 'application/json,*/*',
      'Content-Type': 'application/json',
      if(widget.isToken==true)'Authorization': 'Bearer $token'
    };
    try {
      LogUtil.d('请求网址:$url\n请求参数:${widget.parameter}');
      Response response;
      if(widget.type==RequestType.put){
        response = await Dio().put(url,data: widget.parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
      }else if(widget.type==RequestType.post){
        response = await Dio().post(url,data: widget.parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
      }else if(widget.type==RequestType.delete){
        response = await Dio().delete(url,data: widget.parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
      }else{
        response = await Dio().get(url,queryParameters: Map<String, dynamic>.from(widget.parameter),options: Options(receiveTimeout: outTime,headers: httpHeaders));
      }
      LogUtil.d('请求网址:$url\n请求结果:${response.data}');
      Map dict = response.data;
      if(!mounted)return;
      Navigator.pop(context);
      if(dict['code']==10000){
        if(widget.type==RequestType.get){
          saveDict(widget.api,dict);
        }
        return dict;
      }else if(dict['code']==401){
        ysFlutterToast('${dict['msg']??''}');
        if (!mounted) return;
        // Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context){
        //   return const YSLogin();
        // }), (route) => false);
        prefs.remove('token');
        return {};
      }else{
        ysFlutterToast('${dict['msg']??''}');
        return {};
      }
    } catch (error) {
      if (!mounted) return;
      Navigator.pop(context);
      _isError = true;
      setState(() {});
      LogUtil.d('请求网址:$url\n网络错误:$error');
      if(widget.type==RequestType.get){
        Map loadD = await loadDict(widget.api);
        if(loadD.isNotEmpty){
          return loadD;
        }else if(widget.api=='chains'){
          return YSLoadData().typeDict;
        }
      }
      return {};
    }
  }
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async{
        return false;
      },
      child: widget.isLoading==false?Container():Center(
        child: Container(
          height: hsp(150),
          width: hsp(150),
          decoration: const BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(5)),
            color: Colors.black45,
          ),
          alignment: Alignment.center,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(
                width: 60,
                height: 60,
                child: _isError==true?const Icon(
                  Icons.error_outline,size: 60,color: Colors.redAccent,
                ):CupertinoActivityIndicator(
                  radius: hsp(20),
                  color: Colors.white,
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: hsp(15)),
                child:  Text(_isError==true?'出错了':'请求中',style: TextStyle(fontSize: zsp(16),color: Colors.white,decoration: TextDecoration.none),),
              )
            ],
          ),
        ),
      ),
    );
  }
}


saveDict(String key,Map dict) {
  YSSqflite3 sqflite3 = YSSqflite3().init();
  if(dict.isNotEmpty){
    sqflite3.rawInsert(key, dict);
  }
}
loadDict(String key) async{
  YSSqflite3 sqflite3 = YSSqflite3().init();
  Object object = await sqflite3.rawQuery(key);
  LogUtil.d('loadDict========$key===========$object');
  return object;
}

class YSImageUploadView extends StatefulWidget {
  final ValueSetter successSetter;
  final ValueSetter imageSetter;
  final RequestType type;
  final String api;
  final dynamic parameter;
  final bool isLoading;
  final bool isToken;
  const YSImageUploadView({Key? key, required this.type, required this.api, this.parameter, this.isLoading = false, this.isToken = true,
    required this.imageSetter, required this.successSetter}) : super(key: key);

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

class YSImageUploadViewState extends State<YSImageUploadView> {
  double _rota1 = 0.0;
  double _rota2 = 0.0;
  bool _isError = false;
  @override
  void initState() {
    Future.delayed(const Duration(seconds: 0)).then((value) async{
      Map dict = await _getData();
      if(dict.isNotEmpty){
        widget.successSetter(dict);
      }
    });
    super.initState();
  }
  _getData() async{
    String url = '$base${widget.api}';
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String token = prefs.getString('token')??'';
    Map<String, dynamic> httpHeaders = {
      'Accept': 'application/json,*/*',
      'Content-Type': 'application/json',
      if(widget.isToken==true)'Authorization': 'Bearer $token'
    };
    try {
      LogUtil.d('请求网址:$url\n请求参数:${widget.parameter}');
      // LogUtil.d('请求网址:$url\n加密参数:$secret');
      Response response;
      if(widget.type==RequestType.put){
        response = await Dio().put(url,data: widget.parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
      }else if(widget.type==RequestType.post){
        response = await Dio().post(url,data: widget.parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders),
            onReceiveProgress: (int1,int2){
              if(int2==-1){
                _rota1 = 1;
              }else{
                _rota1 = int1/int2;
              }
              setState(() {});
            },
            onSendProgress: (int1,int2){
              _rota2 = int1/int2;
              setState(() {});
              widget.imageSetter(_rota2);
            });
      }else if(widget.type==RequestType.delete){
        response = await Dio().delete(url,data: widget.parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
      }else{
        response = await Dio().get(url,queryParameters: Map<String, dynamic>.from(widget.parameter),options: Options(receiveTimeout: outTime,headers: httpHeaders));
      }
      LogUtil.d('请求网址:$url\n请求结果:${response.data}');
      // return;
      Map dict = response.data;
      if(!mounted)return;
      Navigator.pop(context);
      if(dict['code']==200){
        return dict;
      }else if(dict['code']==401){
        ysFlutterToast('${dict['msg']??''}');
        if (!mounted) return;
        // Navigator.of(context).push(
        //     CupertinoPageRoute(builder: (context){
        //       return const YSLogin();
        //     })
        // );
        prefs.remove('token');
        return {};
      }else{
        ysFlutterToast('${dict['msg']??''}');
        return {};
      }
    } catch (error) {
      if (!mounted) return;
      Navigator.pop(context);
      _isError = true;
      setState(() {});
      LogUtil.d('请求网址:$url\n网络错误:$error');
      return {};
    }
  }
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async{
        return false;
      },
      child: widget.isLoading==false?Container():Center(
        child: Container(
          height: hsp(150),
          width: hsp(150),
          decoration: const BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(5)),
            color: Colors.black45,
          ),
          alignment: Alignment.center,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(
                width: 60,
                height: 60,
                child: _isError==true?const Icon(
                  Icons.error_outline,size: 60,color: Colors.redAccent,
                ):_rota2==1&&_rota1==1?const Icon(
                  Icons.check,size: 60,color: Colors.green,
                ):CircularProgressIndicator(
                  value: _rota2==1?_rota1:_rota2,
                  color: Colors.lightBlueAccent,
                  backgroundColor: Colors.white,
                  strokeWidth: 5,
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: hsp(15)),
                child:  Text(_isError==true?'出错了':_rota2<1?'上传中':_rota1<1?'接收中':'完成',style: TextStyle(fontSize: zsp(16),color: Colors.white,decoration: TextDecoration.none),),
              )
            ],
          ),
        ),
      )
    );
  }
}

