import 'dart:async';
import 'dart:io';

import 'package:flutter/services.dart';
import 'package:get/get_utils/src/platform/platform.dart';
import 'package:injectable/injectable.dart';
import 'package:location/base/base_controller.dart';
import 'package:location/data/api/response/member_status_response.dart';
import 'package:location/data/repositories/account_repository.dart';
import 'package:location/dialog/agreement_dialog.dart';
import 'package:location/module/main/main_page.dart';
import 'package:location/module/member/activity/member_activity_page.dart';
import 'package:location/sdk/umeng/umeng_helper.dart';
import 'package:location/utils/date_util.dart';

import '../../data/consts/error_code.dart';
import '../../utils/async_util.dart';
import '../../utils/http_handler.dart';
import '../../utils/privacy_compliance.dart';

@injectable
class SplashController extends BaseController {
  final splashDelayedTime = 2;

  DateTime? splashStartTime;

  SplashController();

  @override
  void onReady() {
    final isAgreePrivacy = PrivacyCompliance.isAgreePrivacyPolicy();
    if (isAgreePrivacy) {
      _doSplashTask();
    } else {
      AgreementDialog.show(cancelClick: () {
        exitApp();
      }, sureClick: () async {
        await _agreePrivacy();
        _doSplashTask();
      });
    }
  }

  void _doSplashTask() async {
    //获取用户会员信息
    splashStartTime = DateUtil.getNow();
    AsyncUtil.retry(() => AccountRepository.getInstance().getMemberStatus(),
        Duration(seconds: 1), timeout: Duration(seconds: 6), maxRetry: 6,
        predicate: (error) {
      if (error is ServerErrorException) {
        return error.code != ErrorCode.noLoginError;
      }
      return true;
    }).then((info) {
      _memberCheckNextStep(response: info);
    }).catchError((error) {
      _memberCheckNextStep();
    });
  }

  void _memberCheckNextStep({MemberStatusResponse? response}) {
    final endTime = DateUtil.getNow();
    final duration = endTime.difference(splashStartTime!);
    final splashDelayedTime = this.splashDelayedTime * 1000;

    final int remainTimeMilliseconds =
        duration.inMilliseconds < splashDelayedTime
            ? splashDelayedTime - duration.inMilliseconds
            : 0;
    if (response != null && !response.expired) {
      _goMain(Duration(milliseconds: remainTimeMilliseconds));
    } else {
      _goMemberActivity(Duration(milliseconds: remainTimeMilliseconds));
    }
  }

  void _goMemberActivity(Duration delayTime) {
    Timer(delayTime, () {
      MemberActivityPage.start(isOffAll: true);
    });
  }

  void _goMain(Duration delayTime, {Map<String, dynamic>? arguments}) {
    Timer(delayTime, () {
      MainPage.start(arguments: arguments);
    });
  }

  void exitApp() {
    if (GetPlatform.isAndroid) {
      SystemNavigator.pop();
    } else {
      exit(0);
    }
  }

  _agreePrivacy() async {
    await UmengHelper.setPolicyGrantResult(true);
    await PrivacyCompliance.setPrivacyPolicy(true);
  }
}
