import 'package:anchor_collect_flutter/models/cattle_resume_entity.dart';
import 'package:anchor_collect_flutter/models/immune_batch_detail_entity.dart';
import 'package:anchor_collect_flutter/models/immune_batch_entity.dart';
import 'package:flutter/foundation.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 '../../rfid/rfid_plugin.dart';
import '../../routes/routes.dart';
import '../../utils/dialog_utils.dart';
import '../../utils/dict_utils.dart';
import '../../utils/empty_utils.dart';
import '../../utils/sp_helper.dart';
import 'immune_batch_state.dart';

class ImmuneBatchLogic extends GetxController {
  final ImmuneBatchState state = ImmuneBatchState();

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

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

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

  ///初始化字典项
  refreshDictData() async {
    state.circleNo = await DictUtils.getDictName('zxgl_circle_list', state.entity.value.circleNo ?? '');
    state.immuneMethod =
    await DictUtils.getDictName('zxgl_immunebatch_immuneMethod', state.entity.value.immuneMethod ?? '');

    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.immuneBatchEntitys.put(state.entity.value),
    });

    ///如果是修改，先删除子表
    if (state.isModify) {
      await GlobalService.to.isar.writeTxn(() async => {
      await GlobalService.to.isar.immuneBatchDetailEntitys.filter()
          .immunebatchUnidEqualTo(state.entity.value.unid)
          .deleteAll(),
      });
    }

    ///保存免疫记录详情
    List<CattleResumeEntity> cEntity = await GlobalService.to.isar.cattleResumeEntitys
        .filter()
        .circleNoEqualTo(state.entity.value.circleNo)
        .unidIsNotEmpty()
        .findAll();

    if (cEntity != null) {
      if (kDebugMode) {
        print('cEntity!.length=${cEntity!.length}');
      }
      for (int i = 0; i < cEntity!.length; i++) {
        ImmuneBatchDetailEntity immuneBatchDetailEntity = ImmuneBatchDetailEntity();
        immuneBatchDetailEntity.unid = uuid
            .v4()
            .hashCode
            .toString() + uuid
            .v4()
            .hashCode
            .toString();
        immuneBatchDetailEntity.cattleresumeUnid = cEntity[i].unid;
        immuneBatchDetailEntity.immunebatchUnid = state.entity.value.unid;
        immuneBatchDetailEntity.deptId = SpHelper.getStorage(Config.SP_DEPT_ID);
        immuneBatchDetailEntity.uploadStatus = '0';
        await GlobalService.to.isar.writeTxn(() async =>
        {
          await GlobalService.to.isar.immuneBatchDetailEntitys.put(immuneBatchDetailEntity),
        });
      }
    }
    DialogUtils.showToast('保存免疫记录成功');
    DialogUtils.dismissDialog();
    Get.back(result: 'refresh');
  }

  Future<bool> checkRequiredFields() async {
    if (!EmptyUtils.isStrNotEmpty(state.entity.value.circleNo)) {
      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.immuneDate)) {
      DialogUtils.showToast('必须选择免疫日期');
      return true;
    }
    if (state.entity.value.immuneDosage == null || state.entity.value.immuneDosage == 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;
  }

// copyEntity(ImmuneBatchEntity 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;
// }
}
