import 'dart:async';

import 'package:eitc_erm_dental_flutter/entity/version_info.dart';
import 'package:eitc_erm_dental_flutter/funcs.dart';
import 'package:eitc_erm_dental_flutter/http/api_service.dart';
import 'package:eitc_erm_dental_flutter/http/http.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'global_view_model.g.dart';

///连接状态
@riverpod
class DeviceConnectStatus extends _$DeviceConnectStatus {
  int _connectCode = -1;
  Timer? _timer;

  @override
  bool build(MethodChannel videoChannel) {
    return _connectCode == 1;
  }

  ///开始检查
  void startCheck() {
    if (_timer != null) {
      return;
    }
    logd("开始检查连接");
    _timer = Timer.periodic(const Duration(seconds: 1, milliseconds: 500), (_) {
      _getConnectStatus();
    });
    //一开始就获取一次
    _getConnectStatus();
  }

  ///停止检查
  void stopCheck() {
    logd("停止检查连接");
    _timer?.cancel();
    _timer = null;
  }

  ///读取连接状态
  void _getConnectStatus() async {
    int code = await videoChannel.invokeMethod("getConnectStatus");
    if (_connectCode != code) {
      _connectCode = code;
      state = _connectCode == 1;
    }
  }
}

///验证码
@riverpod
class Captcha extends _$Captcha {
  @override
  String build() {
    return "";
  }

  ///发送验证码
  Future<bool> sendCaptcha(String mobile) async {
    try {
      await Http.instance
          .request(ApiService(Http.instance.dio).sendCaptchaCode(mobile));
    } catch (e) {
      loge("发送验证码异常", error: e);
      return SynchronousFuture(false);
    }
    return SynchronousFuture(true);
  }

  ///检查验证码
  Future<bool> checkCaptcha(String captcha, String mobile) async {
    try {
      await Http.instance.request(
          ApiService(Http.instance.dio).checkCaptchaCode(captcha, mobile));
    } catch (e) {
      loge("检查验证码异常", error: e);
      return SynchronousFuture(false);
    }
    return SynchronousFuture(true);
  }
}

@riverpod
class CheckNewVersion extends _$CheckNewVersion {
  @override
  String build() {
    return "";
  }

  ///检查新版本
  Future<VersionInfo?> checkNewVersion(String type) async {
    try {
      return Http.instance
          .request(ApiService(Http.instance.dio).getVersion(type));
    } catch (e) {
      loge("检查版本异常", error: e);
    }
    return null;
  }
}
