import 'package:al_downloader/al_downloader.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wgshare/common/models/common/base_structure_result.dart';
import 'package:wgshare/common/mixins/request_tool_mixin.dart';
import 'package:wgshare/common/store/business_store.dart';
import 'package:wgshare/common/store/user_store.dart';
import 'package:wgshare/utils/storage.dart';

import '../../common/models/meeting_room_item.dart';
import '../../routes/app_routes.dart';
import '../../utils/permission/PermissionService.dart';
import '../../utils/toast_utils.dart';
import '../../view/public_dialog.dart';
import '../../view/upgrade/loadJson/hide_load_network_json.dart';
import 'home_state.dart';

class HomeLogic extends GetxController with RequestToolMixin {

  final HomeState state = HomeState();

  @override
  void onInit() {
    super.onInit();
    /// 检查更新（后台）
    HideCheckVersion hideCheckVersion = HideCheckVersion();
    hideCheckVersion.doHttpHideCheckVersion();
    /// 权限
    /*PermissionService.checkPermission(permissionList: [Permission.manageExternalStorage]).then((value){
      if(value == true){
        hideCheckVersion.doHttpHideCheckVersion();
      }else{
        if(null == BusinessStore.to.isRefuseHomeCheckPermission || BusinessStore.to.isRefuseHomeCheckPermission == false){
          publicDialog(Get.context!,
              hideCancelBtn: true,
              title: '请求权限说明',
              describe:
              'APP需要获取您的文件访问权限，用以确保新版本下载后可以正常安装。',
              leftBtnStr: '拒绝',
              rightBtnStr: '同意',
              leftBtnCallback: () {
                BusinessStore.to.setIsRefuseHomeCheckPermission(true);
              }, rightBtnCallback: () {
                PermissionService.requestStoragePermissions().then((value){
                  if(value == true){
                    hideCheckVersion.doHttpHideCheckVersion();
                  }
                });
              });
        }else{
          hideCheckVersion.doHttpHideCheckVersion();
        }
      }
    });*/

    doHttpGetMeetingRoomList(state.pageIndex.value, state.pageSize.value);
  }

  @override
  void onClose() {
    super.onClose();
    state.refreshController.dispose();
  }

  /// 获取会议列表
  Future<void> doHttpGetMeetingRoomList(int pageIndex, int pageSize) async {
    debugPrint("wgs输出===：token：${UserStore.to.token}");
    BaseStructureResult<MeetingRoomItem> res = await getClient()
        .getMeetingRoomList(pageIndex, pageSize);
    if (null != res.data) {
      if (state.pageIndex == 1) {
        state.meetingRooms.value = res.data!.items;
        state.totalPage.value = res.data!.totalPage;
        state.total.value = res.data!.total;
        state.refreshController.refreshCompleted(resetFooterState: true);
      } else {
        if (state.pageIndex.value < state.totalPage.value) {
          state.meetingRooms.value.addAll(res.data!.items);
          state.refreshController.loadComplete();
        } else {
          state.refreshController.loadNoData();
        }
      }
    }
  }

  /// 下拉刷新
  void onRefresh() {
    state.pageIndex.value = 1;
    doHttpGetMeetingRoomList(state.pageIndex.value, state.pageSize.value);
  }

  /// 上滑加载更多
  void onLoading() {
    state.pageIndex.value += 1;
    doHttpGetMeetingRoomList(state.pageIndex.value, state.pageSize.value);
  }

  /// 返回键退出
  bool closeOnConfirm(BuildContext context) {
    DateTime now = DateTime.now();
    // 物理键，两次间隔大于4秒, 退出请求无效
    if (state.currentBackPressTime == null ||
        now.difference(state.currentBackPressTime!) >
            const Duration(seconds: 4)) {
      state.currentBackPressTime = now;
      ToastUtils.showInfo("再按一次退出");
      return false;
    }
    // 退出请求有效
    state.currentBackPressTime = null;
    return true;
  }

  /// 进入会议室
  void gotoMeetingRoom(BuildContext context, int index) {
    PermissionService.checkPermission(
        permissionList: [Permission.microphone, Permission.camera]).then((
        value) {
      if (value == true) {
        Get.back();
        Get.toNamed(Routes.meetingMainPage,
            arguments: {
              "roomNumber": state.meetingRooms.value[index].roomNum
            });
      } else {
        publicDialog(
            context,
            hideCancelBtn: true,
            title: '请求权限说明',
            describe: '进入会议室需要获取您的麦克风以及摄像头权限，用以确保能够正常参会发言。',
            leftBtnStr: '拒绝',
            rightBtnStr: '同意',
            leftBtnCallback: () {
              Get.back();
              Get.toNamed(Routes.meetingMainPage,
                  arguments: {
                    "roomNumber": state.meetingRooms.value[index].roomNum
                  });
            },
            rightBtnCallback: () {
              PermissionService.requestPermissions().then((value) {
                if (value == true) {
                  Get.back();
                  Get.toNamed(Routes.meetingMainPage,
                      arguments: {
                        "roomNumber": state.meetingRooms.value[index].roomNum
                      });
                }
              });
            }
        );
      }
    });
  }
}