import 'dart:async';

import 'package:odf/bean/login_bean.dart';
import 'package:odf/network/BaseEntity.dart';
import 'package:odf/network/NetworkConfig.dart';
import 'package:odf/network/RequestCenter.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginModel {
  StreamController streamController = StreamController.broadcast();

  ///登录
  Future<void> appLogin(username, password) async {
    RequestCenter.instance.request(NetworkConfig.appLogin, {
      "username": username,
      "password": password,
    }, (BaseEntity dataEntity) async {
      print("dataEntity==${dataEntity.msg}");

      if (dataEntity.code == 200) {
        LoginBean loginBean = LoginBean.fromJson(dataEntity.data);
        NetworkConfig.token = loginBean.jwt!.toString();
        NetworkConfig.userId = loginBean.userId!.toString();
        NetworkConfig.userName = loginBean.userName!.toString();

        final SharedPreferences prefs = await SharedPreferences.getInstance();
        await prefs.setString('token', loginBean.jwt!);

        print("dataEntity==成功");
        odf();
        streamController.sink.add({
          'code': "appLogin", //有数据
          'data': dataEntity.msg,
        });
      } else {
        streamController.sink.add({
          'code': "error", //
          'data': dataEntity.msg,
        });
      }
    }, (ErrorEntity errorEntity) {
      print("errorEntity==${errorEntity.msg}");
    });
  }

  ///检测权限
  Future<void> odf() async {
    RequestCenter.instance.requestGet(NetworkConfig.odf, {}, (BaseEntity dataEntity) {
      switch (dataEntity.code) {
        case 200:
          NetworkConfig.isPermission = true;
          streamController.sink.add({
            'code': "odf", //有数据
            'data': dataEntity.msg,
          });
          break;
        case 403:
          NetworkConfig.isPermission = false;
          streamController.sink.add({
            'code': "odf", //有数据
            'data': dataEntity.msg,
          });
          break;
        case 401:
          streamController.sink.add({
            'code': "login", //有数据
            'data': dataEntity.msg,
          });
          break;
        default:
          streamController.sink.add({
            'code': "error", //
            'data': dataEntity.msg,
          });
          break;
      }
    }, (ErrorEntity errorEntity) {
      print("errorEntity==${errorEntity.msg}");
    });
  }
}
