import 'package:anchor_collect_flutter/congifs.dart';
import 'package:anchor_collect_flutter/controllers/global_service.dart';
import 'package:anchor_collect_flutter/utils/dialog_utils.dart';
import 'package:anchor_collect_flutter/utils/empty_utils.dart';
import 'package:anchor_collect_flutter/utils/sp_helper.dart';
import 'package:camera/camera.dart';
import 'package:get/get.dart';
import 'package:isar/isar.dart';
import 'package:uuid/uuid.dart';

import '../../models/cattle_resume_entity.dart';
import '../../models/value_model.dart';
import '../../rfid/rfid_plugin.dart';
import '../../routes/routes.dart';
import '../../utils/compress_util.dart';
import '../../utils/dict_utils.dart';
import 'cattle_resume_state.dart';

class CattleResumeLogic extends GetxController {
  final CattleResumeState state = CattleResumeState();

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

  @override
  void onReady() {
    var entity = Get.arguments;

    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!;
    }
    refreshDictData();

    initCamera();
  }

  initCamera() {
    // 初始化 CameraController
    if (Config.cameras != null && Config.cameras[0] != null) {
      Config.controller = CameraController(Config.cameras[0], ResolutionPreset.max);
      Config.controller.initialize().then(
            (_) {},
            onError: (e) => {
              print('why:CameraError:$e'),
            },
          );
    }
  }

  ///初始化字典项
  refreshDictData() async {
    state.photoPath = state.entity.value.photoPath ?? '';
    state.raiseType = await DictUtils.getDictName('zxgl_raiseType', state.entity.value.raiseType ?? '');
    state.raiseVarieties =
        await DictUtils.getDictName('zxgl_cattle_raiseVarieties', state.entity.value.raiseVarieties ?? '');
    state.sex = await DictUtils.getDictName('zxgl_cattleresume_sex', state.entity.value.sex ?? '');
    state.birthDifficulty =
        await DictUtils.getDictName('zxgl_cattleresume_birthDifficulty', state.entity.value.birthDifficulty ?? '');
    state.isTwins = await DictUtils.getDictName('sys_yes_no', state.entity.value.isTwins ?? '');
    // state.circleNo = await DictUtils.getDictName('zxgl_circle_list', state.entity.value.circleNo ?? '');
    state.health = await DictUtils.getDictName('zxgl_cattleresume_health', state.entity.value.health ?? '');
    state.status = await DictUtils.getDictName('zxgl_cattleresume_status', state.entity.value.status ?? '');

    update();
  }

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

  forwardBegats() {
    if (state.entity.value == null) {
      DialogUtils.showToast('请扫描或填写耳标');
      return;
    }
    Map<String, dynamic> params = {};
    params.putIfAbsent("entity", () => state.entity.value);
    Get.toNamed(AppRoute.BEGATS_RECORD, arguments: params);
  }

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

    ///压缩图片
    if (EmptyUtils.isStrNotEmpty(state.photoPath) && state.isCamera) {
      XFile? compressFile =
          await CompressUtil.compressPathWithXFile(state.photoPath, state.entity.value.unid.toString());
      if (compressFile != null) {
        state.entity.value.photoPath = compressFile!.path;
      } else {
        DialogUtils.showWarningDialog('拍照压缩失败');
      }
    }
    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;
      //新增保存的时候添加上默认圈舍
      List<ValueModel> cicleS = await DictUtils.getDictList('zxgl_circle_list');
      if (EmptyUtils.isListNotEmpty(cicleS)) {
        state.entity.value.circleNo = cicleS[0].value;
      }
      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.cattleResumeEntitys.put(state.entity.value),
        });
    state.isCamera = false;
    DialogUtils.showToast('保存基础信息成功');
    DialogUtils.dismissDialog();
    Get.back(result: 'refresh');
  }

  Future<bool> checkRequiredFields() async {
    // if (!EmptyUtils.isStrNotEmpty(state.entity.value.registrationNo)) {
    //   DialogUtils.showToast('必须扫描高频耳标');
    //   return true;
    // }
    if (!EmptyUtils.isStrNotEmpty(state.entity.value.individualNo)) {
      DialogUtils.showToast('必须填写可视耳标');
      return true;
    }
    if (!EmptyUtils.isStrNotEmpty(state.entity.value.photoPath) && !EmptyUtils.isStrNotEmpty(state.photoPath)) {
      DialogUtils.showToast('必须上传牛只拍照');
      return true;
    }
    // if (!EmptyUtils.isStrNotEmpty(state.entity.value.circleNo)) {
    //   DialogUtils.showToast('必须选择圈舍');
    //   return true;
    // }
    if (!EmptyUtils.isStrNotEmpty(state.entity.value.raiseType)) {
      DialogUtils.showToast('必须选择饲养类型');
      return true;
    }
    if (!EmptyUtils.isStrNotEmpty(state.entity.value.raiseVarieties)) {
      DialogUtils.showToast('必须选择饲养品种');
      return true;
    }
    if (!EmptyUtils.isStrNotEmpty(state.entity.value.birthdate)) {
      DialogUtils.showToast('必须选择出生日期');
      return true;
    }
    if (state.entity.value.birthHeavy == null || state.entity.value.birthHeavy == 0) {
      DialogUtils.showToast('必须填写出生重量');
      return true;
    }
    if (!EmptyUtils.isStrNotEmpty(state.entity.value.sex)) {
      DialogUtils.showToast('必须选择性别');
      return true;
    }
    if (!EmptyUtils.isStrNotEmpty(state.entity.value.status)) {
      DialogUtils.showToast('必须选择状态');
      return true;
    }
    // if (!EmptyUtils.isStrNotEmpty(state.entity.colour)) {
    //   DialogUtils.showToast('必须填写犊牛毛色');
    //   return true;
    // }

    // if (await GlobalService.to.isar.cattleResumeEntitys
    //         .filter()
    //         .not()
    //         .unidEqualTo(state.entity.value.unid)
    //         .and()
    //         .registrationNoEqualTo(state.entity.value.registrationNo)
    //         .count() >
    //     0) {
    //   DialogUtils.showToast('高频耳标已使用');
    //   return true;
    // }

    if (await GlobalService.to.isar.cattleResumeEntitys
            .filter()
            .not()
            .unidEqualTo(state.entity.value.unid)
            .and()
            .individualNoEqualTo(state.entity.value.individualNo)
            .count() >
        0) {
      DialogUtils.showToast('可视耳标已使用');
      return true;
    }

    return false;
  }

  forward(String forwardType) {
    if (EmptyUtils.isStrNotEmpty(state.entity.value.unid)) {
      Map<String, dynamic> params = {};
      params.putIfAbsent("cattleResumeEntity", () => state.entity.value);
      switch (forwardType) {
        case '性能测定':
          Get.offNamed(AppRoute.PERFORMANCE_LIST, arguments: params);
          break;
        case '诊疗记录':
          Get.offNamed(AppRoute.MEDICAL_RECORD_LIST, arguments: params);
          break;
        case '配种记录':
          Get.offNamed(AppRoute.BREEDING_RECORD_LIST, arguments: params);
          break;
        case '免疫记录':
          Get.offNamed(AppRoute.IMMUNE_BATCH_LIST, arguments: params);
          break;
        case '称重记录':
          Get.offNamed(AppRoute.WEIGHT_MAN_LIST, arguments: params);
          break;
      }
    } else {
      DialogUtils.showToast('基础信息未创建');
    }
  }

  @override
  void dispose() {
    Config.controller.dispose();
  }
}
