import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:openim/core/controller/im_controller.dart';
import 'package:openim/pages/conversation/conversation_logic.dart';
import 'package:openim/routes/app_navigator.dart';
import 'package:openim_common/openim_common.dart';

import 'auth_api.dart';

class CompanyLoginLogic extends GetxController {
  final staffCtrl = TextEditingController();
  final pwdCtrl = TextEditingController();
  final obscure = true.obs;
  final submitting = false.obs;
  final staffError = RxnString();
  final pwdError = RxnString();
  final toast = RxnString();
  Timer? _toastTimer;

  final _auth = AuthApi();
  final _im = Get.find<IMController>();

  @override
  void onClose() {
    _toastTimer?.cancel();
    staffCtrl.dispose();
    pwdCtrl.dispose();
    super.onClose();
  }

  void toggleObscure() => obscure.toggle();

  void _showToast(String msg) {
    toast.value = msg;
    _toastTimer?.cancel();
    _toastTimer = Timer(const Duration(seconds: 2), () {
      toast.value = null;
    });
  }

  Future<void> submit() async {
    if (submitting.value) return;
    final staffNo = staffCtrl.text.trim();
    final password = pwdCtrl.text;
    staffError.value = staffNo.isEmpty ? '请输入工号' : null;
    pwdError.value = password.isEmpty ? '请输入密码' : null;
    if (staffNo.isEmpty || password.isEmpty) return;

    submitting.value = true;
    toast.value = null;
    try {
      final result = await _auth.login(
        staffNo: staffNo,
        password: password,
        platformID: IMUtils.getPlatform(),
      );
      final cert = LoginCertificate.fromJson({
        'userID': result.userID,
        'imToken': result.imToken,
        'chatToken': result.imToken,
      });
      await DataSp.putLoginCertificate(cert);
      await DataSp.putLoginAccount({'phoneNumber': staffNo, 'loginType': 2});
      await DataSp.putLoginType(2);
      Logger.print('company login : ${result.userID}');
      await _im.login(result.userID, result.imToken);
      final conversations = await ConversationLogic.getConversationFirstPage();
      Get.find<CacheController>().resetCache();
      AppNavigator.startMain(conversations: conversations);
    } on AuthException catch (e) {
      _showToast(e.network ? '网络异常，请稍后重试' : '工号或密码不正确');
    } catch (e, s) {
      Logger.print('company login e: $e $s');
      _showToast('网络异常，请稍后重试');
    } finally {
      submitting.value = false;
    }
  }
}
