import 'dart:convert';

import 'package:chat/data/WebData.dart';
import 'package:chat/data/chat_data_mgr.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/data/group_data_mgr.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/home/EditData.dart';
import 'package:chat/home/IndexPage.dart';
import 'package:chat/home/MoneyPage.dart';
import 'package:chat/home/SelectSexPage.dart';
import 'package:chat/models/ChatMsg.dart';
import 'package:chat/models/UserInfo.dart';
import 'package:chat/models/daily_bonus.dart';
import 'package:chat/models/money_change.dart';
import 'package:chat/proto/all.pbserver.dart';
import 'package:chat/utils/LoadingDialog.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/NetUtil.dart';
import 'package:chat/utils/blacklist_mgr.dart';
import 'package:chat/utils/friend_list_mgr.dart';
import 'package:chat/utils/image_util.dart';
import 'package:chat/utils/local_notification_util.dart';
import 'package:chat/utils/sp_utils.dart';
import 'package:chat/utils/sql_util.dart';
import 'package:chat/utils/user_info_table.dart';
import 'package:device_info/device_info.dart';
import 'dart:core';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inapp_purchase/flutter_inapp_purchase.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:io';
import '../data/UserData.dart';
import '../utils/TokenMgr.dart';
import 'package:http_parser/http_parser.dart';

class HttpUtil {
  static HttpUtil _instance;
  Dio dio;
  BaseOptions options;

  //static const String BaseUrl = 'http://192.168.0.223:7001/';
  //static const String BaseUrl = 'http://192.168.0.207:9080/';
  static const String BaseUrl = 'http://120.79.107.63:9080/';
  //static const String BaseUrl = 'http://192.168.0.177:9016/';
//  static const String BaseUrl = 'https://datasm.chengyouhd.com/';

  static HttpUtil _getInstance() {
    if (_instance == null) {
      _instance = HttpUtil._();
    }
    return _instance;
  }

  factory HttpUtil() => _getInstance();
  Map friendCache = {};

