import 'package:anchor_collect_flutter/models/medical_record_entity.dart';
import 'package:get/get.dart';
import 'package:isar/isar.dart';
import 'package:uuid/uuid.dart';

import '../../congifs.dart';
import '../../controllers/global_service.dart';
import '../../models/cattle_resume_entity.dart';
import '../../rfid/rfid_plugin.dart';
import '../../routes/routes.dart';
import '../../utils/dialog_utils.dart';
import '../../utils/empty_utils.dart';
import '../../utils/sp_helper.dart';
import 'medical_record_state.dart';

class MedicalRecordLogic extends GetxController {
  final MedicalRecordState state = MedicalRecordState();

  // 创建一个Uuid实例
  var uuid = Uuid();

  @override
  void onReady() {
    Map<String, dynamic> arguments = Get.arguments;
    MedicalRecordEntity? entity = arguments['entity'];
    CattleResumeEntity? cattleResumeEntity = arguments['cattleResumeEntity'];

    state.unid = uuid.v4().hashCode.toString();
    state.unid += uuid.v4().hashCode.toString();
    if (entity != null) {
      state.entity.value = entity;
      state.isModify = true;
      state.unid = state.entity.value.unid!;
    } else if (cattleResumeEntity != null) {
      state.entity.value.cattleresumeId = cattleResumeEntity.unid;
      state.entity.value.registrationNo = cattleResumeEntity.registrationNo;
      state.entity.value.individualNo = cattleResumeEntity.individualNo;
    }
    refreshDictData();
  }

  ///初始化字典项
  refreshDictData() async {
    // state.age = await DictUtils.getDictName('zxgl_performance_age', state.entity.value.age ?? '');
    // state.grade = await DictUtils.getDictName('zxgl_cattleresume_grade', state.entity.value.grade ?? '');

    update();
  }

  save() async {
    if (await checkRequiredFields()) {
      return;
    }
    DialogUtils.showLoadingDialog('保存中。。。');

    if (state.isModify) {
      state.entity.value.updateTime = DateTime.now().toString();
      state.entity.value.updateBy = SpHelper.getStorage(Config.SP_STR_USERNAME);
    } else {
      state.entity.value.unid = state.unid;
      state.entity.value.createTime = DateTime.now().toString();
      state.entity.value.createBy = SpHelper.getStorage(Config.SP_STR_USERNAME);
    }
    state.entity.value.deptId = SpHelper.getStorage(Config.SP_DEPT_ID);
    state.entity.value.uploadStatus = '0';

    ///保存诊疗记录
    await GlobalService.to.isar.writeTxn(() async => {
      await GlobalService.to.isar.medicalRecordEntitys.put(state.entity.value),
    });
    DialogUtils.showToast('保存诊疗记录成功');
    DialogUtils.dismissDialog();
    Get.back(result: 'refresh');
  }

  Future<bool> checkRequiredFields() async {
    if (!EmptyUtils.isStrNotEmpty(state.entity.value.cattleresumeId)) {
      DialogUtils.showToast('高频耳标或者可视耳标无效');
      return true;
    }
    // if (!EmptyUtils.isStrNotEmpty(state.entity.individualNo)) {
    //   DialogUtils.showToast('必须填写可视耳标');
    //   return true;
    // }
    // if (!EmptyUtils.isStrNotEmpty(state.entity.photoPath) && !EmptyUtils.isStrNotEmpty(state.photoPath)) {
    //   DialogUtils.showToast('必须上传牛只拍照');
    //   return true;
    // }
    // if (!EmptyUtils.isStrNotEmpty(state.entity.circleNo)) {
    //   DialogUtils.showToast('必须选择圈舍');
    //   return true;
    // }
    // if (!EmptyUtils.isStrNotEmpty(state.entity.raiseType)) {
    //   DialogUtils.showToast('必须选择饲养类型');
    //   return true;
    // }
    if (!EmptyUtils.isStrNotEmpty(state.entity.value.treatDate)) {
      DialogUtils.showToast('必须选择诊疗日期');
      return true;
    }
    if (state.entity.value.drugNumber == null ||state.entity.value.drugNumber == 0) {
      DialogUtils.showToast('必须填写用药数量');
      return true;
    }
    // if (state.entity.birthHeavy == null || state.entity.birthHeavy == 0) {
    //   DialogUtils.showToast('必须填写出生重量');
    //   return true;
    // }
    // if (!EmptyUtils.isStrNotEmpty(state.entity.sex)) {
    //   DialogUtils.showToast('必须选择性别');
    //   return true;
    // }
    // if (!EmptyUtils.isStrNotEmpty(state.entity.status)) {
    //   DialogUtils.showToast('必须选择状态');
    //   return true;
    // }
    // if (!EmptyUtils.isStrNotEmpty(state.entity.colour)) {
    //   DialogUtils.showToast('必须填写犊牛毛色');
    //   return true;
    // }
    return false;
  }

