import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutterappfuyou/code/base/YSTools.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../YSlogin.dart';

//https://v2fy.niwoshenghuo.com
//http://114.115.251.233:30009
//https://v3fy.niwoshenghuo.com
//https://v3fy.api.niwoshenghuo.com
//https://v3fy.niwoshenghuo.com/v3api
//http://192.168.1.33:8088
String base = 'https://v3fy.niwoshenghuo.com/v3api/api/';
// ignore: camel_case_types
enum requestType{
  put,
  delete,
  get,
  post
}

ysRequestHttp(BuildContext context,requestType type,String api,var parameter) async {
  showDialog(
    context: context,
    barrierDismissible: false,
    builder: (BuildContext context) {return LoadingDialog(text: "正在请求",);}
  );
  try {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String token = prefs.getString('token');
    Map<String, dynamic> httpHeaders = {
      'Accept': 'application/json,*/*',
      // 'Content-Type': 'application/json',
      'Authorization':'Bearer $token'
    };
    String url = base+api;
    print('请求网址:$url');
    print('token:$token');
    print('请求参数:$parameter');
    Response response;
    if(type==requestType.put){
      response = await Dio().put(url,data: parameter,options: Options(receiveTimeout: 10000,headers: httpHeaders));
    }else if(type==requestType.post){
      response = await Dio().post(url,data: parameter,options: Options(receiveTimeout: 10000,headers: httpHeaders));
    }else if(type==requestType.delete){
      response = await Dio().delete(url,data: parameter,options: Options(receiveTimeout: 10000,headers: httpHeaders));
    }else if(type==requestType.get){
      response = await Dio().get(url,queryParameters: Map<String, dynamic>.from(parameter),options: Options(receiveTimeout: 10000,headers: httpHeaders));
    }
    Navigator.of(context,rootNavigator: true).pop();
    LogUtil.d('请求结果:$url ${response.data}');
    if(response.data is List){
      List list = response.data;
      return list;
    }else{
      Map dict = response.data;
      if(api=='user/info'&&type==requestType.get){
        return dict['data'];
      }else if(api=='chapter/list' || api=='policy/list' || api=='policy/info' || api=='policy/doctor' || api=='policy/doctorInfo'){
        return dict;
      }else if(dict['code']==200 || dict['status']=='0000'){
        return dict;
      }else if(dict['datas']!=null||dict['id']!=null){
        return dict;
      }else if(dict['code']==401){
        clearAndToLogin(context);
      }else{
        if(dict['msg']!=null){
          ysFlutterToast(context,dict['msg'].toString());
        }else if(dict['message']!=null){
          ysFlutterToast(context,dict['message'].toString());
        }
      }
    }
  } catch (error) {
    Navigator.of(context,rootNavigator: true).pop();
    print('网络错误:$error');
    if(error.message=='Http status error [401]'){
      clearAndToLogin(context);
    }else{
      ysFlutterToast(context,'系统繁忙，请稍后重试');
    }
  }
}

clearAndToLogin(BuildContext context) {
  ysFlutterToast(context,'登录失效，请重新登录');
  Future<SharedPreferences> _prefer = SharedPreferences.getInstance();
  _prefer.then((value){
    value.remove('token');
  });
  Navigator.of(context,rootNavigator: true).pushAndRemoveUntil(
      MaterialPageRoute(
          builder: (context){
            return YSLogin(isCheck: true,);
          }
      ), (route) => false);
}

ysRequestHttpNoLoading(BuildContext context,requestType type,String api,var parameter) async {
  try {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String token = prefs.getString('token');
    Map<String, dynamic> httpHeaders = {
      'Accept': 'application/json,*/*',
      // 'Content-Type': 'application/json',
      'Authorization':'Bearer $token'
    };
    LogUtil.d(httpHeaders);
    String url = base+api;
    print('请求网址:$url');
    print('token:$token');
    print('请求参数:$parameter');
    Response response;
    if(type==requestType.put){
      response = await Dio().put(url,data: parameter,options: Options(receiveTimeout: 10000,headers: httpHeaders));
    }else if(type==requestType.post){
      response = await Dio().post(url,data: parameter,options: Options(receiveTimeout: 10000,headers: httpHeaders));
    }else if(type==requestType.delete){
      response = await Dio().delete(url,data: parameter,options: Options(receiveTimeout: 10000,headers: httpHeaders));
    }else if(type==requestType.get){
      response = await Dio().get(url,queryParameters: Map<String, dynamic>.from(parameter),options: Options(receiveTimeout: 10000,headers: httpHeaders));
    }
    LogUtil.d('请求结果:$url ${response.data}');
    // LogUtil.d('请求结果: ${response.data}');
    if(response.data is List){
      List list = response.data;
      return list;
    }else if(response.data is Map){
      Map dict = response.data;
      if(api=='basic/BodyStandard'|| api=='upQiniuToken' || api=='app/version'){
        return dict;
      }else if(api=='wike/list'  || api=='wike/favoriteList' || api=='policy/list'){//|| api=='basic/info'
        if(dict['code']==200){
          List datas = dict['data']['datas']??[];
          dict['data'] = datas;
          return dict;
        }
      }else if(api=='tool/list'||api=='policy/doctor'||api=='user/info'){
        return dict['data'];
      }else if(dict['code']==200 || dict['status']=='0000'){
        return dict;
      }else if(dict['datas']!=null||dict['id']!=null){
        return dict;
      }else if(dict['code']==401){
        clearAndToLogin(context);
      }else{
        if(dict['msg']!=null){
          ysFlutterToast(context,dict['msg']??'');
        }else if(dict['message']!=null){
          ysFlutterToast(context,dict['message']??'');
        }
      }
    }
  } catch (error) {
    LogUtil.d('网络错误:$error');
    if(error.message=='Http status error [401]'){
      clearAndToLogin(context);
    }else{
      ysFlutterToast(context,'系统繁忙，请稍后重试');
    }
  }
}

class LoadingDialog extends Dialog {
  final String text;

  LoadingDialog({Key key, @required this.text}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: Center(
        child: SizedBox(
          width: 120.0,
          height: 120.0,
          child: Container(
            decoration: ShapeDecoration(
              color: Color(0xFFDB5278),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(
                  Radius.circular(8.0),
                ),
              ),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                CircularProgressIndicator(valueColor: AlwaysStoppedAnimation<Color>(Colors.white),),
                Padding(
                  padding: EdgeInsets.only(top: 20.0,),
                  child: Text(text,style: TextStyle(color: Colors.white),),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

void ysFlutterToast(BuildContext context,String msg){
  FlutterToast(context).showToast(
    child: Padding(
      padding: EdgeInsets.only(top: 100),
      child: Container(
        padding: EdgeInsets.only(left: 20,right: 20,top: 5,bottom: 5),
        decoration: BoxDecoration(
          color: Color(0xFFDB5278),
          borderRadius: BorderRadius.all(Radius.circular(25))
        ),
        child: Text(msg,style: TextStyle(fontSize: 14,color: Colors.white),),
      ),
    ),
    gravity: ToastGravity.CENTER,
    toastDuration: Duration(seconds: 2),
  );
}
