Hibok
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1298 lines
39 KiB

  1. import 'dart:convert';
  2. import 'package:chat/data/WebData.dart';
  3. import 'package:chat/data/chat_data_mgr.dart';
  4. import 'package:chat/data/constants.dart';
  5. import 'package:chat/data/group_data_mgr.dart';
  6. import 'package:chat/generated/i18n.dart';
  7. import 'package:chat/home/EditData.dart';
  8. import 'package:chat/home/IndexPage.dart';
  9. import 'package:chat/home/MoneyPage.dart';
  10. import 'package:chat/home/SelectSexPage.dart';
  11. import 'package:chat/models/ChatMsg.dart';
  12. import 'package:chat/models/UserInfo.dart';
  13. import 'package:chat/models/daily_bonus.dart';
  14. import 'package:chat/models/money_change.dart';
  15. import 'package:chat/proto/all.pbserver.dart';
  16. import 'package:chat/utils/LoadingDialog.dart';
  17. import 'package:chat/utils/MessageMgr.dart';
  18. import 'package:chat/utils/NetUtil.dart';
  19. import 'package:chat/utils/friend_list_mgr.dart';
  20. import 'package:chat/utils/image_util.dart';
  21. import 'package:chat/utils/local_notification_util.dart';
  22. import 'package:chat/utils/sp_utils.dart';
  23. import 'package:chat/utils/sql_util.dart';
  24. import 'package:chat/utils/user_info_table.dart';
  25. import 'dart:core';
  26. import 'package:dio/dio.dart';
  27. import 'package:flutter/material.dart';
  28. import 'package:flutter_inapp_purchase/flutter_inapp_purchase.dart';
  29. import 'package:oktoast/oktoast.dart';
  30. import 'package:provider/provider.dart';
  31. import 'package:shared_preferences/shared_preferences.dart';
  32. import 'dart:io';
  33. import '../data/UserData.dart';
  34. import '../utils/TokenMgr.dart';
  35. import 'package:http_parser/http_parser.dart';
  36. class HttpUtil {
  37. static HttpUtil _instance;
  38. Dio dio;
  39. BaseOptions options;
  40. //static const String BaseUrl = 'http://192.168.0.223:7001/';
  41. //static const String BaseUrl = 'http://192.168.0.207:9080/';
  42. static const String BaseUrl = 'http://120.79.107.63:9080/';
  43. //static const String BaseUrl = 'http://192.168.0.177:9016/';
  44. //static const String BaseUrl = 'https://datasm.chengyouhd.com/';
  45. static HttpUtil _getInstance() {
  46. if (_instance == null) {
  47. _instance = HttpUtil._();
  48. }
  49. return _instance;
  50. }
  51. factory HttpUtil() => _getInstance();
  52. Map friendCache = {};
  53. HttpUtil._() {
  54. options = BaseOptions(
  55. baseUrl: BaseUrl,
  56. headers: {},
  57. );
  58. dio = new Dio(options);
  59. // (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
  60. // (HttpClient client) {
  61. // client.findProxy = (uri) {
  62. // //proxy all request to localhost:8888
  63. // return "PROXY 192.168.0.181:8888";
  64. // };
  65. // client.badCertificateCallback =
  66. // (X509Certificate cert, String host, int port) => true;
  67. // };
  68. dio.interceptors
  69. .add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
  70. // Do something before request is sent
  71. return options; //continue
  72. // If you want to resolve the request with some custom data,
  73. // you can return a `Response` object or return `dio.resolve(data)`.
  74. // If you want to reject the request with a error message,
  75. // you can return a `DioError` object or return `dio.reject(errMsg)`
  76. }, onResponse: (Response response) async {
  77. // Do something with response data
  78. return response; // continue
  79. }, onError: (DioError e) async {
  80. // Do something with response error
  81. showToast(I18n.of(LoadingManage.context).net_error);
  82. return e; //continue
  83. }));
  84. }
  85. Future get(url, {data, options, cancelToken}) async {
  86. print('get请求启动! url:$url ,body: $data');
  87. Response response;
  88. try {
  89. response = await dio.get(
  90. url,
  91. queryParameters: data,
  92. cancelToken: cancelToken,
  93. );
  94. print('get请求成功!$url');
  95. } on DioError catch (e) {
  96. if (CancelToken.isCancel(e)) {
  97. print('get请求取消! ' + e.message);
  98. }
  99. print('get请求发生错误:$e');
  100. }
  101. return response;
  102. }
  103. getFriendList(callback) async {
  104. Map data = {
  105. "userId": UserData().basicInfo.userId,
  106. };
  107. data['sign'] = TokenMgr().getSign(data);
  108. Response res = await HttpUtil().post('friendship/friends/list', data: data);
  109. Map resData = res.data;
  110. if (resData['code'] == 0) {
  111. if (callback != null) callback(resData['data']);
  112. }
  113. }
  114. Future getDataWX(url, {data, options, cancelToken}) async {
  115. print('get请求启动! url:$url ,body: $data');
  116. Response response;
  117. BaseOptions options = BaseOptions(
  118. headers: {},
  119. );
  120. Dio dio = new Dio(options);
  121. try {
  122. response = await dio.get(
  123. url,
  124. queryParameters: data,
  125. cancelToken: cancelToken,
  126. );
  127. print('get请求成功!$url');
  128. } on DioError catch (e) {
  129. if (CancelToken.isCancel(e)) {
  130. print('get请求取消! ' + e.message);
  131. }
  132. print('get请求发生错误:$e');
  133. }
  134. return response;
  135. }
  136. Future post(url,
  137. {data,
  138. options,
  139. cancelToken,
  140. bool isShowLoading = false,
  141. failback}) async {
  142. print('post请求启动! url:$url ,body: $data');
  143. Response response;
  144. if (isShowLoading) LoadingManage().showLoading();
  145. try {
  146. response = await dio.post(
  147. url,
  148. data: data,
  149. cancelToken: cancelToken,
  150. );
  151. print('$url post请求成功! $BaseUrl');
  152. if (isShowLoading) LoadingManage().closeLoading();
  153. } on DioError catch (e) {
  154. if (CancelToken.isCancel(e)) {
  155. print('post请求取消! ' + e.message);
  156. }
  157. print('post请求发生错误:$e');
  158. if (isShowLoading) LoadingManage().closeLoading();
  159. showToast(I18n.of(LoadingManage.context).server_error_tips);
  160. if (failback != null) failback();
  161. }
  162. return response;
  163. }
  164. // 上传文件
  165. Future uploadFile(File imgfile, data, url, contentType,
  166. {isShowLoading = false}) async {
  167. FormData formData = new FormData.fromMap({
  168. "type": data["type"],
  169. "userId": data["userId"],
  170. "sex": data['sex'] == null ? 0 : data['sex'],
  171. "isBurn": data['isBurn'] == null ? 0 : data['isBurn'],
  172. "sign": data['sign'],
  173. "file": await getMultipartFile(imgfile, contentType)
  174. });
  175. print('post请求启动! url:$url');
  176. if (isShowLoading) LoadingManage().showLoading();
  177. Response response;
  178. try {
  179. response = await dio.post(
  180. url,
  181. data: formData,
  182. );
  183. print('post请求成功!response.data:${response.data}');
  184. if (isShowLoading) LoadingManage().closeLoading();
  185. } on DioError catch (e) {
  186. if (CancelToken.isCancel(e)) {
  187. print('post请求取消! ' + e.message);
  188. }
  189. print('post请求发生错误:$e');
  190. if (isShowLoading) LoadingManage().closeLoading();
  191. }
  192. return response;
  193. }
  194. Future<MultipartFile> getMultipartFile(
  195. File imgfile, String contentType) async {
  196. //压缩图片文件
  197. var size = await imgfile.length();
  198. String path = imgfile.path;
  199. var fileBytes;
  200. if (contentType == 'image' && size > 10240) {
  201. fileBytes = await WidgetUtil.getCompressImg(path);
  202. } else {
  203. fileBytes = imgfile.readAsBytesSync();
  204. }
  205. var name = path.substring(path.lastIndexOf("/") + 1, path.length);
  206. var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
  207. return new MultipartFile.fromBytes(fileBytes,
  208. filename: name, contentType: MediaType(contentType, suffix));
  209. }
  210. // 上传多个图片
  211. Future uploadFiles(List<File> imgfileList, data, url, contentType,
  212. {isShowLoading = false}) async {
  213. var imgList = [];
  214. for (int i = 0; i < imgfileList.length; i++) {
  215. imgList.add(await getMultipartFile(imgfileList[i], contentType));
  216. }
  217. FormData formData = new FormData.fromMap({
  218. "type": data["type"],
  219. "userId": data["userId"],
  220. "sex": data['sex'] == null ? 0 : data['sex'],
  221. "isBurn": data['isBurn'] == null ? 0 : data['isBurn'],
  222. "sign": data['sign'],
  223. "file": imgList
  224. });
  225. print('post请求启动! url:$url');
  226. if (isShowLoading) LoadingManage().showLoading();
  227. Response response;
  228. try {
  229. response = await dio.post(
  230. url,
  231. data: formData,
  232. );
  233. print('post请求成功!response.data:${response.data}');
  234. if (isShowLoading) LoadingManage().closeLoading();
  235. } on DioError catch (e) {
  236. if (CancelToken.isCancel(e)) {
  237. print('post请求取消! ' + e.message);
  238. }
  239. print('post请求发生错误:$e');
  240. if (isShowLoading) LoadingManage().closeLoading();
  241. }
  242. return response;
  243. }
  244. Future getUserInfoFromServer(int friendId) async {
  245. Map<String, dynamic> data = {
  246. "visitUserId": UserData().basicInfo.userId,
  247. "userId": friendId,
  248. "language": UserData().language,
  249. };
  250. data['sign'] = TokenMgr().getSign(data);
  251. data['lat'] = UserData().latitude;
  252. data['lng'] = UserData().longitude;
  253. print('请求用户信息 $data}');
  254. print('从服务器获取用户信息$friendId');
  255. Response res = await HttpUtil().post('user/info/list', data: data);
  256. if (res == null) {
  257. return null;
  258. }
  259. Map resData = res.data;
  260. print('用户信息resData $resData');
  261. if (resData['code'] == 0) {
  262. var info = UserInfo.fromJson(resData['data']);
  263. friendCache[friendId] = info;
  264. FriendListMgr().updateFriendInfo(info);
  265. UserInfoTable().insertUser(info);
  266. MessageMgr().emit('UpdateUserInfo', info);
  267. return info;
  268. } else {
  269. return null;
  270. }
  271. }
  272. Future getFriendInfo(int friendId, [bool isUpdate = false]) async {
  273. print('开始获取用户信息$friendId');
  274. if (friendId == null) {
  275. print('用户Id为空,无法获取信息');
  276. return null;
  277. }
  278. if (friendCache[friendId] != null) {
  279. print('存在用户信息$friendId 缓存');
  280. if (isUpdate) {
  281. //如果需要更新,那么先读取旧数据,然后后台更新
  282. getUserInfoFromServer(friendId);
  283. }
  284. return friendCache[friendId];
  285. }
  286. var info = await SqlUtil.userInfoTable.getUserInfoFromLocal(friendId);
  287. print('从本地数据库读取用户$friendId 信息');
  288. if (info != null) {
  289. if (isUpdate) {
  290. //如果需要更新,那么先读取旧数据,然后后台更新
  291. getUserInfoFromServer(friendId);
  292. }
  293. friendCache[friendId] = info;
  294. return info;
  295. }
  296. return await getUserInfoFromServer(friendId);
  297. }
  298. getUserInfo(visitedUserId, [callback, failcallback, errorcallback]) async {
  299. var data = {
  300. "visitUserId": UserData().basicInfo.userId,
  301. "userId": visitedUserId,
  302. "language": UserData().language,
  303. };
  304. data['sign'] = TokenMgr().getSign(data);
  305. data['lat'] = UserData().latitude;
  306. data['lng'] = UserData().longitude;
  307. Response res = await HttpUtil()
  308. .post('user/info/list', data: data, failback: errorcallback);
  309. if (res == null) {
  310. print('请求异常');
  311. return;
  312. }
  313. Map resData = res.data;
  314. if (resData['code'] == 0) {
  315. var info = UserInfo.fromJson(resData['data']);
  316. FriendListMgr().updateFriendInfo(info);
  317. friendCache[info.userId] = info;
  318. MessageMgr().emit('UpdateUserInfo', info);
  319. if (callback != null) callback(resData['data']);
  320. } else if (resData['code'] == -4) {
  321. if (failcallback != null) failcallback();
  322. }
  323. }
  324. getFirstProgram() async {
  325. Map data = {
  326. "userId": UserData().basicInfo.userId,
  327. "visitUserId": UserData().basicInfo.userId,
  328. "type": 1,
  329. };
  330. data['sign'] = TokenMgr().getSign(data);
  331. data['page'] = 1;
  332. data['rows'] = 1;
  333. Response res = await HttpUtil().post('station/gain/program', data: data);
  334. if (res == null) {
  335. print('请求异常');
  336. return;
  337. }
  338. var resData = res.data;
  339. if (resData['code'] == 0) {
  340. UserData().isCanProgram =
  341. resData['data'] == null || resData['data'][0]['Status'] == 1;
  342. }
  343. }
  344. Future getTranslateState(int sessionId) async {
  345. Map data = {
  346. "userId": UserData().basicInfo.userId,
  347. "chatUserId": sessionId,
  348. };
  349. data['sign'] = TokenMgr().getSign(data);
  350. Response res =
  351. await HttpUtil().post('translate/get/user/status', data: data);
  352. if (res == null) {
  353. print('请求异常');
  354. return null;
  355. }
  356. var resData = res.data;
  357. if (resData['code'] == 0) {
  358. return resData['data'];
  359. }
  360. return null;
  361. }
  362. updateTranslateState(int sessionId, bool state) async {
  363. Map data = {
  364. "userId": UserData().basicInfo.userId,
  365. "chatUserId": sessionId,
  366. "status": state ? 1 : 0
  367. };
  368. data['sign'] = TokenMgr().getSign(data);
  369. Response res = await HttpUtil().post('translate/set/up/status', data: data);
  370. if (res == null) {
  371. print('请求异常');
  372. return false;
  373. }
  374. var resData = res.data;
  375. if (resData['code'] == 0) {
  376. return true;
  377. }
  378. return false;
  379. }
  380. changeLanguage(BuildContext context, lang, callback,
  381. [showLoading = false]) async {
  382. var data = {
  383. "userid": UserData().basicInfo.userId,
  384. "language": lang,
  385. };
  386. data['sign'] = TokenMgr().getSign(data);
  387. try {
  388. Response res = await HttpUtil().post('user/setting/language',
  389. data: data, isShowLoading: showLoading);
  390. if (res == null) {
  391. print('请求异常');
  392. return;
  393. }
  394. Map resData = res.data;
  395. if (resData['code'] == 0) {
  396. if (callback != null) callback();
  397. //重新登录
  398. // SocketUtil().reLogin();
  399. NetWork().reLogin();
  400. }
  401. } catch (e) {}
  402. }
  403. userFreeTime(BuildContext context, var viewUserId, int type, callback) async {
  404. Map data = {
  405. "userId": UserData().basicInfo.userId,
  406. "viewUserId": viewUserId,
  407. 'type': type,
  408. };
  409. data['sign'] = TokenMgr().getSign(data);
  410. try {
  411. Response res = await HttpUtil()
  412. .post('photos/unlock/permissions', data: data, isShowLoading: true);
  413. if (res == null) {
  414. print('请求异常');
  415. return;
  416. }
  417. Map resData = res.data;
  418. if (resData['code'] == 0) {
  419. if (callback != null) callback();
  420. }
  421. } catch (e) {}
  422. }
  423. saveAotuLoginKey(resData, {bool isSaveUserId = true}) async {
  424. //将用户信息存到本地
  425. if (resData['data']['aotuLoginKey'] != null) {
  426. SharedPreferences prefs = await SharedPreferences.getInstance();
  427. await prefs.setString(
  428. Constants.AutoLoginKey, resData['data']['aotuLoginKey']);
  429. if (isSaveUserId) {
  430. await prefs.setInt(Constants.LocalUserId, UserData().basicInfo.userId);
  431. }
  432. }
  433. }
  434. ///登录
  435. changePage(BuildContext context, Map resData) async {
  436. UserData().basicInfo.userId = resData['data']['userid'];
  437. UserData().basicInfo.sex = resData['data']['sex'];
  438. if (resData['data']['mobile'] != null && resData['data']['mobile'] != '') {
  439. UserData().mobile = int.parse(resData['data']['mobile']);
  440. }
  441. if (resData['data']['bindId'] != null) {
  442. UserData().agentId = resData['data']['bindId'];
  443. }
  444. //读取聊天信息
  445. await ChatDataMgr().initMsg();
  446. //读取群信息
  447. await GroupInfoMgr().initLocalGroupList();
  448. print('~~~~~~~~~~~~~changePage~~~~~~~~~~~~~~~~~~~~~~');
  449. changeLanguage(context, UserData().language, null);
  450. getRewardAndRedPacketState();
  451. //clearReadData(UserData().basicInfo.userId);
  452. if (resData['data']['sex'] == 0) {
  453. Navigator.of(context).push(
  454. new MaterialPageRoute(
  455. builder: (context) {
  456. return SelectSex();
  457. },
  458. ),
  459. );
  460. saveAotuLoginKey(resData, isSaveUserId: false);
  461. return;
  462. }
  463. if (resData['data']['info'] == 0) {
  464. Navigator.of(context).push(
  465. new MaterialPageRoute(
  466. builder: (context) {
  467. return EditPage(
  468. isEditPage: false,
  469. );
  470. },
  471. ),
  472. );
  473. saveAotuLoginKey(resData, isSaveUserId: false);
  474. return;
  475. }
  476. LocalNotificationUtil.instance.startPush();
  477. //ChatDataMgr().initMsg();
  478. Navigator.of(context)
  479. .pushNamedAndRemoveUntil('/main', (route) => route == null);
  480. MessageMgr().emit('update_system');
  481. saveAotuLoginKey(resData);
  482. getFirstProgram();
  483. initLocation();
  484. }
  485. initLocation() async {
  486. SharedPreferences prefs = await SharedPreferences.getInstance();
  487. var latitude = prefs.getDouble(Constants.Latitude);
  488. var longitude = prefs.getDouble(Constants.Longitude);
  489. print('存贮在本地的位置: $latitude------$longitude');
  490. if (latitude != null) UserData().latitude = latitude;
  491. if (longitude != null) UserData().longitude = longitude;
  492. }
  493. setPhote(BuildContext context, id, type, callback) async {
  494. var data = {
  495. "userId": UserData().basicInfo.userId,
  496. "type": type,
  497. "pId": id,
  498. };
  499. data['sign'] = TokenMgr().getSign(data);
  500. Response res = await HttpUtil()
  501. .post('photos/setting/burns', data: data, isShowLoading: true);
  502. if (res == null) {
  503. print('请求异常');
  504. return;
  505. }
  506. var resData = res.data;
  507. showToast(resData['msg']);
  508. if (resData['code'] == 0) {
  509. if (callback != null) callback();
  510. }
  511. }
  512. clearCacheData() async {
  513. print('######### 清除缓存key');
  514. SharedPreferences prefs = await SharedPreferences.getInstance();
  515. prefs.remove(Constants.AutoLoginKey);
  516. prefs.remove(Constants.LocalUserId);
  517. prefs.remove(Constants.LocalUsrInfo);
  518. }
  519. // clearReadData(userId) async {
  520. // SharedPreferences prefs = await SharedPreferences.getInstance();
  521. // var localUserId = prefs.getInt(Constants.LocalUserId);
  522. // if (userId != localUserId) {
  523. // prefs.remove(Constants.ApplyCount);
  524. // prefs.remove(Constants.EvaluateCount);
  525. // prefs.remove(Constants.ParkCount);
  526. // prefs.remove(Constants.CastCount);
  527. // prefs.remove(Constants.WalletCount);
  528. // }
  529. // }
  530. void postLoginOut(BuildContext context) async {
  531. Map data = {
  532. "userId": UserData().basicInfo.userId,
  533. };
  534. data['sign'] = TokenMgr().getSign(data);
  535. Response res = await HttpUtil().post('user/login/out', data: data);
  536. if (res == null) {
  537. print('请求异常');
  538. return;
  539. }
  540. Map resData = res.data;
  541. if (resData['code'] == 0) {
  542. clearCacheData();
  543. FriendListMgr().friendList?.clear();
  544. Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute(
  545. builder: (context) {
  546. return IndexPage();
  547. },
  548. ), (route) => route == null);
  549. NetWork().singOut();
  550. UserData().reset();
  551. } else {
  552. showToast(resData['msg']);
  553. }
  554. }
  555. buyGoods(money, goodsId, detailtype, changeuserId, context, callback) async {
  556. if (Provider.of<MoneyChangeProvider>(context).money < money) {
  557. showToast(I18n.of(context).balance_insufficien);
  558. return;
  559. }
  560. var data = {
  561. "userId": UserData().basicInfo.userId,
  562. "type": 1,
  563. "detailtype": detailtype,
  564. };
  565. data['sign'] = TokenMgr().getSign(data);
  566. data['value'] = money;
  567. data['changeuserId'] = changeuserId;
  568. data['membergoodsId'] = goodsId;
  569. Response res = await HttpUtil()
  570. .post('wealth/user/add', data: data, isShowLoading: true);
  571. if (res == null) {
  572. print('请求异常');
  573. return;
  574. }
  575. Map resData = res.data;
  576. showToast(resData['msg']);
  577. if (resData['code'] == 0) {
  578. Provider.of<MoneyChangeProvider>(context, listen: false).subMoney(money);
  579. if (callback != null) callback();
  580. }
  581. }
  582. buyPictures(money, changeuserId, context, callback) async {
  583. if (Provider.of<MoneyChangeProvider>(context).money < money) {
  584. showToast(I18n.of(context).balance_insufficien);
  585. return;
  586. }
  587. var data = {
  588. "userId": UserData().basicInfo.userId,
  589. "viewUserId": changeuserId,
  590. "price": money,
  591. };
  592. data['sign'] = TokenMgr().getSign(data);
  593. Response res = await HttpUtil()
  594. .post('photos/user/unlock', data: data, isShowLoading: true);
  595. if (res == null) {
  596. print('请求异常');
  597. return;
  598. }
  599. Map resData = res.data;
  600. showToast(resData['msg']);
  601. if (resData['code'] == 0) {
  602. Provider.of<MoneyChangeProvider>(context, listen: false).subMoney(money);
  603. if (callback != null) callback();
  604. }
  605. }
  606. buyVIP(int money, int gid, int type, BuildContext context, callback) async {
  607. if (Provider.of<MoneyChangeProvider>(context).money < money) {
  608. showToast(I18n.of(context).balance_insufficien);
  609. return;
  610. }
  611. Map data = {
  612. "userId": UserData().basicInfo.userId,
  613. "gid": gid,
  614. "type": type,
  615. "price": money,
  616. };
  617. data['sign'] = TokenMgr().getSign(data);
  618. Response res = await HttpUtil()
  619. .post('goods/user/purchase', data: data, isShowLoading: true);
  620. if (res == null) {
  621. print('请求异常');
  622. return;
  623. }
  624. Map resData = res.data;
  625. showToast(resData['msg']);
  626. if (resData['code'] == 0) {
  627. Provider.of<MoneyChangeProvider>(context, listen: false).subMoney(money);
  628. if (callback != null) callback();
  629. }
  630. }
  631. buyChatAccount(money, changeuserId, context, callback) async {
  632. if (Provider.of<MoneyChangeProvider>(context).money < money) {
  633. showToast(I18n.of(context).balance_insufficien);
  634. return;
  635. }
  636. var data = {
  637. "userId": UserData().basicInfo.userId,
  638. "unlockUserId": changeuserId,
  639. "price": money,
  640. };
  641. data['sign'] = TokenMgr().getSign(data);
  642. Response res = await HttpUtil()
  643. .post('photos/pay/unlock/chat', data: data, isShowLoading: true);
  644. if (res == null) {
  645. print('请求异常');
  646. return;
  647. }
  648. Map resData = res.data;
  649. showToast(resData['msg']);
  650. if (resData['code'] == 0) {
  651. Provider.of<MoneyChangeProvider>(context, listen: false).subMoney(money);
  652. if (callback != null) callback();
  653. }
  654. }
  655. void getMoneyInfo(BuildContext context, callback) async {
  656. if (Platform.isIOS) {
  657. await MoneyPageState.initPayConf(context);
  658. }
  659. Map data = {
  660. "userid": UserData().basicInfo.userId,
  661. "moneytype":
  662. UserData().language == LanguageType.SimplifiedChinese ? 0 : 1,
  663. "mobiletype": Platform.isIOS ? 0 : 1,
  664. };
  665. if (Platform.isIOS) {
  666. data['moneytype'] = 1;
  667. }
  668. print('moneytype ${data['moneytype']}');
  669. data['sign'] = TokenMgr().getSign(data);
  670. Response res = await HttpUtil()
  671. .post('goods/info/list', data: data, isShowLoading: true);
  672. if (res == null) {
  673. print('请求异常');
  674. return;
  675. }
  676. Map resData = res.data;
  677. if (resData['code'] == 0) {
  678. if (callback != null) callback(resData['data']);
  679. }
  680. }
  681. void getWealth(BuildContext context, callback) async {
  682. Map data = {
  683. "userId": UserData().basicInfo.userId,
  684. };
  685. data['sign'] = TokenMgr().getSign(data);
  686. Response res = await HttpUtil().post('wealth/user/info', data: data);
  687. if (res == null) {
  688. print('请求异常');
  689. return;
  690. }
  691. Map resData = res.data;
  692. print(resData);
  693. if (resData['code'] == 0 && resData['data'] != null) {
  694. UserData().basicInfo.isMember = resData['data']['IsMember'] ?? 0;
  695. UserData().incomeMoney = resData['data']['IncomeCoin'];
  696. UserData().frozenMoney = resData['data']['FrozenCoin'];
  697. UserData().memberEndTime = resData['data']['MemberEnd'];
  698. if (callback != null) callback(resData['data']);
  699. }
  700. }
  701. //获取红包与打赏开关状态
  702. getRewardAndRedPacketState() async {
  703. var myId = UserData().basicInfo.userId;
  704. Map data = {
  705. "userId": myId,
  706. };
  707. data['sign'] = TokenMgr().getSign(data);
  708. Response res = await HttpUtil().post('system/switch', data: data);
  709. if (res == null) {
  710. print('请求异常');
  711. return;
  712. }
  713. Map resData = res.data;
  714. print('### system/switch' + resData.toString());
  715. if (resData['code'] == 0) {
  716. var config = resData['data'];
  717. if (config != null) {
  718. UserData().redPacketSW = config['redPacket'];
  719. UserData().giftSwitch = config['reward'];
  720. UserData().bannerZF = config['iapPay'];
  721. UserData().sign = config['sign'];
  722. UserData().groupQRCode = config['groupQRCode'];
  723. UserData().addFdDistanceSwitch = config['distance'] ?? 0;
  724. UserData().stationOpenSwitch = config['station'] == 1;
  725. UserData().myProgramOpenSwitch = config['myProgram'] == 1;
  726. UserData().nearbyOpenSwitch = config['nearby'] == 1;
  727. // print('### config: start');
  728. // print('### config: iapPay:${config['iapPay']}');
  729. }
  730. }
  731. }
  732. ///检查是否有缓存的内购单-有的话向服务器发送请求重新创建订单
  733. void checkReceiptCache() async {
  734. String str = await SPUtils.get(Constants.IOS_IAP_Receipt);
  735. if (str != null && str.isNotEmpty) {
  736. print('### 有缓存单');
  737. List<String> split = str.split("@");
  738. createOrder(split[0], split[1], split[2]);
  739. } else {
  740. print('### 没有缓存单');
  741. }
  742. }
  743. ///ios内购-创建订单
  744. void createOrder(String currentGoodsId, String receipt, String purchaseToken,
  745. {BuildContext context}) async {
  746. // String base84str = base64Encode(utf8.encode(receipt));
  747. var data = {
  748. "userid": UserData().basicInfo.userId,
  749. "moneytype": 1,
  750. 'gid': currentGoodsId,
  751. "payway": 1,
  752. };
  753. data['sign'] = TokenMgr().getSign(data);
  754. data['receipt'] = receipt;
  755. data['isenable'] = Constants.isSandbox ? 0 : 1;
  756. Response res = await HttpUtil().post('order/add/goods', data: data);
  757. print('#### 创建订单-返回');
  758. if (res == null) {
  759. print('请求异常');
  760. return;
  761. }
  762. Map resData = res.data;
  763. print('#### 创建订单-返回:' + resData.toString());
  764. if (resData['code'] == 0) {
  765. // String OrderNo = resData['data']['OrderNo'];
  766. Future.delayed(Duration(seconds: 3), () {
  767. MessageMgr().emit('refresh_money');
  768. });
  769. if (context == null) {
  770. await FlutterInappPurchase.instance.initConnection;
  771. }
  772. FlutterInappPurchase.instance.finishTransaction(purchaseToken);
  773. SPUtils.remove(Constants.IOS_IAP_Receipt);
  774. } else {
  775. ///创建订单失败-
  776. await SPUtils.saveString(Constants.IOS_IAP_Receipt,
  777. currentGoodsId + '@' + receipt + '@' + purchaseToken);
  778. }
  779. if (context != null) {
  780. Navigator.of(context).pop();
  781. }
  782. }
  783. ///登陆
  784. void login(
  785. String _phoneNumber, String _passWorld, BuildContext context) async {
  786. var data = {
  787. "mobile": _phoneNumber,
  788. "text": _passWorld,
  789. "type": 0,
  790. "language": UserData().language,
  791. };
  792. data['sign'] = TokenMgr().getSign(data);
  793. Response res = await HttpUtil()
  794. .post('user/mobile/login', data: data, isShowLoading: true);
  795. if (res == null) {
  796. print('请求异常');
  797. return;
  798. }
  799. var resData = res.data;
  800. if (resData['code'] == 0 && resData['data'] != null) {
  801. HttpUtil().changePage(context, resData);
  802. } else {
  803. showToast(resData['msg']);
  804. }
  805. }
  806. ///获取推送设置
  807. getSettingInfo() async {
  808. Map data = {
  809. "userId": UserData().basicInfo.userId,
  810. "sex": UserData().basicInfo.sex,
  811. };
  812. data['sign'] = TokenMgr().getSign(data);
  813. try {
  814. Response res = await HttpUtil().post('message/push/message', data: data);
  815. if (res == null) {
  816. print('请求异常');
  817. return;
  818. }
  819. Map resData = res.data;
  820. bool isMan = UserData().isMan();
  821. ///女号 {data: {PrivacyChat: 1, NewBroadcast: 1, ApplyCheck: 1, CheckAccount: 1, CheckPhoto: 1, SendAccount: 1}, code: 0, msg: 成功}
  822. ///男号 {data: {PrivacyChat: 1, NewBroadcast: 1, AcceptCheck: 1, ApplySuccess: 1}, code: 0, msg: 成功}
  823. print('###settingdata res.data ${res.data}');
  824. if (resData['code'] == 0) {
  825. UserData().privatyMsgPushSwitch = resData['data']['PrivacyChat'] == 1;
  826. UserData().newDateSwitch = resData['data']['NewBroadcast'] == 1;
  827. if (isMan) {
  828. UserData().acceptCheckSwitch = resData['data']['AcceptCheck'] == 1;
  829. UserData().codeSucessSwitch = resData['data']['ApplySuccess'] == 1;
  830. } else {
  831. UserData().applyCheckSwitch = resData['data']['ApplyCheck'] == 1;
  832. UserData().checkPhotoSwitch = resData['data']['CheckPhoto'] == 1;
  833. }
  834. }
  835. } catch (e) {}
  836. MessageMgr().emit(MessageMgr.REFRESH_PUSH_PERMISSION);
  837. }
  838. ///版本控制
  839. appVersionUpdate(Function callBack) async {
  840. Map data = {
  841. "ditch": Constants.isStoreVersion ? 0 : 1,
  842. "type": Platform.isAndroid ? 0 : 1,
  843. };
  844. data['sign'] = TokenMgr().getSign(data);
  845. data['language'] = UserData().language;
  846. try {
  847. Response res = await HttpUtil().post('system/version/info', data: data);
  848. Map resData = res.data;
  849. print('###appVersionUpdate res.data ${res.data}');
  850. if (resData['code'] == 0) {
  851. bool needNotice = resData['data']['Notice'] == 1;
  852. ///是否通知更新
  853. bool forceUpdate = resData['data']['IsStronger'] == 1;
  854. ///是否通知强更
  855. String version = resData['data']['VersionNo'];
  856. String describe = resData['data']['Describe'];
  857. String downloadUrl = resData['data']['DownloadUrl'];
  858. String appId = resData['data']['AppId'];
  859. callBack(
  860. needNotice, forceUpdate, version, describe, downloadUrl, appId);
  861. }
  862. } catch (e) {}
  863. }
  864. downloadApk(
  865. BuildContext context,
  866. String filePath,
  867. String downloadUrl,
  868. Function downloadCallback,
  869. ) async {
  870. final file = new File(filePath);
  871. bool isExist = await file.exists();
  872. if (isExist) {
  873. print('### 文件存在 : ${file.path}');
  874. file.delete();
  875. }
  876. // else {
  877. //
  878. // print('### 开始下载 $downloadUrl');
  879. // dio.download(downloadUrl, filePath, onReceiveProgress: downloadCallback);
  880. // }
  881. // downloadUrl ='oemarket.com/app0/30/30970/apk/2085562.apk?channel_id=426&tid=d73j9ihlkucuxfqpgnxgjeif';
  882. dio.download(downloadUrl, filePath, onReceiveProgress: downloadCallback);
  883. }
  884. ///获取用户每日签到信息
  885. Future<DailyBonusBean> getDailyBonus() async {
  886. Map data = {
  887. "userId": UserData().basicInfo.userId,
  888. };
  889. data['sign'] = TokenMgr().getSign(data);
  890. data['userId'] = UserData().basicInfo.userId;
  891. try {
  892. Response res = await HttpUtil().post('sign/in/user/info', data: data);
  893. Map resData = res.data;
  894. print('###getDailyBonus res.data ${res.data}');
  895. if (resData['code'] == 0) {
  896. return DailyBonusBean.fromMap(resData['data']);
  897. }
  898. return null;
  899. } catch (e) {
  900. return null;
  901. }
  902. }
  903. ///点击签到
  904. Future<bool> signInBounus(int score) async {
  905. Map data = {
  906. "userId": UserData().basicInfo.userId,
  907. "score": score,
  908. };
  909. data['sign'] = TokenMgr().getSign(data);
  910. data['userId'] = UserData().basicInfo.userId;
  911. data['score'] = score;
  912. try {
  913. Response res = await HttpUtil().post('sign/in/user', data: data);
  914. Map resData = res.data;
  915. print('###signInBounus res.data ${res.data}');
  916. if (resData['code'] == 0) {
  917. return true;
  918. // bool needNotice = resData['data']['Notice']==1; ///是否通知更新
  919. // return DailyBonusBean.fromMap(resData['data']);
  920. } else {
  921. showToast(resData['msg']);
  922. }
  923. return false;
  924. } catch (e) {
  925. return false;
  926. }
  927. }
  928. /// 用户签到积分兑换商品
  929. Future<bool> signInExchange(GoodsBean goodsBean) async {
  930. Map data = {
  931. "userId": UserData().basicInfo.userId,
  932. "id": goodsBean.id,
  933. "score": goodsBean.s,
  934. };
  935. data['sign'] = TokenMgr().getSign(data);
  936. data['userId'] = UserData().basicInfo.userId;
  937. data['score'] = goodsBean.s;
  938. data['id'] = goodsBean.id;
  939. try {
  940. Response res =
  941. await HttpUtil().post('sign/in/score/exchange', data: data);
  942. Map resData = res.data;
  943. print('###signInExchange res.data ${res.data}');
  944. if (resData['code'] == 0) {
  945. return true;
  946. } else {
  947. showToast(resData['msg']);
  948. }
  949. return false;
  950. } catch (e) {
  951. return false;
  952. }
  953. }
  954. addFriends(
  955. BuildContext context, int friendId, String content, callback) async {
  956. Map data = {
  957. "userId": UserData().basicInfo.userId,
  958. "friendsUserId": friendId
  959. };
  960. data['sign'] = TokenMgr().getSign(data);
  961. data['content'] = content;
  962. Response res = await HttpUtil().post('friendship/add/friends', data: data);
  963. Map resData = res.data;
  964. print(resData);
  965. if (resData['code'] == 0) {
  966. showToast(resData['msg']);
  967. if (callback != null) callback();
  968. }
  969. }
  970. //付费人工翻译
  971. getPersonalTranslate(MsgModel msgModel) async {
  972. Map data = {
  973. "suserid": msgModel.from,
  974. "chatmsgid": msgModel.time,
  975. "slanguage": 1,
  976. "tlanguage": UserData().language,
  977. "chattype": msgModel.msgType,
  978. "chatchanneltype": msgModel.channelType,
  979. "targetid": msgModel.sessionId
  980. };
  981. data['sign'] = TokenMgr().getSign(data);
  982. if (msgModel.msgType == 0) {
  983. data['content'] = base64Encode(msgModel.msgContent);
  984. } else {
  985. if (msgModel.localFile == null) {
  986. showToast('请稍后再试');
  987. return;
  988. }
  989. data['content'] =
  990. base64Encode(File(msgModel.localFile).readAsBytesSync());
  991. }
  992. data["tuserids"] = [UserData().basicInfo.userId];
  993. data['duration'] =
  994. msgModel.extraInfo != null ? msgModel.extraInfo ~/ 1000 : 0;
  995. data['ispay'] = true;
  996. if (msgModel.msgType == ChatType.TextChatType.value) {
  997. int length = utf8.decode(msgModel.msgContent).length;
  998. data['money'] = length ~/ 50 + 1; //每50个字耗费1H币
  999. print('字数 $length 价格 ${length % 50 + 1}');
  1000. } else if (msgModel.msgType == ChatType.ShortVoiceChatType.value) {
  1001. //没20秒扣除1Hb
  1002. data['money'] =
  1003. msgModel.extraInfo != null ? msgModel.extraInfo ~/ 20000 + 1 : 0;
  1004. }
  1005. if (msgModel.translateContent != null &&
  1006. msgModel.translateContent.length > 0) {
  1007. data['mcontent'] = base64Encode(msgModel.enTranslateContent);
  1008. }
  1009. Response res =
  1010. await HttpUtil().post('service/paid/translation', data: data);
  1011. if (res == null) {
  1012. return false;
  1013. }
  1014. Map resData = res.data;
  1015. print('付费翻译请求$resData');
  1016. if (resData['code'] == 0) {
  1017. print('扣除 H 币 ${data['money']}');
  1018. return true;
  1019. }
  1020. print(resData['msg']);
  1021. showToast(resData['msg']);
  1022. return false;
  1023. }
  1024. //用户评价人工翻译,差评
  1025. Future<bool> rateTranslateResult(MsgModel msg, Function callback) async {
  1026. Map data = {
  1027. "userId": UserData().basicInfo.userId,
  1028. "chatUserId": msg.from,
  1029. "chatMsgId": msg.time,
  1030. "score": 1
  1031. };
  1032. data['sign'] = TokenMgr().getSign(data);
  1033. Response res = await HttpUtil().post('translate/user/score', data: data);
  1034. if (res == null) {
  1035. return false;
  1036. }
  1037. var resData = res.data;
  1038. if (resData['code'] == 0) {
  1039. msg.transTag = 10; //已评价过
  1040. if (callback != null) {
  1041. callback();
  1042. }
  1043. SqlUtil().updateUserTranslateRate(msg.sessionId, msg.time, msg.transTag);
  1044. return true;
  1045. }
  1046. return false;
  1047. }
  1048. //根据经纬度获取用户国家城市
  1049. getAddress(double lon, double lat) async {
  1050. Map data = {
  1051. "lon": lon,
  1052. "lat": lat,
  1053. };
  1054. data['sign'] = TokenMgr().getSign(data);
  1055. data['language'] = UserData().language;
  1056. Response res = await HttpUtil().post('user/get/address', data: data);
  1057. if (res == null) return;
  1058. Map resData = res.data;
  1059. if (resData['code'] == 0 && resData['data'] != null) {
  1060. print(resData['data']);
  1061. List address = resData['data'].split(',');
  1062. if (address.length != 2) return;
  1063. String country = address[0];
  1064. String city = address[1];
  1065. UserData().isInChina = false;
  1066. if (country == '越南') {
  1067. UserData().currentCity = 'VietNam-';
  1068. List citys = constData[3]['city'][0]['List'];
  1069. for (int i = 0; i < citys.length; i++) {
  1070. if (citys[i]['Value'] == city) {
  1071. UserData().currentCity += citys[i]['Key'];
  1072. break;
  1073. }
  1074. }
  1075. } else if (country == '中国') {
  1076. UserData().isInChina = true;
  1077. UserData().currentCity = 'China-ChinaRepeat';
  1078. } else {
  1079. UserData().currentCity = 'VietNam-HoChiMinhCIty';
  1080. }
  1081. if (UserData().currentCity != UserData().basicInfo.meetPlace) {
  1082. UserData().basicInfo.meetPlace = UserData().currentCity;
  1083. changeCurrentCity(lon, lat, () {});
  1084. }
  1085. MessageMgr().emit('change_currentcity');
  1086. }
  1087. }
  1088. //根据经纬度获取用户国家城市
  1089. changeCurrentCity(double lon, double lat, callback) async {
  1090. if (UserData().basicInfo.userId == null) return;
  1091. Map data = {
  1092. "userId": UserData().basicInfo.userId,
  1093. "lon": lon,
  1094. "lat": lat,
  1095. };
  1096. data['sign'] = TokenMgr().getSign(data);
  1097. Response res = await HttpUtil().post('user/update/meetPlace', data: data);
  1098. if (res == null) return;
  1099. Map resData = res.data;
  1100. print(resData);
  1101. if (resData['code'] == 0) {
  1102. callback();
  1103. }
  1104. }
  1105. //通过手机号查询用户
  1106. searchNewFrindsByPhone(String phone, callback) async {
  1107. Map data = {
  1108. "userId": UserData().basicInfo.userId,
  1109. "value": phone,
  1110. };
  1111. data['sign'] = TokenMgr().getSign(data);
  1112. Response res = await HttpUtil()
  1113. .post('/friendship/search/userPhone', data: data, isShowLoading: true);
  1114. if (res == null) return;
  1115. Map resData = res.data;
  1116. print(resData);
  1117. if (resData['code'] == 0) {
  1118. callback(resData['data']['UserId']);
  1119. }
  1120. }
  1121. //向企业服务助手提交信息
  1122. Future<bool> commitInfoToCompany(MsgModel msgModel) async {
  1123. Map data = {
  1124. "userid": msgModel.from,
  1125. "msgType": msgModel.msgType,
  1126. };
  1127. data['sign'] = TokenMgr().getSign(data);
  1128. data['msgContent'] = base64Encode(msgModel.msgContent);
  1129. msgModel.state = MsgState.Sending;
  1130. print('commitInfoToCompany 参数 $data');
  1131. Response res = await HttpUtil().post('feedback/user/insert', data: data);
  1132. if (res == null) {
  1133. msgModel.state = MsgState.SendingFailed;
  1134. ChatDataMgr().updateMsgState(msgModel.sessionId, msgModel.time,
  1135. msgModel.channelType, msgModel.state);
  1136. return false;
  1137. }
  1138. Map resData = res.data;
  1139. print('commitInfoToCompany $resData');
  1140. if (resData['code'] == 0) {
  1141. msgModel.state = MsgState.SendingSuccess;
  1142. ChatDataMgr().updateMsgState(msgModel.sessionId, msgModel.time,
  1143. msgModel.channelType, msgModel.state);
  1144. return true;
  1145. }
  1146. showToast(resData['msg']);
  1147. return false;
  1148. }
  1149. }