import 'package:fis_jsonrpc/rpc.dart';
import 'package:get/get.dart';
import 'package:idread/model/id_card_info_model.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:idread/idread.dart';

class CardReaderController extends GetxController {
  CardReaderController();

  bool isCardReaderConnected = false; // 是否连接读卡器

  _initData() async {
    bool result = await Idread.init();
    if (result) {
      bool start = await Idread.startRead();
      if (start) {
        Idread.dataStreamListen((data) {
          if (data is IdCardInfoModel) {
            onReadInfo(data);
          }
        });
      }
    }
    isCardReaderConnected = result;
    update(["card_reader"]);
  }

  void checkReader() async {
    bool result = await Idread.init();
    if (result) {
      bool start = await Idread.startRead();
      if (start) {
        Idread.dataStreamListen((data) {
          if (data is IdCardInfoModel) {
            onReadInfo(data);
          }
        });
      }
    } else {
      PromptBox.toast("未检测到读卡器，请检查连接后重试");
    }
    isCardReaderConnected = result;
    update(["card_reader"]);
  }

  /// 读取到数据的回调
  void onReadInfo(IdCardInfoModel data) {
    final result = CardReaderResult(
      success: true,
      cardNo: data.idCard,
      name: data.peopleName,
      nation: data.people,
      gender: data.sex == '男' ? GenderEnum.Male : GenderEnum.Female,
      birthday: DateTime.parse(data.birthDay),
      address: data.address,
    );
    Get.back(
      result: result,
    );
  }

  Future<void> unInit() async {
    await Idread.unInit();
  }
  // @override
  // void onInit() {
  //   super.onInit();
  // }

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

  @override
  void onClose() {
    super.onClose();
    Idread.stopRead();
    unInit();
  }
}

class CardReaderResult {
  bool success;

  /// 身份证号
  String cardNo;

  /// 姓名
  String name;

  /// 性别
  GenderEnum gender;

  /// 民族
  String nation;

  /// 出生日期
  DateTime birthday;

  /// 地址
  String address;

  CardReaderResult({
    required this.success,
    required this.cardNo,
    required this.name,
    required this.gender,
    required this.nation,
    required this.birthday,
    required this.address,
  });
}
