web_cubit.dart 30.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:app_settings/app_settings.dart';
import 'package:appframe/config/constant.dart';
import 'package:appframe/config/locator.dart';
import 'package:appframe/config/routes.dart';
import 'package:appframe/data/models/message/h5_message.dart';
import 'package:appframe/services/dispatcher.dart';
import 'package:appframe/services/im_service.dart';
import 'package:appframe/services/local_server_service.dart';
import 'package:appframe/services/player_service.dart';
import 'package:appframe/services/recorder_service.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:dio/dio.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluwx/fluwx.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

class WebState extends Equatable {
  final int selectedIndex;

  final bool loaded;
  final bool isUpgrading;
  final bool suggestUpgrade;

  final String title;
  final int titleColor;
  final int bgColor;
  final String opIcon;
  final bool showBottomNavBar;

  final String? sessionCode;
  final String? userCode;
  final String? classCode;
  final int? userType;
  final String? stuId;

  /// getOrientationCmd
  final bool orientationCmdFlag;
  final String orientationCmdMessage;

  /// getWindowInfoCmd
  final bool windowInfoCmdFlag;
  final String windowInfoCmdMessage;

  /// chooseImageCmd
  final bool chooseImageCmdFlag;
  final String chooseImageCmdMessage;

  /// chooseVideoCmd
  final bool chooseVideoCmdFlag;
  final String chooseVideoCmdMessage;

  final String h5Version;

  const WebState({
    this.selectedIndex = 0,
    this.loaded = false,
    this.isUpgrading = false,
    this.suggestUpgrade = false,
    this.title = '',
    this.titleColor = 0xFFFFFFFF,
    this.bgColor = 0xFF7691FA,
    this.opIcon = 'none',
    this.showBottomNavBar = false,
    this.sessionCode,
    this.userCode,
    this.classCode,
    this.userType,
    this.stuId,
    this.orientationCmdFlag = false,
    this.orientationCmdMessage = '',
    this.windowInfoCmdFlag = false,
    this.windowInfoCmdMessage = '',
    this.chooseImageCmdFlag = false,
    this.chooseImageCmdMessage = '',
    this.chooseVideoCmdFlag = false,
    this.chooseVideoCmdMessage = '',
    this.h5Version = '',
  });

  WebState copyWith({
    int? selectedIndex,
    bool? loaded,
    bool? isUpgrading,
    bool? suggestUpgrade,
    String? title,
    int? titleColor,
    int? bgColor,
    String? opIcon,
    bool? showNavBar,
    bool? showBottomNavBar,
    String? sessionCode,
    String? userCode,
    String? classCode,
    int? userType,
    String? stuId,
    bool? orientationCmdFlag,
    String? orientationCmdMessage,
    bool? windowInfoCmdFlag,
    String? windowInfoCmdMessage,
    bool? chooseImageCmdFlag,
    String? chooseImageCmdMessage,
    bool? chooseVideoCmdFlag,
    String? chooseVideoCmdMessage,
    String? h5Version,
  }) {
    return WebState(
      selectedIndex: selectedIndex ?? this.selectedIndex,
      loaded: loaded ?? this.loaded,
      isUpgrading: isUpgrading ?? this.isUpgrading,
      suggestUpgrade: suggestUpgrade ?? this.suggestUpgrade,
      title: title ?? this.title,
      titleColor: titleColor ?? this.titleColor,
      bgColor: bgColor ?? this.bgColor,
      opIcon: opIcon ?? this.opIcon,
      showBottomNavBar: showBottomNavBar ?? this.showBottomNavBar,
      sessionCode: sessionCode ?? this.sessionCode,
      userCode: userCode ?? this.userCode,
      classCode: classCode ?? this.classCode,
      userType: userType ?? this.userType,
      stuId: stuId ?? this.stuId,
      orientationCmdFlag: orientationCmdFlag ?? this.orientationCmdFlag,
      orientationCmdMessage: orientationCmdMessage ?? this.orientationCmdMessage,
      windowInfoCmdFlag: windowInfoCmdFlag ?? this.windowInfoCmdFlag,
      windowInfoCmdMessage: windowInfoCmdMessage ?? this.windowInfoCmdMessage,
      chooseImageCmdFlag: chooseImageCmdFlag ?? this.chooseImageCmdFlag,
      chooseImageCmdMessage: chooseImageCmdMessage ?? this.chooseImageCmdMessage,
      chooseVideoCmdFlag: chooseVideoCmdFlag ?? this.chooseVideoCmdFlag,
      chooseVideoCmdMessage: chooseVideoCmdMessage ?? this.chooseVideoCmdMessage,
      h5Version: h5Version ?? this.h5Version,
    );
  }