  HttpUtil._() {
    options = BaseOptions(
      baseUrl: BaseUrl,
      headers: {},
    );
    dio = new Dio(options);

//        (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
//        (HttpClient client) {
//      client.findProxy = (uri) {
//        //proxy all request to localhost:8888
//        return "PROXY 192.168.0.181:8888";
//      };
//      client.badCertificateCallback =
//          (X509Certificate cert, String host, int port) => true;
//    };

    dio.interceptors
        .add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
      // Do something before request is sent
      return options; //continue
      // If you want to resolve the request with some custom data，
      // you can return a `Response` object or return `dio.resolve(data)`.
      // If you want to reject the request with a error message,
      // you can return a `DioError` object or return `dio.reject(errMsg)`
    }, onResponse: (Response response) async {
      // Do something with response data
      return response; // continue
    }, onError: (DioError e) async {
      // Do something with response error
      showToast(I18n.of(Constants.getCurrentContext()).net_error);
      return e; //continue
    }));
  }

  Future get(url, {data, options, cancelToken}) async {
    print('get请求启动! url：$url ,body: $data');
    Response response;
    try {
      response = await dio.get(
        url,
        queryParameters: data,
        cancelToken: cancelToken,
      );
      print('get请求成功!$url');
    } on DioError catch (e) {
      if (CancelToken.isCancel(e)) {
        print('get请求取消! ' + e.message);
      }
      print('get请求发生错误：$e');
    }
    return response;
  }

  getFriendList(callback) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil().post('friendship/friends/list', data: data);

    Map resData = res.data;

    if (resData['code'] == 0) {
      if (callback != null) callback(resData['data']);
    }
  }

  Future getDataWX(url, {data, options, cancelToken}) async {
    print('get请求启动! url：$url ,body: $data');
    Response response;
    BaseOptions options = BaseOptions(
      headers: {},
    );
    Dio dio = new Dio(options);
    try {
      response = await dio.get(
        url,
        queryParameters: data,
        cancelToken: cancelToken,
      );
      print('get请求成功!$url');
    } on DioError catch (e) {
      if (CancelToken.isCancel(e)) {
        print('get请求取消! ' + e.message);
      }
      print('get请求发生错误：$e');
    }
    return response;
  }

  Future post(url,
      {data,
      options,
      cancelToken,
      bool isShowLoading = false,
      failback}) async {
    print('post请求启动! url：$url ,body: $data');
    Response response;
    if (isShowLoading) LoadingManage().showLoading();
    try {
      response = await dio.post(
        url,
        data: data,
        cancelToken: cancelToken,
      );
      print('$url post请求成功!   $BaseUrl');
      if (isShowLoading) LoadingManage().closeLoading();
    } on DioError catch (e) {
      if (CancelToken.isCancel(e)) {
        print('post请求取消! ' + e.message);
      }
      print('post请求发生错误：$e');
      if (isShowLoading) LoadingManage().closeLoading();
      showToast(I18n.of(Constants.getCurrentContext()).server_error_tips);
      if (failback != null) failback();
    }
    return response;
  }

  // 上传文件
  Future uploadFile(File imgfile, data, url, contentType,
      {isShowLoading = false}) async {
    FormData formData = new FormData.fromMap({
      "type": data["type"],
      "userId": data["userId"],
      "sex": data['sex'] == null ? 0 : data['sex'],
      "isBurn": data['isBurn'] == null ? 0 : data['isBurn'],
      "sign": data['sign'],
      "file": await getMultipartFile(imgfile, contentType)
    });
    print('post请求启动! url：$url');
    if (isShowLoading) LoadingManage().showLoading();
    Response response;
    try {
      response = await dio.post(
        url,
        data: formData,
      );
      print('post请求成功!response.data：${response.data}');
      if (isShowLoading) LoadingManage().closeLoading();
    } on DioError catch (e) {
      if (CancelToken.isCancel(e)) {
        print('post请求取消! ' + e.message);
      }
      print('post请求发生错误：$e');
      if (isShowLoading) LoadingManage().closeLoading();
    }
    return response;
  }

  Future<MultipartFile> getMultipartFile(
      File imgfile, String contentType) async {
    //压缩图片文件
    var size = await imgfile.length();
    String path = imgfile.path;

    var fileBytes;
    if (contentType == 'image' && size > 10240) {
      fileBytes =
          await WidgetUtil.getCompressImg(path, quality: 80, percentage: 80);
    } else {
      fileBytes = imgfile.readAsBytesSync();
    }
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
    return new MultipartFile.fromBytes(fileBytes,
        filename: name, contentType: MediaType(contentType, suffix));
  }

  // 上传多个图片
  Future uploadFiles(List<File> imgfileList, data, url, contentType,
      {isShowLoading = false}) async {
    var imgList = [];
    for (int i = 0; i < imgfileList.length; i++) {
      imgList.add(await getMultipartFile(imgfileList[i], contentType));
    }
    FormData formData = new FormData.fromMap({
      "type": data["type"],
      "userId": data["userId"],
      "sex": data['sex'] == null ? 0 : data['sex'],
      "isBurn": data['isBurn'] == null ? 0 : data['isBurn'],
      "sign": data['sign'],
      "file": imgList
    });
    print('post请求启动! url：$url');
    if (isShowLoading) LoadingManage().showLoading();
    Response response;
    try {
      response = await dio.post(
        url,
        data: formData,
      );
      print('post请求成功!response.data：${response.data}');
      if (isShowLoading) LoadingManage().closeLoading();
    } on DioError catch (e) {
      if (CancelToken.isCancel(e)) {
        print('post请求取消! ' + e.message);
      }
      print('post请求发生错误：$e');
      if (isShowLoading) LoadingManage().closeLoading();
    }
    return response;
  }

  Future getUserInfoFromServer(int friendId) async {
    Map<String, dynamic> data = {
      "visitUserId": UserData().basicInfo.userId,
      "userId": friendId,
      "language": UserData().language,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['lat'] = UserData().latitude;
    data['lng'] = UserData().longitude;
    print('请求用户信息 $data}');
    print('从服务器获取用户信息$friendId');
    Response res = await HttpUtil().post('user/info/list', data: data);

    if (res == null) {
      return null;
    }
    Map resData = res.data;
    print('用户信息resData $resData');
    if (resData['code'] == 0) {
      var info = UserInfo.fromJson(resData['data']);
      info.isBlackened
          ? BlacklistMgr.addBlackListMe(info.userId)
          : BlacklistMgr.removeBalckListMe(info.userId);

      info.isBlackList
          ? BlacklistMgr.addMyBlackList(info.userId)
          : BlacklistMgr.removeMyBalckList(info.userId);
      friendCache[friendId] = info;
      FriendListMgr().updateFriendInfo(info);
      UserInfoTable().insertUser(info);
      MessageMgr().emit('UpdateUserInfo', info);
      return info;
    } else {
      return null;
    }
  }

  Future getFriendInfo(int friendId, [bool isUpdate = false]) async {
    print('开始获取用户信息$friendId');
    if (friendId == null) {
      print('用户Id为空，无法获取信息');
      return null;
    }

    if (friendCache[friendId] != null) {
      print('存在用户信息$friendId 缓存');
      if (isUpdate) {
        //如果需要更新，那么先读取旧数据，然后后台更新
        getUserInfoFromServer(friendId);
      }

      return friendCache[friendId];
    }

    var info = await SqlUtil.userInfoTable.getUserInfoFromLocal(friendId);
    print('从本地数据库读取用户$friendId 信息');
    if (info != null) {
      if (isUpdate) {
        //如果需要更新，那么先读取旧数据，然后后台更新
        getUserInfoFromServer(friendId);
      }

      friendCache[friendId] = info;
      return info;
    }

    return await getUserInfoFromServer(friendId);
  }

  getUserInfo(visitedUserId, [callback, failcallback, errorcallback]) async {
    var data = {
      "visitUserId": UserData().basicInfo.userId,
      "userId": visitedUserId,
      "language": UserData().language,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['lat'] = UserData().latitude;
    data['lng'] = UserData().longitude;
    Response res = await HttpUtil()
        .post('user/info/list', data: data, failback: errorcallback);

    if (res == null) {
      print('请求异常');
      return;
    }
    Map resData = res.data;

    if (resData['code'] == 0) {
      var info = UserInfo.fromJson(resData['data']);
      info.isBlackened
          ? BlacklistMgr.addBlackListMe(info.userId)
          : BlacklistMgr.removeBalckListMe(info.userId);

      info.isBlackList
          ? BlacklistMgr.addMyBlackList(info.userId)
          : BlacklistMgr.removeMyBalckList(info.userId);
      FriendListMgr().updateFriendInfo(info);
      friendCache[info.userId] = info;
      MessageMgr().emit('UpdateUserInfo', info);
      if (callback != null) callback(resData['data']);
    } else if (resData['code'] == -4) {
      if (failcallback != null) failcallback();
    }
  }

  getFirstProgram() async {
    Map data = {
      "userId": UserData().basicInfo.userId,
      "visitUserId": UserData().basicInfo.userId,
      "type": 1,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['page'] = 1;
    data['rows'] = 1;
    Response res = await HttpUtil().post('station/gain/program', data: data);

    if (res == null) {
      print('请求异常');
      return;
    }
    var resData = res.data;
    if (resData['code'] == 0) {
      UserData().isCanProgram =
          resData['data'] == null || resData['data'][0]['Status'] == 1;
    }
  }

  Future getTranslateState(int sessionId) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
      "chatUserId": sessionId,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res =
        await HttpUtil().post('translate/get/user/status', data: data);

    if (res == null) {
      print('请求异常');
      return null;
    }
    var resData = res.data;
    if (resData['code'] == 0) {
      return resData['data'];
    }

    return null;
  }

  updateTranslateState(int sessionId, bool state) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
      "chatUserId": sessionId,
      "status": state ? 1 : 0
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil().post('translate/set/up/status', data: data);

    if (res == null) {
      print('请求异常');
      return false;
    }
    var resData = res.data;
    if (resData['code'] == 0) {
      return true;
    }

    return false;
  }

  changeLanguage(BuildContext context, lang, callback,
      [showLoading = false]) async {
    var data = {
      "userid": UserData().basicInfo.userId,
      "language": lang,
    };

    data['sign'] = TokenMgr().getSign(data);

    try {
      Response res = await HttpUtil().post('user/setting/language',
          data: data, isShowLoading: showLoading);

      if (res == null) {
        print('请求异常');
        return;
      }
      Map resData = res.data;
      if (resData['code'] == 0) {
        if (callback != null) callback();
        //重新登录
        // SocketUtil().reLogin();
        NetWork().reLogin();
      }
    } catch (e) {}
  }

  userFreeTime(BuildContext context, var viewUserId, int type, callback) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
      "viewUserId": viewUserId,
      'type': type,
    };

    data['sign'] = TokenMgr().getSign(data);
    try {
      Response res = await HttpUtil()
          .post('photos/unlock/permissions', data: data, isShowLoading: true);
      if (res == null) {
        print('请求异常');
        return;
      }
      Map resData = res.data;
      if (resData['code'] == 0) {
        if (callback != null) callback();
      }
    } catch (e) {}
  }

  saveAotuLoginKey(resData, {bool isSaveUserId = true}) async {
    //将用户信息存到本地
    if (resData['data']['aotuLoginKey'] != null) {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      await prefs.setString(
          Constants.AutoLoginKey, resData['data']['aotuLoginKey']);
      if (isSaveUserId) {
        await prefs.setInt(Constants.LocalUserId, UserData().basicInfo.userId);
      }
    }
  }

  ///登录
  changePage(BuildContext context, Map resData) async {
    UserData().basicInfo.userId = resData['data']['userid'];
    UserData().basicInfo.sex = resData['data']['sex'];

    if (resData['data']['mobile'] != null && resData['data']['mobile'] != '') {
      UserData().mobile = int.parse(resData['data']['mobile']);
    }

    if (resData['data']['bindId'] != null) {
      UserData().agentId = resData['data']['bindId'];
    }

    //读取聊天信息
    await ChatDataMgr().initMsg();
    //读取群信息
    await GroupInfoMgr().initLocalGroupList();

    print('~~~~~~~~~~~~~changePage~~~~~~~~~~~~~~~~~~~~~~');

    changeLanguage(context, UserData().language, null);

    getRewardAndRedPacketState();
    //clearReadData(UserData().basicInfo.userId);

    if (resData['data']['sex'] == 0) {
      Navigator.of(context).push(
        new MaterialPageRoute(
          builder: (context) {
            return SelectSex();
          },
        ),
      );
      saveAotuLoginKey(resData, isSaveUserId: false);
      return;
    }
    if (resData['data']['info'] == 0) {
      Navigator.of(context).push(
        new MaterialPageRoute(
          builder: (context) {
            return EditPage(
              isEditPage: false,
            );
          },
        ),
      );
      saveAotuLoginKey(resData, isSaveUserId: false);
      return;
    }
    checkFriends();
    LocalNotificationUtil.instance.startPush();
    //ChatDataMgr().initMsg();
    Navigator.of(context)
        .pushNamedAndRemoveUntil('/main', (route) => route == null);

    MessageMgr().emit('update_system');
    saveAotuLoginKey(resData);
    getFirstProgram();
    initLocation();
  }

  initLocation() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    var latitude = prefs.getDouble(Constants.Latitude);
    var longitude = prefs.getDouble(Constants.Longitude);

    print('存贮在本地的位置: $latitude------$longitude');

    if (latitude != null) UserData().latitude = latitude;
    if (longitude != null) UserData().longitude = longitude;
  }

  setPhote(BuildContext context, id, type, callback) async {
    var data = {
      "userId": UserData().basicInfo.userId,
      "type": type,
      "pId": id,
    };
    data['sign'] = TokenMgr().getSign(data);
    Response res = await HttpUtil()
        .post('photos/setting/burns', data: data, isShowLoading: true);

    if (res == null) {
      print('请求异常');
      return;
    }
    var resData = res.data;
    showToast(resData['msg']);
    if (resData['code'] == 0) {
      if (callback != null) callback();
    }
  }

  clearCacheData() async {
    print('######### 清除缓存key');
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove(Constants.AutoLoginKey);
    prefs.remove(Constants.LocalUserId);
    prefs.remove(Constants.LocalUsrInfo);
  }

  // clearReadData(userId) async {
  //   SharedPreferences prefs = await SharedPreferences.getInstance();

  //   var localUserId = prefs.getInt(Constants.LocalUserId);
  //   if (userId != localUserId) {
  //     prefs.remove(Constants.ApplyCount);
  //     prefs.remove(Constants.EvaluateCount);
  //     prefs.remove(Constants.ParkCount);
  //     prefs.remove(Constants.CastCount);
  //     prefs.remove(Constants.WalletCount);
  //   }
  // }

  void postLoginOut(BuildContext context) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil().post('user/login/out', data: data);
    if (res == null) {
      print('请求异常');
      return;
    }
    Map resData = res.data;
    if (resData['code'] == 0) {
      clearCacheData();

      FriendListMgr().friendList?.clear();

      Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute(
        builder: (context) {
          return IndexPage();
        },
      ), (route) => route == null);
      NetWork().singOut();

      UserData().reset();
    } else {
      showToast(resData['msg']);
    }
  }

  buyGoods(money, goodsId, detailtype, changeuserId, context, callback) async {
    if (Provider.of<MoneyChangeProvider>(context).money < money) {
      showToast(I18n.of(context).balance_insufficien);
      return;
    }

    var data = {
      "userId": UserData().basicInfo.userId,
      "type": 1,
      "detailtype": detailtype,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['value'] = money;
    data['changeuserId'] = changeuserId;
    data['membergoodsId'] = goodsId;

    Response res = await HttpUtil()
        .post('wealth/user/add', data: data, isShowLoading: true);
    if (res == null) {
      print('请求异常');
      return;
    }
    Map resData = res.data;

    showToast(resData['msg']);
    if (resData['code'] == 0) {
      Provider.of<MoneyChangeProvider>(context, listen: false).subMoney(money);
      if (callback != null) callback();
    }
  }

  buyPictures(money, changeuserId, context, callback) async {
    if (Provider.of<MoneyChangeProvider>(context).money < money) {
      showToast(I18n.of(context).balance_insufficien);
      return;
    }

    var data = {
      "userId": UserData().basicInfo.userId,
      "viewUserId": changeuserId,
      "price": money,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil()
        .post('photos/user/unlock', data: data, isShowLoading: true);

    if (res == null) {
      print('请求异常');
      return;
    }
    Map resData = res.data;
    showToast(resData['msg']);
    if (resData['code'] == 0) {
      Provider.of<MoneyChangeProvider>(context, listen: false).subMoney(money);
      if (callback != null) callback();
    }
  }

  buyVIP(int money, int gid, int type, BuildContext context, callback) async {
    if (Provider.of<MoneyChangeProvider>(context).money < money) {
      showToast(I18n.of(context).balance_insufficien);
      return;
    }

    Map data = {
      "userId": UserData().basicInfo.userId,
      "gid": gid,
      "type": type,
      "price": money,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil()
        .post('goods/user/purchase', data: data, isShowLoading: true);
    if (res == null) {
      print('请求异常');
      return;
    }
    Map resData = res.data;
    showToast(resData['msg']);
    if (resData['code'] == 0) {
      Provider.of<MoneyChangeProvider>(context, listen: false).subMoney(money);
      if (callback != null) callback();
    }
  }

  buyChatAccount(money, changeuserId, context, callback) async {
    if (Provider.of<MoneyChangeProvider>(context).money < money) {
      showToast(I18n.of(context).balance_insufficien);
      return;
    }

    var data = {
      "userId": UserData().basicInfo.userId,
      "unlockUserId": changeuserId,
      "price": money,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil()
        .post('photos/pay/unlock/chat', data: data, isShowLoading: true);

    if (res == null) {
      print('请求异常');
      return;
    }
    Map resData = res.data;
    showToast(resData['msg']);
    if (resData['code'] == 0) {
      Provider.of<MoneyChangeProvider>(context, listen: false).subMoney(money);
      if (callback != null) callback();
    }
  }

  void getMoneyInfo(BuildContext context, callback) async {
    if (Platform.isIOS) {
      await MoneyPageState.initPayConf(context);
    }
    Map data = {
      "userid": UserData().basicInfo.userId,
      "moneytype":
          UserData().language == LanguageType.SimplifiedChinese ? 0 : 1,
      "mobiletype": Platform.isIOS ? 0 : 1,
    };
    if (Platform.isIOS) {
      data['moneytype'] = 1;
    }
    print('moneytype ${data['moneytype']}');
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil()
        .post('goods/info/list', data: data, isShowLoading: true);
    if (res == null) {
      print('请求异常');
      return;
    }

    Map resData = res.data;
    if (resData['code'] == 0) {
      if (callback != null) callback(resData['data']);
    }
  }

  void getWealth(BuildContext context, callback) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil().post('wealth/user/info', data: data);
    if (res == null) {
      print('请求异常');
      return;
    }
    Map resData = res.data;
    print(resData);
    if (resData['code'] == 0 && resData['data'] != null) {
      UserData().basicInfo.isMember = resData['data']['IsMember'] ?? 0;
      UserData().incomeMoney = resData['data']['IncomeCoin'];
      UserData().frozenMoney = resData['data']['FrozenCoin'];
      UserData().memberEndTime = resData['data']['MemberEnd'];
      if (callback != null) callback(resData['data']);
    }
  }

  //获取红包与打赏开关状态
  getRewardAndRedPacketState() async {
    var myId = UserData().basicInfo.userId;
    Map data = {
      "userId": myId,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil().post('system/switch', data: data);
    if (res == null) {
      print('请求异常');
      return;
    }
    Map resData = res.data;
    print('### system/switch' + resData.toString());
    if (resData['code'] == 0) {
      var config = resData['data'];

      if (config != null) {
        UserData().redPacketSW = config['redPacket'];
        UserData().giftSwitch = config['reward'];
        UserData().bannerZF = config['iapPay'];
        UserData().sign = config['sign'];
        UserData().groupQRCode = config['groupQRCode'];
        UserData().addFdDistanceSwitch = config['distance'] ?? 0;

        UserData().stationOpenSwitch = config['station'] == 1;
        UserData().myProgramOpenSwitch = config['myProgram'] == 1;
        UserData().nearbyOpenSwitch = config['nearby'] == 1;

//        print('### config: start');
//        print('### config: iapPay:${config['iapPay']}');
      }
    }
  }

  ///检查是否有缓存的内购单-有的话向服务器发送请求重新创建订单
  void checkReceiptCache() async {
    String str = await SPUtils.get(Constants.IOS_IAP_Receipt);
    if (str != null && str.isNotEmpty) {
      print('### 有缓存单');
      List<String> split = str.split("@");
      createOrder(split[0], split[1], split[2]);
    } else {
      print('### 没有缓存单');
    }
  }

  ///ios内购-创建订单
  void createOrder(String currentGoodsId, String receipt, String purchaseToken,
      {BuildContext context}) async {
//     String base84str = base64Encode(utf8.encode(receipt));

    var data = {
      "userid": UserData().basicInfo.userId,
      "moneytype": 1,
      'gid': currentGoodsId,
      "payway": 1,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['receipt'] = receipt;
    data['isenable'] = Constants.isSandbox ? 0 : 1;

    Response res = await HttpUtil().post('order/add/goods', data: data);
    print('#### 创建订单-返回');
    if (res == null) {
      print('请求异常');
      return;
    }
    Map resData = res.data;
    print('#### 创建订单-返回:' + resData.toString());
    if (resData['code'] == 0) {
//      String OrderNo = resData['data']['OrderNo'];
      Future.delayed(Duration(seconds: 3), () {
        MessageMgr().emit('refresh_money');
      });

      if (context == null) {
        await FlutterInappPurchase.instance.initConnection;
      }

      FlutterInappPurchase.instance.finishTransaction(purchaseToken);
      SPUtils.remove(Constants.IOS_IAP_Receipt);
    } else {
      ///创建订单失败-
      await SPUtils.saveString(Constants.IOS_IAP_Receipt,
          currentGoodsId + '@' + receipt + '@' + purchaseToken);
    }
    if (context != null) {
      Navigator.of(context).pop();
    }
  }

  ///登陆
  void login(
      String _phoneNumber, String _passWorld, BuildContext context) async {
    var data = {
      "mobile": _phoneNumber,
      "text": _passWorld,
      "type": 0,
      "language": UserData().language,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil()
        .post('user/mobile/login', data: data, isShowLoading: true);

    if (res == null) {
      print('请求异常');
      return;
    }
    var resData = res.data;
    if (resData['code'] == 0 && resData['data'] != null) {
      HttpUtil().changePage(context, resData);
    } else {
      showToast(resData['msg']);
    }
  }

  ///获取推送设置
  getSettingInfo() async {
    Map data = {
      "userId": UserData().basicInfo.userId,
      "sex": UserData().basicInfo.sex,
    };
    data['sign'] = TokenMgr().getSign(data);
    try {
      Response res = await HttpUtil().post('message/push/message', data: data);

      if (res == null) {
        print('请求异常');
        return;
      }

      Map resData = res.data;

      bool isMan = UserData().isMan();

      ///女号 {data: {PrivacyChat: 1, NewBroadcast: 1, ApplyCheck: 1, CheckAccount: 1, CheckPhoto: 1, SendAccount: 1}, code: 0, msg: 成功}
      ///男号 {data: {PrivacyChat: 1, NewBroadcast: 1, AcceptCheck: 1, ApplySuccess: 1}, code: 0, msg: 成功}
      print('###settingdata res.data ${res.data}');
      if (resData['code'] == 0) {
        UserData().privatyMsgPushSwitch = resData['data']['PrivacyChat'] == 1;
        UserData().newDateSwitch = resData['data']['NewBroadcast'] == 1;

        if (isMan) {
          UserData().acceptCheckSwitch = resData['data']['AcceptCheck'] == 1;
          UserData().codeSucessSwitch = resData['data']['ApplySuccess'] == 1;
        } else {
          UserData().applyCheckSwitch = resData['data']['ApplyCheck'] == 1;
          UserData().checkPhotoSwitch = resData['data']['CheckPhoto'] == 1;
        }
      }
    } catch (e) {}
    MessageMgr().emit(MessageMgr.REFRESH_PUSH_PERMISSION);
  }

  ///版本控制
  appVersionUpdate(Function callBack) async {
    Map data = {
      "ditch": Constants.isStoreVersion ? 0 : 1,
      "type": Platform.isAndroid ? 0 : 1,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['language'] = UserData().language;
    try {
      Response res = await HttpUtil().post('system/version/info', data: data);
      Map resData = res.data;
      print('###appVersionUpdate res.data ${res.data}');
      if (resData['code'] == 0) {
        bool needNotice = resData['data']['Notice'] == 1;

        ///是否通知更新
        bool forceUpdate = resData['data']['IsStronger'] == 1;

        ///是否通知强更
        String version = resData['data']['VersionNo'];
        String describe = resData['data']['Describe'];
        String downloadUrl = resData['data']['DownloadUrl'];
        String appId = resData['data']['AppId'];
        callBack(
            needNotice, forceUpdate, version, describe, downloadUrl, appId);
      }
    } catch (e) {}
  }

  downloadApk(
    BuildContext context,
    String filePath,
    String downloadUrl,
    Function downloadCallback,
  ) async {
    final file = new File(filePath);
    bool isExist = await file.exists();
    if (isExist) {
      print('### 文件存在 : ${file.path}');
      file.delete();
    }
//    else {
//
//      print('### 开始下载 $downloadUrl');
//      dio.download(downloadUrl, filePath, onReceiveProgress: downloadCallback);
//    }

//    downloadUrl ='oemarket.com/app0/30/30970/apk/2085562.apk?channel_id=426&tid=d73j9ihlkucuxfqpgnxgjeif';
    dio.download(downloadUrl, filePath, onReceiveProgress: downloadCallback);
  }

  ///获取用户每日签到信息
  Future<DailyBonusBean> getDailyBonus() async {
    Map data = {
      "userId": UserData().basicInfo.userId,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['userId'] = UserData().basicInfo.userId;
    try {
      Response res = await HttpUtil().post('sign/in/user/info', data: data);
      Map resData = res.data;
      print('###getDailyBonus res.data ${res.data}');
      if (resData['code'] == 0) {
        return DailyBonusBean.fromMap(resData['data']);
      }
      return null;
    } catch (e) {
      return null;
    }
  }

  ///点击签到
  Future<bool> signInBounus(int score) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
      "score": score,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['userId'] = UserData().basicInfo.userId;
    data['score'] = score;
    try {
      Response res = await HttpUtil().post('sign/in/user', data: data);
      Map resData = res.data;
      print('###signInBounus res.data ${res.data}');
      if (resData['code'] == 0) {
        return true;
//        bool needNotice = resData['data']['Notice']==1; ///是否通知更新
//        return DailyBonusBean.fromMap(resData['data']);
      } else {
        showToast(resData['msg']);
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  /// 用户签到积分兑换商品
  Future<bool> signInExchange(GoodsBean goodsBean) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
      "id": goodsBean.id,
      "score": goodsBean.s,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['userId'] = UserData().basicInfo.userId;
    data['score'] = goodsBean.s;
    data['id'] = goodsBean.id;
    try {
      Response res =
          await HttpUtil().post('sign/in/score/exchange', data: data);
      Map resData = res.data;
      print('###signInExchange res.data ${res.data}');
      if (resData['code'] == 0) {
        return true;
      } else {
        showToast(resData['msg']);
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  addFriends(
      BuildContext context, int friendId, String content, callback) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
      "friendsUserId": friendId
    };
    data['sign'] = TokenMgr().getSign(data);
    data['content'] = content;
    Response res = await HttpUtil().post('friendship/add/friends', data: data);

    Map resData = res.data;
    print(resData);
    if (resData['code'] == 0) {
      showToast(resData['msg']);
      if (callback != null) callback();
    }
  }

  //付费人工翻译
  getPersonalTranslate(MsgModel msgModel) async {
    Map data = {
      "suserid": msgModel.from,
      "chatmsgid": msgModel.time,
      "slanguage": 1,
      "tlanguage": UserData().language,
      "chattype": msgModel.msgType,
      "chatchanneltype": msgModel.channelType,
      "targetid": msgModel.sessionId
    };
    data['sign'] = TokenMgr().getSign(data);

    if (msgModel.msgType == 0) {
      data['content'] = base64Encode(msgModel.msgContent);
    } else {
      if (msgModel.localFile == null) {
        showToast('请稍后再试');
        return;
      }
      data['content'] =
          base64Encode(File(msgModel.localFile).readAsBytesSync());
    }

    data["tuserids"] = [UserData().basicInfo.userId];
    data['duration'] =
        msgModel.extraInfo != null ? msgModel.extraInfo ~/ 1000 : 0;
    data['ispay'] = true;

    if (msgModel.msgType == ChatType.TextChatType.value) {
      int length = utf8.decode(msgModel.msgContent).length;
      data['money'] = length ~/ 50 + 1; //每50个字耗费1H币

      print('字数 $length  价格 ${length % 50 + 1}');
    } else if (msgModel.msgType == ChatType.ShortVoiceChatType.value) {
      //没20秒扣除1Hb
      data['money'] =
          msgModel.extraInfo != null ? msgModel.extraInfo ~/ 20000 + 1 : 0;
    }

    if (msgModel.translateContent != null &&
        msgModel.translateContent.length > 0) {
      data['mcontent'] = base64Encode(msgModel.enTranslateContent);
    }

    Response res =
        await HttpUtil().post('service/paid/translation', data: data);

    if (res == null) {
      return false;
    }
    Map resData = res.data;
    print('付费翻译请求$resData');
    if (resData['code'] == 0) {
      print('扣除 H 币 ${data['money']}');

      return true;
    }

    print(resData['msg']);
    showToast(resData['msg']);
    return false;
  }

  //用户评价人工翻译,差评
  Future<bool> rateTranslateResult(MsgModel msg, Function callback) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
      "chatUserId": msg.from,
      "chatMsgId": msg.time,
      "score": 1
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil().post('translate/user/score', data: data);
    if (res == null) {
      return false;
    }
    var resData = res.data;
    if (resData['code'] == 0) {
      msg.transTag = 10; //已评价过

      if (callback != null) {
        callback();
      }

      SqlUtil().updateUserTranslateRate(msg.sessionId, msg.time, msg.transTag);
      return true;
    }

    return false;
  }

  //根据经纬度获取用户国家城市
  getAddress(double lon, double lat) async {
    Map data = {
      "lon": lon.toString(),
      "lat": lat.toString(),
    };
    data['sign'] = TokenMgr().getSign(data);
    data['language'] = UserData().language;

    Response res = await HttpUtil().post('user/get/address', data: data);
    if (res == null) return;
    Map resData = res.data;
    if (resData['code'] == 0 && resData['data'] != null) {
      print(resData['data']);
      List address = resData['data'].split(',');
      if (address.length != 2) return;
      String country = address[0];
      String city = address[1];
      UserData().isInChina = false;
      if (country == '越南') {
        UserData().currentCity = 'VietNam-';
        List citys = constData[3]['city'][0]['List'];
        for (int i = 0; i < citys.length; i++) {
          if (citys[i]['Value'] == city) {
            UserData().currentCity += citys[i]['Key'];
            break;
          }
        }
      } else if (country == '中国') {
        UserData().isInChina = true;
        UserData().currentCity = 'China-ChinaRepeat';
      } else {
        UserData().currentCity = 'VietNam-HoChiMinhCIty';
      }

      if (UserData().currentCity != UserData().basicInfo.meetPlace) {
        UserData().basicInfo.meetPlace = UserData().currentCity;
        changeCurrentCity(lon, lat, () {});
      }

      MessageMgr().emit('change_currentcity');
    }
  }

  //根据经纬度获取用户国家城市
  changeCurrentCity(double lon, double lat, callback) async {
    if (UserData().basicInfo.userId == null) return;
    Map data = {
      "userId": UserData().basicInfo.userId,
      "lon": lon.toString(),
      "lat": lat.toString(),
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil().post('user/update/meetPlace', data: data);
    if (res == null) return;
    Map resData = res.data;
    print(resData);
    if (resData['code'] == 0) {
      callback();
    }
  }

  //通过手机号查询用户
  searchNewFrindsByPhone(String phone, callback) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
      "value": phone,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil()
        .post('/friendship/search/userPhone', data: data, isShowLoading: true);
    if (res == null) return;
    Map resData = res.data;
    print(resData);
    if (resData['code'] == 0) {
      callback(resData['data']['UserId']);
    }
  }

//拉黑用户
  blackUser(int userId, callback) async {
    Map data = {
      "userid": UserData().basicInfo.userId,
      "type": 1,
      "followUserId": userId,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res =
        await HttpUtil().post('userfollow/follow/insert', data: data);
    Map resData = res.data;
    showToast(resData['msg']);
    if (resData['code'] == 0) {
      BlacklistMgr.addMyBlackList(userId);
      callback();
    }
  }

  //取消拉黑用户
  cancleBlackUser(int userId, callback) async {
    Map data = {
      "userid": UserData().basicInfo.userId,
      "type": 1,
      "followUserId": userId,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil()
        .post('userfollow/follow/cancel', data: data, isShowLoading: true);
    Map resData = res.data;
    showToast(resData['msg']);
    if (resData['code'] == 0) {
      BlacklistMgr.removeMyBalckList(userId);
      callback();
    }
  }

  //收藏用户
  setLove(int userId, callback) async {
    Map data = {
      "userid": UserData().basicInfo.userId,
      "type": 0,
      "followUserId": userId,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil()
        .post('userfollow/follow/insert', data: data, isShowLoading: true);
    Map resData = res.data;
    if (resData['code'] == 0) {
      showToast(resData['msg']);
      callback();
    }
  }

  //取消收藏用户
  cancleLove(int userId, callback) async {
    Map data = {
      "userid": UserData().basicInfo.userId,
      "type": 0,
      "followUserId": userId,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil()
        .post('userfollow/follow/cancel', data: data, isShowLoading: true);
    Map resData = res.data;
    if (resData['code'] == 0) {
      showToast(resData['msg']);
      callback();
    }
  }

  //向企业服务助手提交信息
  Future<bool> commitInfoToCompany(MsgModel msgModel) async {
    Map data = {
      "userid": msgModel.from,
      "msgType": msgModel.msgType,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['msgContent'] = base64Encode(msgModel.msgContent);

    msgModel.state = MsgState.Sending;

    print('commitInfoToCompany  参数 $data');
    Response res = await HttpUtil().post('feedback/user/insert', data: data);

    if (res == null) {
      msgModel.state = MsgState.SendingFailed;
      ChatDataMgr().updateMsgState(msgModel.sessionId, msgModel.time,
          msgModel.channelType, msgModel.state);
      return false;
    }
    Map resData = res.data;
    print('commitInfoToCompany $resData');
    if (resData['code'] == 0) {
      msgModel.state = MsgState.SendingSuccess;
      ChatDataMgr().updateMsgState(msgModel.sessionId, msgModel.time,
          msgModel.channelType, msgModel.state);
      return true;
    }

    showToast(resData['msg']);
    return false;
  }

  //焚阅照片恢复
  resetPhoto(callback) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil()
        .post('user/recover/photos', data: data, isShowLoading: true);
    Map resData = res.data;
    if (resData['code'] == 0) {
      showToast(resData['msg']);
      callback();
    }
  }

  //获取好友校验值
  checkFriends() async {
    Map data = {
      "userId": UserData().basicInfo.userId,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil()
        .post('friendship/check/userFriends', data: data);
    Map resData = res.data;
    if (resData['code'] == 0) {
      FriendListMgr().checkFromServer(resData['data']);
    }
  }



  //保存设备名称和编码
 saveMobileInfo() async {
String mobileType = '';
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    if (Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      mobileType = androidInfo.model;
      print('Running on ${androidInfo.model}'); // e.g. "Moto G (4)"
    } else if (Platform.isIOS) {
      IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
      mobileType = iosInfo.utsname.machine;
    }

    Map data = {
      "userId": UserData().basicInfo.userId,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['model'] = mobileType;
    data['coding'] = UserData().deviceLanguageCode;

    Response res =
        await HttpUtil().post('user/save/modelAndCoding', data: data);

    Map resData = res.data;
    print(resData);
  }

  ///实时帮-翻译管家评价
    evaluationTransalteHK(String orderNo,String value,bool isGood,Function callback) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
      "orderNo": orderNo,
      "gradeStatus":isGood?1:2
    };
    data['sign'] = TokenMgr().getSign(data);
    data['value'] = value;
    Response res = await HttpUtil().post('steward/evaluation', data: data);
    callback();
    if (res == null) {
      print('请求异常');
      return;
    }
    var resData = res.data;
    if (resData['code'] == 0) {
      showToast('评价成功');
    }else{
      showToast(I18n.of(Constants.getCurrentContext()).net_error);
    }
  }


  ///实时帮-用户测距
  userRanging(int distance,String origin,String ending) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
      "distance": distance,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['origin'] = origin;
    data['ending'] = ending;
    Response res = await HttpUtil().post('steward/userRanging', data: data);

    if (res == null) {
      print('请求异常');
      return;
    }
    var resData = res.data;
    if (resData['code'] == 0) {
      print('实时帮-用户测距提交 成功');
    }else{
      print('实时帮-用户测距提交 失败');
    }
  }


  ///实时帮-翻译人员上线、下线
  translateHKloginRecord(bool isLogin,Function callback) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
      "type": isLogin?1:2,
    };
    data['sign'] = TokenMgr().getSign(data);
    Response res = await HttpUtil().post('steward/loginRecord', data: data);

    if (res == null) {
      print('请求异常');
      return;
    }
    var resData = res.data;
    if (resData['code'] == 0) {
      callback();
      print('翻译人员上线、下线 成功');
    }else{
      print('翻译人员上线、下线 失败 ${resData['msg']}');
    }
  }
}
