import 'package:anchor_collect_flutter/api/HttpUtils.dart';
import 'package:anchor_collect_flutter/congifs.dart';
import 'package:anchor_collect_flutter/models/login_entity.dart';
import 'package:anchor_collect_flutter/models/user_model.dart';
import 'package:anchor_collect_flutter/routes/routes.dart';
import 'package:anchor_collect_flutter/utils/dialog_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:package_info/package_info.dart';
import 'package:r_upgrade/r_upgrade.dart';

import '../../api/RequestClient.dart';
import '../../api/apis.dart';
import '../../controllers/global_service.dart';
import '../../models/dict_entity.dart';
import '../../utils/list_utils.dart';
import '../../utils/sp_helper.dart';

class LoginLogic extends GetxController {
  late RxInt groupValue;

  RxString versionStr = '1.0.0'.obs;

  RxBool isObscure = true.obs;

  int appId = 0;

  LoginLogic() {
    groupValue = 0.obs;

    nameController.text = '13932316000';
    passwordController.text = '123456';
    // nameController.text = '15047917803';
    // passwordController.text = 'Tpsq7803*';
  }

  login() async {
    if (nameController.text.isEmpty || passwordController.text.isEmpty) {
      DialogUtils.showWarningDialog('请输入用户名和密码!');
      return;
    }
    Config.isOnLine ? onLine() : offLine();
  }

  offLine() {
    if (SpHelper.getStorage(Config.SP_STR_USERNAME, '') == '' ||
        SpHelper.getStorage(Config.SP_STR_PASSWORD, '') == '') {
      DialogUtils.showWarningDialog('第一次请联机登录!');
      return;
    }
    if (nameController.text == SpHelper.getStorage(Config.SP_STR_USERNAME) &&
        passwordController.text == SpHelper.getStorage(Config.SP_STR_PASSWORD)) {
      Get.offNamed(AppRoute.MAIN);
    } else {
      DialogUtils.showWarningDialog('用户名或密码错误！');
    }
  }

  onLine() {
    Map<String, String> map = {}; //参数
    map.putIfAbsent('username', () => nameController.text);
    map.putIfAbsent('password', () => passwordController.text);
    // FormData formData = FormData.(map);
    HttpUtils<LoginEntity>()
      ..post()
      ..setUrl(APIS.login_interface)
      ..setQueryParameters(map)
      ..showLoading()
      ..onResponse((response) async {
        if (kDebugMode) {
          print('登录成功');
        }
        SpHelper.putStorage(Config.SP_STR_USERNAME, nameController.text);
        SpHelper.putStorage(Config.SP_STR_PASSWORD, passwordController.text);
        SpHelper.putStorage(Config.SP_STR_TOKEN, response!.token);
        SpHelper.putStorage(Config.SP_DEPT_ID, response!.user.deptId);
        await GlobalService.to.isar.writeTxn(() async {
          await GlobalService.to.isar.userModels.put(response!.user);
        });
        getDictList();
      })
      ..onError((msg, code) {
        // DialogUtils.showWarningDialog('登录失败:$msg');
        DialogUtils.showToast('登录失败');
        return;
      })
      ..build();
  }

  getDictList() async {
    ///先清除一下
    await GlobalService.to.isar.writeTxn(() async => {
          await GlobalService.to.isar.dictEntitys.clear(),
        });
    HttpUtils<DictEntity>()
      ..post()
      ..setUrl(APIS.login_get_dict)
      ..showLoading()
      ..setIsList()
      ..onResponseList((response) async {
        if (kDebugMode) {
          print('字典项数量：${response.length}');
        }
        await GlobalService.to.isar.writeTxn(() async => {
              await GlobalService.to.isar.dictEntitys.putAll(ListUtils.removeNullValues<DictEntity>(response)),
              Get.offNamed(AppRoute.MAIN),
            });
      })
      ..onError((msg, code) {
        DialogUtils.showWarningDialog('获取字典失败:$msg');
      })
      ..build();
  }

  loginTypeChanged(int position) {
    groupValue.value = position;

    if (groupValue.value == 0) {
      Config.isOnLine = false;
    } else if (groupValue.value == 1) {
      Config.isOnLine = true;
    }
    update();
  }

  TextEditingController nameController = TextEditingController();
  TextEditingController passwordController = TextEditingController();

  @override
  Future<void> onInit() async {

    ///拉取版本信息
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    versionStr.value = packageInfo.version;
    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 {
    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;
  }
}