  @override
  List<Object?> get props => [
        selectedIndex,
        loaded,
        isUpgrading,
        suggestUpgrade,
        title,
        titleColor,
        bgColor,
        opIcon,
        showBottomNavBar,
        sessionCode,
        userCode,
        classCode,
        userType,
        stuId,
        orientationCmdFlag,
        orientationCmdMessage,
        windowInfoCmdFlag,
        windowInfoCmdMessage,
        chooseImageCmdFlag,
        chooseImageCmdMessage,
        chooseVideoCmdFlag,
        chooseVideoCmdMessage,
        h5Version,
      ];
}

class WebCubit extends Cubit<WebState> {
  late final MessageDispatcher _dispatcher;
  late final WebViewController _controller;
  late final Fluwx _fluwx;
  HttpServer? _server;
  PlayerService? _playerService;
  RecorderService? _recorderService;

  WebViewController get controller => _controller;

  WebCubit(super.initialState) {
    // 没有登录数据,跳转到登录页面
    if (state.sessionCode == null || state.sessionCode == '') {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        router.go('/loginMain');
      });
    } else {
      _init();
    }
  }

  Future<void> _init() async {
    // 当前使用的H5版本
    var curVersion = getIt.get<SharedPreferences>().getString(Constant.h5VersionKey) ?? Constant.h5Version;
    try {
      // 获取版本信息
      var versionConfig = await _getVersionConfig();
      var configVersion = versionConfig['version'] as String;
      var downloadUrl = versionConfig['zip'] as String;
      var force = versionConfig['force'] as String;

      // 版本不一致则需要升级
      // 需要强制升级时,一直等待下载完成
      // 不需要强制升级时,异步下载,下载完后弹框提示用户进行确认操作
      if (curVersion != configVersion) {
        if (force == "1") {
          // 一直等待升级完成
          // 遮罩界面
          emit(state.copyWith(isUpgrading: true));
          await _downloadH5Zip(configVersion, downloadUrl);
          _setH5Version(configVersion);
          // 下载完成后取消遮罩,继续初始化其它数据
          emit(state.copyWith(isUpgrading: false));
        } else {
          // 后台下载,完成后提示用户
          _downloadH5Zip(configVersion, downloadUrl).then(
            (value) {
              _setH5Version(configVersion);
              emit(state.copyWith(suggestUpgrade: true));
            },
          );
        }
      }
    } catch (e) {
      emit(state.copyWith(isUpgrading: false));
      print('升级检测处理失败');
      print(e);
    }

    // 消息处理器
    _dispatcher = MessageDispatcher();

    // 启动本地服务器
    await _startLocalServer();

    // 创建WebView控制器
    await _createWebViewController();

    // 加载H5页面
    _loadHtml();

    // 读取 h5 版本号
    _readH5ShowVersion();

    // 初始化其它一些属性
    _fluwx = getIt.get<Fluwx>();
    _playerService = getIt.get<PlayerService>();
    _playerService?.sendResponse = _sendResponse;
    _recorderService = getIt.get<RecorderService>();

    // 登录IM
    _loginIM();
  }

  Future<Map<String, String>> _getVersionConfig() async {
    Dio dio = Dio();
    try {
      Response response = await dio.get(
        '${Constant.configUrl}?t=${DateTime.now().millisecondsSinceEpoch}',
        options: Options(responseType: ResponseType.json),
      );
      if (response.statusCode != 200) {
        throw Exception('获取版本信息失败');
      }

      String version = response.data['version'] as String;
      String force = response.data['force'] as String;
      String zip = response.data['zip'] as String;
      return {
        'version': version,
        'force': force,
        'zip': '$zip$version.zip',
      };
    } finally {
      dio.close(force: true);
    }
  }

  Future<void> _downloadH5Zip(String version, String zipUrl) async {
    Dio dio = Dio();
    try {
      // 下载zip文件
      var tempDir = await getTemporaryDirectory();
      var tempFilePath = '${tempDir.path}/${Uuid().v4()}.zip';

      Response response = await dio.download(zipUrl, tempFilePath);
      if (response.statusCode != 200) {
        throw Exception('文件下载失败');
      }

      var dir = await getApplicationSupportDirectory();
      String httpDirPath = '${dir.path}/${Constant.h5DistDir}';

      var httpDir = Directory(httpDirPath);
      if (!httpDir.existsSync()) {
        await httpDir.create(recursive: true);
      }

      var tempZipFile = File(tempFilePath);
      var saveZipFilePath = '$httpDirPath/$version.zip';

      // 复制zip文件,保留备用
      await tempZipFile.copy(saveZipFilePath);
      // 删除临时文件
      await tempZipFile.delete();
    } finally {
      dio.close(force: true);
    }
  }

  void _setH5Version(String version) {
    getIt.get<SharedPreferences>().setString(Constant.h5VersionKey, version);
  }

  Future<void> _startLocalServer() async {
    // 启动本地服务器
    _server = await getIt.get<LocalServerService>().startLocalServer();
  }

  Future<void> _createWebViewController() async {
    _controller = WebViewController();
    await _controller.setJavaScriptMode(JavaScriptMode.unrestricted);
    await _controller.setNavigationDelegate(
      NavigationDelegate(
        onUrlChange: (UrlChange url) {},
        onPageStarted: (String url) async {
          // 进行新页面加载时,关闭录音器和播放器,(如果有打开过)
          await _playerService?.close();
          await _recorderService?.close();
        },
        onPageFinished: (String url) async {
          print('onPageFinished--------------------------------->');
          print(url);

          _controller.runJavaScript(
            'document.querySelector("meta[name=viewport]").setAttribute("content", "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no")',
          );

          finishLoading();
        },
      ),
    );
    await _controller.addJavaScriptChannel("xeJsBridge", onMessageReceived: _onMessageReceived);
  }

  void _loadHtml() {
    // 构造函数中已拦截判断未登录的情况进行了处理,所以这里不再处理未登录的情况
    final String serverUrl = '${Constant.localServerUrl}/index.html'
        '#/h5/login/pages/applogin?'
        'sessionCode=${state.sessionCode}&'
        'userCode=${state.userCode}&'
        'classCode=${state.classCode}&'
        'userType=${state.userType}&'
        'stuId=${state.stuId}';
    // final String serverUrl = '${Constant.localServerUrl}/test/test2.html';
    _controller.loadRequest(Uri.parse(serverUrl));
  }

  void _readH5ShowVersion() {
    var h5Version = getIt.get<SharedPreferences>().getString(Constant.h5ShowVersionKey) ?? 'unknown';
    emit(state.copyWith(h5Version: h5Version));
  }

  Future<void> _loginIM() async {
    if (Constant.needIM) {
      var imService = getIt.get<ImService>();
      var loginResult = await imService.login(state.userCode!);
      if (loginResult) {
        print("缓存自动登录处,IM 登录成功");
        await imService.registerPush();
      } else {
        print("缓存自动登录处,IM 登录失败");
      }
    }
  }

  void _onMessageReceived(JavaScriptMessage message) async {
    try {
      _dispatcher.dispatch(message.message, (response) {
        _sendResponse(response);
      }, webCubit: this);
    } catch (e) {
      print('消息解析错误: $e');
    }
  }

  // 向H5发送响应
  void _sendResponse(Map<String, dynamic> response) {
    String jsonString = jsonEncode(response);
    String escapedJson = jsonString.replaceAll('"', '\\"');
    final String script = 'xeJsBridgeCallback("$escapedJson");';
    _controller.runJavaScript(script);
  }

  void finishLoading() {
    emit(state.copyWith(loaded: true));
  }

  void goLogin() {
    router.go('/loginMain');
  }

  void goIm() {
    router.go('/im');
  }

  //测试
  void goAuth() {
    String serverUrl = '${Constant.localServerUrl}/index.html';
    _controller.loadRequest(Uri.parse(serverUrl));
  }

  void goMiniProgram() {
    _fluwx
      // ..addSubscriber(_responseListener)
      ..open(
        target: MiniProgram(
          username: 'gh_9a8d84445828',
          path: '/pages/index/index?classCode=needswitch',
          miniProgramType: WXMiniProgramType.preview,
        ),
      );

    // _fluwx.share(WeChatShareTextModel("source text", scene: WeChatScene.session));
  }

  // void _responseListener(response) {
  //   if (response is WeChatLaunchMiniProgramResponse) {
  //     print("小程序跳转 1 --------------------------------");
  //     print(response);
  //   }
  // }

  Future<String?> goScanCode() async {
    var result = await router.push('/scanCode');
    return result as String?;
  }

  Future<void> handleBack() async {
    // navigateBack指令
    var resp = {'unique': '', 'cmd': 'navigateBack', 'data': '', 'errMsg': ''};
    _sendResponse(resp);
  }

  Future<void> handleHome() async {
    // navigateHome指令
    var resp = {'unique': '', 'cmd': 'navigateHome', 'data': '', 'errMsg': ''};
    _sendResponse(resp);
  }

  Future<void> handleRefreshPage() async {
    // refreshPage指令
    var resp = {'unique': '', 'cmd': 'refreshPage', 'data': '', 'errMsg': ''};
    _sendResponse(resp);
  }

  bool setTitleBar(String title, String color, String bgColor, String icon) {
    int parsedTitleColor = _hexStringToInt(color);
    int parsedBgColor = _hexStringToInt(bgColor);

    emit(state.copyWith(title: title, titleColor: parsedTitleColor, bgColor: parsedBgColor, opIcon: icon));
    return true;
  }

  int _hexStringToInt(String hexString) {
    // 移除可能存在的 # 前缀
    if (hexString.startsWith('#')) {
      hexString = hexString.substring(1);
    }

    // 确保颜色值是8位(包含alpha通道)
    if (hexString.length == 6) {
      hexString = 'FF$hexString'; // 添加不透明的alpha值
    }

    // 解析十六进制字符串为整数
    return int.parse(hexString, radix: 16);
  }

  Future<void> refresh() async {
    // await clearRecording();
    // await clearAudio();
    _controller.reload();
  }

  Future<void> clearStorage() async {
    // 1 清理 localStorage
    _controller.clearLocalStorage();
    _controller.clearCache();

    // 2 清理非 h5_version 的缓存
    var sharedPreferences = getIt.get<SharedPreferences>();
    sharedPreferences.getKeys().forEach((key) async {
      if (!key.startsWith('h5')) {
        await sharedPreferences.remove(key);
      }
    });

    // 3 清理 http_dist_assets 下的非当前版本号的文件和目录
    var dir = await getApplicationSupportDirectory();
    var httpDir = Directory('${dir.path}/${Constant.h5DistDir}');
    if (httpDir.existsSync()) {
      var version = sharedPreferences.getString(Constant.h5VersionKey) ?? Constant.h5Version;

      await for (final FileSystemEntity entity in httpDir.list()) {
        if (entity is Directory) {
          // 删除目录
          if (!entity.path.endsWith(version)) {
            await entity.delete(recursive: true);
          }
        } else if (entity is File) {
          // 删除文件
          if (!entity.path.endsWith('$version.zip')) {
            await entity.delete();
          }
        }
      }
    }

    // 4 清理临时目录下的所有文件和目录
    var tempDir = await getTemporaryDirectory();
    if (tempDir.existsSync()) {
      await for (final FileSystemEntity entity in tempDir.list()) {
        if (entity is Directory) {
          await entity.delete(recursive: true);
        } else {
          await entity.delete();
        }
      }
    }
  }

  Future<void> logout() async {
    // 删除所有auth_开头的key
    var sharedPreferences = getIt.get<SharedPreferences>();
    sharedPreferences.getKeys().forEach((key) {
      if (key.startsWith('auth_')) {
        sharedPreferences.remove(key);
      }
    });

    // IM 登出
    // await getIt.get<ImService>().logout();

    goLogin();
  }

  void updateSelectedIndex(int index) {
    emit(state.copyWith(selectedIndex: index));
  }

  void showBottomNavBar() {
    emit(state.copyWith(showBottomNavBar: true));
  }

  void hideBottomNavBar() {
    emit(state.copyWith(showBottomNavBar: false));
  }

  ///
  /// 升级提示
  ///
  void suggestUpgrade(BuildContext ctx) {
    showDialog(
      context: ctx,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('温馨提示'),
          content: Text('资源已更新为最新版本,是否现在进行加载?'),
          actions: <Widget>[
            TextButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
                emit(state.copyWith(suggestUpgrade: false));
              },
            ),
            TextButton(
              child: Text('确定'),
              onPressed: () {
                Navigator.of(context).pop();
                emit(state.copyWith(suggestUpgrade: false));
                router.go('/reload');
              },
            ),
          ],
        );
      },
    );
  }

  ///
  ///
  ///
  void setChooseImageCmdFlag(bool chooseImageCmdFlag, String chooseImageCmdMessage) {
    emit(state.copyWith(chooseImageCmdFlag: chooseImageCmdFlag, chooseImageCmdMessage: chooseImageCmdMessage));
  }

  void chooseImage(BuildContext context) async {
    final Map<String, dynamic> data = json.decode(state.chooseImageCmdMessage);
    H5Message h5Message = H5Message.fromJson(data);

    setChooseImageCmdFlag(false, '');

    final params = h5Message.params;
    if (params is! Map<String, dynamic>) {
      throw Exception('参数错误');
    }
    var sourceType = params['sourceType'] as String;
    if (sourceType != 'album' && sourceType != 'camera') {
      sourceType = 'album';
    }
    // 暂时忽略 sizeType 参数

    int count = 9;
    if (params.containsKey('count')) {
      count = params['count'] as int;
      if (count < 1 || count > 9) {
        count = 9;
      }
    }

    // 相册
    if (sourceType == 'album') {
      _chooseImageFromAlbum(context, count, h5Message.unique, h5Message.cmd);
    }
    // 拍照
    else {
      _chooseImageFromCamera(context, h5Message.unique, h5Message.cmd);
    }
  }

  void _chooseImageFromAlbum(BuildContext context, int count, String unique, String cmd) async {
    // 检查是否已被永久拒绝,此时需要对用户进行引导
    if (await _checkGalleryPermanentlyDenied()) {
      var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'no auth'};
      _sendResponse(resp);
      _permissionLead(context, '相册权限');
      return;
    }

    final List<AssetEntity>? result;
    try {
      result = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: count,
          requestType: RequestType.image,
          gridThumbnailSize: const ThumbnailSize.square(120),
          previewThumbnailSize: const ThumbnailSize.square(150),
          dragToSelect: false,
        ),
      );
    } catch (e) {
      var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'no auth'};
      _sendResponse(resp);
      return;
    }

    if (result == null || result.isEmpty) {
      var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'cancel'};
      _sendResponse(resp);
      return;
    }

    // 获取临时目录
    final Directory tempDir = await getTemporaryDirectory();

    final List<Map<String, dynamic>> resultList = [];
    for (var asset in result) {
      resultList.add(await _handleSingleImage(asset, tempDir));
    }
    var resp = {
      'unique': unique,
      'cmd': cmd,
      'data': {'tempFiles': resultList},
      'errMsg': '',
    };
    _sendResponse(resp);
  }

  void _chooseImageFromCamera(BuildContext context, String unique, String cmd) async {
    // 检查是否已被永久拒绝,此时需要对用户进行引导
    if (await _checkCameraPermanentlyDenied()) {
      var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'no auth'};
      _sendResponse(resp);
      _permissionLead(context, '相机权限');
      return;
    }

    AssetEntity? asset;
    try {
      asset = await CameraPicker.pickFromCamera(context, pickerConfig: const CameraPickerConfig());
    } catch (e) {
      var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'no auth'};
      _sendResponse(resp);
      return;
    }

    if (asset == null) {
      var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'cancel'};
      _sendResponse(resp);
      return;
    }

    final Directory tempDir = await getTemporaryDirectory();
    final Map<String, dynamic> result = await _handleSingleImage(asset, tempDir);
    var resp = {
      'unique': unique,
      'cmd': cmd,
      'data': {
        'tempFiles': [result],
      },
      'errMsg': '',
    };
    _sendResponse(resp);
  }

  Future<Map<String, dynamic>> _handleSingleImage(AssetEntity asset, Directory tempDir) async {
    final file = await asset.file;

    // 生成缩略图
    final data = await asset.thumbnailData;
    final thumbnailFile = await File(
      '${tempDir.path}/${DateTime.now().millisecondsSinceEpoch}.png',
    ).writeAsBytes(data!);

    return {
      "tempFilePath": '${Constant.localServerTempFileUrl}${file!.path}',
      "size": file.lengthSync(),
      "width": asset.width,
      "height": asset.height,
      "thumbTempFilePath": '${Constant.localServerTempFileUrl}${thumbnailFile.path}',
      "fileType": file.path.split('/').last.split('.').last,
    };
  }

  ///
  /// 引导打开权限设置
  ///
  Future<void> _permissionLead(BuildContext context, String permission) async {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('权限设置'),
          content: Text('$permission已被拒绝,请到设置中手动开启权限'),
          actions: <Widget>[
            TextButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: Text('去设置'),
              onPressed: () {
                Navigator.of(context).pop();
                AppSettings.openAppSettings(asAnotherTask: true); // 引导用户到应用设置页面
              },
            ),
          ],
        );
      },
    );
  }

  ///
  /// 检测相册权限是否被永久拒绝
  ///
  Future<bool> _checkGalleryPermanentlyDenied() async {
    PermissionStatus status;
    if (Platform.isAndroid) {
      final androidInfo = await DeviceInfoPlugin().androidInfo;
      if (androidInfo.version.sdkInt <= 32) {
        status = await Permission.storage.status;
      } else {
        status = await Permission.photos.status;
      }
    } else if (Platform.isIOS) {
      status = await Permission.photos.status;
    } else {
      return false;
    }
    return PermissionStatus.permanentlyDenied == status;
  }

  ///
  /// 检测摄像头权限是否被永久拒绝
  ///
  Future<bool> _checkCameraPermanentlyDenied() async {
    PermissionStatus status = await Permission.camera.status;
    return PermissionStatus.permanentlyDenied == status;
  }

  void setChooseVideoCmdFlag(bool chooseVideoCmdFlag, String chooseVideoCmdMessage) {
    emit(state.copyWith(chooseVideoCmdFlag: chooseVideoCmdFlag, chooseVideoCmdMessage: chooseVideoCmdMessage));
  }

  void chooseVideo(BuildContext context) async {
    final Map<String, dynamic> data = json.decode(state.chooseVideoCmdMessage);
    H5Message h5Message = H5Message.fromJson(data);

    setChooseVideoCmdFlag(false, '');
    final params = h5Message.params;
    if (params is! Map<String, dynamic>) {
      throw Exception('参数错误');
    }
    var sourceType = params['sourceType'] as String;
    if (sourceType != 'album' && sourceType != 'camera') {
      sourceType = 'album';
    }
    // 暂时忽略 sizeType 参数

    int count = 1;
    if (params.containsKey('count')) {
      count = params['count'] as int;
      if (count < 1 || count > 9) {
        count = 9;
      }
    }

    int maxDuration = 60;
    if (params.containsKey('maxDuration')) {
      maxDuration = params['maxDuration'] as int;
      if (maxDuration < 1 || maxDuration > 600) {
        maxDuration = 60;
      }
    }

    // 相册选择
    if (sourceType == 'album') {
      _chooseVideoFromAlbum(context, count, h5Message.unique, h5Message.cmd);
    }
    // 拍摄
    else {
      _chooseVideoFromCamera(context, maxDuration, h5Message.unique, h5Message.cmd);
    }
  }

  void _chooseVideoFromAlbum(BuildContext context, int count, String unique, String cmd) async {
    // 检查是否已被永久拒绝,此时需要对用户进行引导
    if (await _checkGalleryPermanentlyDenied()) {
      var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'no auth'};
      _sendResponse(resp);
      _permissionLead(context, '相册权限');
      return;
    }

    List<AssetEntity>? result;
    try {
      result = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: count,
          requestType: RequestType.video,
          dragToSelect: false,
        ),
      );
    } catch (e) {
      var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'no auth'};
      _sendResponse(resp);
      return;
    }

    if (result == null || result.isEmpty) {
      var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'cancel'};
      _sendResponse(resp);
      return;
    }

    // 获取临时目录
    final Directory tempDir = await getTemporaryDirectory();

    final List<Map<String, dynamic>> resultList = [];
    for (var asset in result) {
      resultList.add(await _handleSingleVideo(asset, tempDir));
    }
    var resp = {
      'unique': unique,
      'cmd': cmd,
      'data': {'tempFiles': resultList},
      'errMsg': '',
    };
    _sendResponse(resp);
  }

  void _chooseVideoFromCamera(BuildContext context, int maxDuration, String unique, String cmd) async {
    // 检查是否已被永久拒绝,此时需要对用户进行引导
    if (await _checkCameraPermanentlyDenied()) {
      var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'no auth'};
      _sendResponse(resp);
      _permissionLead(context, '相机权限');
      return;
    }

    AssetEntity? asset;
    try {
      asset = await CameraPicker.pickFromCamera(
        context,
        pickerConfig: CameraPickerConfig(
          enableRecording: true,
          onlyEnableRecording: true,
          // enableTapRecording: true,
          maximumRecordingDuration: Duration(seconds: maxDuration),
        ),
      );
    } catch (e) {
      var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'no auth'};
      _sendResponse(resp);
      return;
    }

    if (asset == null) {
      var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'cancel'};
      _sendResponse(resp);
      return;
    }

    final Directory tempDir = await getTemporaryDirectory();
    final Map<String, dynamic> result = await _handleSingleVideo(asset, tempDir);
    var resp = {
      'unique': unique,
      'cmd': cmd,
      'data': {
        'tempFiles': [result],
      },
      'errMsg': '',
    };
    _sendResponse(resp);
  }

  Future<Map<String, dynamic>> _handleSingleVideo(AssetEntity asset, Directory tempDir) async {
    final file = await asset.file;

    // 获取缩略图
    final data = await asset.thumbnailData;
    final thumbnailFile = await File(
      '${tempDir.path}/${DateTime.now().millisecondsSinceEpoch}.png',
    ).writeAsBytes(data!);

    return {
      "tempFilePath": '${Constant.localServerTempFileUrl}${file!.path}',
      "size": file.lengthSync(),
      "width": asset.width,
      "height": asset.height,
      "thumbTempFilePath": '${Constant.localServerTempFileUrl}${thumbnailFile.path}',
      "fileType": file.path.split('/').last.split('.').last,
    };
  }

  void setOrientationCmdFlag(bool orientationCmdFlag, String orientationCmdMessage) {
    emit(state.copyWith(orientationCmdFlag: orientationCmdFlag, orientationCmdMessage: orientationCmdMessage));
  }

  void getOrientation(BuildContext context) async {
    final Map<String, dynamic> data = json.decode(state.orientationCmdMessage);
    H5Message h5Message = H5Message.fromJson(data);

    setOrientationCmdFlag(false, '');

    final orientation = MediaQuery.of(context).orientation;

    var resp = {
      'unique': h5Message.unique,
      'cmd': h5Message.cmd,
      'data': {'orientation': orientation == Orientation.portrait ? "portrait" : "landscape"},
      'errMsg': '',
    };
    _sendResponse(resp);
  }

  void setWindowInfoCmdFlag(bool windowInfoCmdFlag, String windowInfoCmdMessage) {
    emit(state.copyWith(windowInfoCmdFlag: windowInfoCmdFlag, windowInfoCmdMessage: windowInfoCmdMessage));
  }

  void getWindowInfo(BuildContext context) async {
    final Map<String, dynamic> data = json.decode(state.windowInfoCmdMessage);
    H5Message h5Message = H5Message.fromJson(data);

    setWindowInfoCmdFlag(false, '');

    final mediaQuery = MediaQuery.of(context);
    final viewPadding = mediaQuery.viewPadding;
    final size = mediaQuery.size;
    final safeArea = mediaQuery.padding;
    final devicePixelRatio = mediaQuery.devicePixelRatio;

    // 计算安全区域坐标
    final safeAreaLeft = safeArea.left;
    final safeAreaRight = size.width - safeArea.right;
    final safeAreaTop = safeArea.top;
    final safeAreaBottom = size.height - safeArea.bottom;
    final safeAreaWidth = size.width - safeArea.horizontal;
    final safeAreaHeight = size.height - safeArea.vertical;

    final windowInfo = {
      'pixelRatio': devicePixelRatio,
      'screenWidth': size.width * devicePixelRatio,
      'screenHeight': size.height * devicePixelRatio,
      'windowWidth': size.width,
      'windowHeight': size.height,
      'statusBarHeight': viewPadding.top,
      'screenTop': 0, // Flutter中通常不使用此值,设为0
      'safeArea': {
        'left': safeAreaLeft,
        'right': safeAreaRight,
        'top': safeAreaTop,
        'bottom': safeAreaBottom,
        'width': safeAreaWidth,
        'height': safeAreaHeight,
      },
    };

    var resp = {'unique': h5Message.unique, 'cmd': h5Message.cmd, 'data': windowInfo, 'errMsg': ''};
    _sendResponse(resp);
  }

  @override
  Future<void> close() async {
    _server?.close();
    // _fluwx.removeSubscriber(_responseListener);

    await _playerService?.close();
    await _recorderService?.close();

    return super.close();
  }
}