import 'package:anchor_collect_flutter/generated/json/performance.g.dart';
import 'package:anchor_collect_flutter/models/cattle_resume_entity.dart';
import 'package:anchor_collect_flutter/models/performance.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 'performance_state.dart';

class PerformanceLogic extends GetxController {
  final PerformanceState state = PerformanceState();

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

  @override
  void onReady() {
    Map<String, dynamic> arguments = Get.arguments;
    PerformanceEntity? 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.performanceEntitys.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.age)) {
      DialogUtils.showToast('必须选择年龄');
      return true;
    }
    if (!EmptyUtils.isStrNotEmpty(state.entity.value.measureDate)) {
      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;
  }

  ///是否有此年龄记录检查
  Future<void> checkAge(String key, String value) async {
    List<PerformanceEntity> performanceEntitys = await GlobalService.to.isar.performanceEntitys
        .filter()
        .cattleresumeIdEqualTo(state.entity.value.cattleresumeId)
        .and()
        .ageEqualTo(value)
        .findAll();
    if (performanceEntitys.isNotEmpty) {
      copyEntity(performanceEntitys[0]);
      DialogUtils.showWarningDialog('改畜龄记录已存在，保存会修改记录');
    }
    state.age = key;
    state.entity.value.age = value;
    update();
  }

  ///扫描高频耳标
  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(PerformanceEntity formerEntityEntity) {
    state.entity.value.id = formerEntityEntity.id;
    state.entity.value.unid = formerEntityEntity.unid;
    state.entity.value.cattleresumeId = formerEntityEntity.cattleresumeId;
    state.entity.value.registrationNo = formerEntityEntity.registrationNo;
    state.entity.value.individualNo = formerEntityEntity.individualNo;
    state.entity.value.fatherReg = formerEntityEntity.fatherReg;
    state.entity.value.motherReg = formerEntityEntity.motherReg;
    state.entity.value.age = formerEntityEntity.age;
    state.entity.value.measureDate = formerEntityEntity.measureDate;
    state.entity.value.height = formerEntityEntity.height;
    state.entity.value.length = formerEntityEntity.length;
    state.entity.value.bust = formerEntityEntity.bust;
    state.entity.value.weight = formerEntityEntity.weight;
    state.entity.value.chestWidth = formerEntityEntity.chestWidth;
    state.entity.value.chestDeep = formerEntityEntity.chestDeep;
    state.entity.value.waistWidth = formerEntityEntity.waistWidth;
    state.entity.value.crossWidth = formerEntityEntity.crossWidth;
    state.entity.value.guanWei = formerEntityEntity.guanWei;
    state.entity.value.eyeMuscleArea = formerEntityEntity.eyeMuscleArea;
    state.entity.value.grade = formerEntityEntity.grade;
    state.entity.value.hairLength = formerEntityEntity.hairLength;
    state.entity.value.hairFineness = formerEntityEntity.hairFineness;
    state.entity.value.shearing = formerEntityEntity.shearing;
    state.entity.value.backWidth = formerEntityEntity.backWidth;
    state.entity.value.breedRes = formerEntityEntity.breedRes;
    state.entity.value.health = formerEntityEntity.health;
    state.entity.value.immune = formerEntityEntity.immune;
    state.entity.value.uploadStatus = formerEntityEntity.uploadStatus;
    state.entity.value.deptId = formerEntityEntity.deptId;
    state.entity.value.searchValue = formerEntityEntity.searchValue;
    state.entity.value.createBy = formerEntityEntity.createBy;
    state.entity.value.createTime = formerEntityEntity.createTime;
    state.entity.value.updateBy = formerEntityEntity.updateBy;
    state.entity.value.updateTime = formerEntityEntity.updateTime;
    state.entity.value.remark = formerEntityEntity.remark;
  }
}