  ///扫描高频耳标
  scanRfid() {
    if (!Config.isConnect) {
      Get.toNamed(AppRoute.SETTING);
      return;
    }
    if (!RfidPlugin.isInventory) {
      RfidPlugin.startInventory((epc, agrs1) {
        RfidPlugin.stopInventory();
        print('why:epc:$epc');
        RfidPlugin.isInventory = false;
        queryCattleResume(0, epc);
      });
    }
  }

  ///查询标签信息，0高频，1可视
  queryCattleResume(int type, String queryNo) async {
    CattleResumeEntity? cattleInfo;
    state.entity.value.registrationNo = '';
    state.entity.value.individualNo = '';
    state.entity.value.cattleresumeId = '';
    switch (type) {
      case 0:
        state.entity.value.registrationNo = queryNo;
        cattleInfo =
        await GlobalService.to.isar.cattleResumeEntitys.filter().registrationNoEqualTo(queryNo).findFirst();
        break;
      case 1:
        state.entity.value.individualNo = queryNo;
        cattleInfo = await GlobalService.to.isar.cattleResumeEntitys.filter().individualNoEqualTo(queryNo).findFirst();
        break;
    }
    if (cattleInfo == null) {
      DialogUtils.showToast('未查询到标签信息');
    } else {
      state.entity.value.registrationNo = cattleInfo.registrationNo;
      state.entity.value.individualNo = cattleInfo.individualNo;
      state.entity.value.cattleresumeId = cattleInfo.unid;
    }
    update();
  }

  copyEntity(MedicalRecordEntity formerEntity) {
    state.entity.value.id = formerEntity.id;
    state.entity.value.unid = formerEntity.unid;
    state.entity.value.cattleresumeId = formerEntity.cattleresumeId;
    state.entity.value.registrationNo = formerEntity.registrationNo;
    state.entity.value.individualNo = formerEntity.individualNo;
    state.entity.value.treatDate = formerEntity.treatDate;
    state.entity.value.treatPersonnel = formerEntity.treatPersonnel;
    state.entity.value.causeOf = formerEntity.causeOf;
    state.entity.value.drugName = formerEntity.drugName;
    state.entity.value.specifications = formerEntity.specifications;
    state.entity.value.drugMethods = formerEntity.drugMethods;
    state.entity.value.drugNumber = formerEntity.drugNumber;
    state.entity.value.results = formerEntity.results;
    state.entity.value.uploadStatus = formerEntity.uploadStatus;
    state.entity.value.deptId = formerEntity.deptId;
    state.entity.value.searchValue = formerEntity.searchValue;
    state.entity.value.createBy = formerEntity.createBy;
    state.entity.value.createTime = formerEntity.createTime;
    state.entity.value.updateBy = formerEntity.updateBy;
    state.entity.value.updateTime = formerEntity.updateTime;
    state.entity.value.remark = formerEntity.remark;
  }
}
