import 'package:dart_json_mapper/dart_json_mapper.dart';
import 'package:get/get.dart';
import 'package:naiyouwl/app/common/SharedPreferencesUtil.dart';
import 'package:naiyouwl/app/common/constants.dart';
import 'package:naiyouwl/app/controller/controllers.dart';
import 'package:naiyouwl/app/data/model/UpdateVersion.dart';

import '../../../data/model/SysConfig.dart';
import '../../../network/api_service.dart';
import '../../../routes/app_pages.dart';

class WelcomeController extends GetxController {
  var isLoading = true.obs;
  var sysConfig = SysConfig().obs;
  var verModes = UpdateVersion().obs;
  var error = "".obs;
  var msgStatus = "".obs;
  var isUPdateVerion = false.obs;
  Future<void> fetchSysConfig() async {
    try {
      msgStatus.value = "获取系统配置";
      isLoading.value = true;
      sysConfig.value = await ApiService().fetchSysConfig(kSysConfig);
      await SharedPreferencesUtil().setString("sysconfig", JsonMapper.serialize(sysConfig.value));

      var token = await SharedPreferencesUtil().getString("token");
      if(token != null){
        Get.offNamed(Routes.HOME);
      }else {
        Get.offNamed(Routes.LOGIN);
      }


    } catch (e) {
      isLoading.value = false;
      msgStatus.value = "获取系统配置错误";
      controllers.global.handleApiError(e);
      error.value = controllers.global.errorMsg.value;
      controllers.global.errorMsg.value = ''; // Clear the error message immediately

    } finally {
      isLoading.value = false;
      msgStatus.value = "获取系统配置完成";
    }
  }
  Future<void> fetchUpdateVersion() async {
    try {
      msgStatus.value = "正在检测版本...";
      isLoading.value = true;
      var tag = "win10";
      if(GetPlatform.isMacOS){
        tag = "mac";
      }
      verModes.value = await ApiService().fetchUpdateVersion(kUpdateVersion,{"tag":tag,"appverion":kVersion});
      if(verModes.value.versionupdate != null){
        if(verModes.value.versionupdate == 1){
          msgStatus.value = "有更新...";
          isUPdateVerion.value = true;
        } else {
          isUPdateVerion.value = false;
          await fetchSysConfig();
        }
      }else{
        isUPdateVerion.value = false;
        await fetchSysConfig();
      }
    } catch (e) {
      isUPdateVerion.value = false;
      msgStatus.value = "获取版本数据失败";
      await fetchSysConfig();
      // controllers.global.handleApiError(e);
      // error.value = controllers.global.errorMsg.value;
      // controllers.global.errorMsg.value = ''; // Clear the error message immediately

    } finally {
      isLoading.value = false;
      msgStatus.value = "检测版本号完成";
    }
  }
  //app_update


  @override
  void onInit() {
    super.onInit();
    fetchUpdateVersion();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }


}
