import 'package:get/get.dart';
import 'package:package_info/package_info.dart';
import 'package:r_upgrade/r_upgrade.dart';

import '../../api/HttpUtils.dart';
import '../../api/apis.dart';
import '../../congifs.dart';
import '../../routes/routes.dart';
import '../../utils/dialog_utils.dart';
import '../../utils/sp_helper.dart';
import 'mine_state.dart';

class MineLogic extends GetxController {
  final MineState state = MineState();


  @override
  void onInit() {
    state.deptName = SpHelper.getStorage(Config.SP_DEPT_NAME, '');
    update();
  }

  logout(){
    SpHelper.putStorage(Config.SP_STR_USERNAME, '');
    SpHelper.putStorage(Config.SP_STR_PASSWORD, '');
    SpHelper.putStorage(Config.SP_STR_TOKEN, '');
    SpHelper.putStorage(Config.SP_DEPT_ID, '');
    SpHelper.putStorage(Config.SP_DEPT_NAME, '');
    SpHelper.putStorage(Config.SP_DEPT_ROLE, false);
    Config.isOnLine = false;
    Get.offNamed(AppRoute.LOGIN);
  }

  checkUpdate() async {

    ///拉取版本信息
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String buildNumber = packageInfo.buildNumber;

    ///检查更新
    HttpUtils<int>()
      ..get()
      ..setUrl(APIS.get_version)
      ..onResponse((response) {
        if (buildNumber != response.toString()) {
          // DialogUtils.showToast('最新版本$response');
          DialogUtils.showLoadingDialog('正在下载新版本');
          upgrade();
        } else {
          DialogUtils.showToast('已经是最新版本');
        }
        //  var _appName = packageInfo.appName;
        // var _packageName = packageInfo.packageName;
      })
      ..onError((msg, code) {
        // DialogUtils.dismissDialog();
      })
      ..build();
  }

  ///下载app
  void upgrade() async {
    int appId = await RUpgrade.upgrade(
      '${APIS.baseUrl}/api/download?type=Flutter',
      fileName: 'anchor_collect_flutter.apk',
      installType: RUpgradeInstallType.normal,
    ) ??
        0;
    bool isSuccess = await RUpgrade.install(appId) ?? false;
  }

}
