import 'package:anchor_collect_flutter/models/weight_man_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 'weight_man_state.dart';

class WeightManLogic extends GetxController {
  final WeightManState state = WeightManState();

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

  @override
  void onReady() {
    Map<String, dynamic> arguments = Get.arguments;
    WeightManEntity? 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.weightManEntitys.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 (state.entity.value.weight == null ||state.entity.value.weight == 0) {
      DialogUtils.showToast('必须填写重量');
      return true;
    }
    if (!EmptyUtils.isStrNotEmpty(state.entity.value.wTime)) {
      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> checkWeightDate(String date) async {

    state.entity.value.wTime = date;
    List<WeightManEntity> checkEntity = await GlobalService.to.isar.weightManEntitys
        .filter()
        .cattleresumeIdEqualTo(state.entity.value.cattleresumeId)
        .and()
        .wTimeEqualTo(date)
        .findAll();
    if (checkEntity.isNotEmpty) {
      copyEntity(checkEntity[0]);
      DialogUtils.showWarningDialog('今日称重记录已存在，保存会修改记录');
    state.entity.value.weight = checkEntity[0].weight;
    }
    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(WeightManEntity 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.weight = formerEntity.weight;
    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;
  }
}
