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 '../../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();
    if (entity != null) {
      state.entity = entity;
      state.isModify = true;
      state.unid = state.entity.unid!;
      refreshDictData();
    }

    initCamera();
  }

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

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

    update();
  }

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

    ///压缩图片
    if (EmptyUtils.isStrNotEmpty(state.photoPath) && state.isCamera) {
      XFile? compressFile = await CompressUtil.compressPathWithXFile(state.photoPath, state.entity.unid.toString());
      if (compressFile != null) {
        state.entity.photoPath = compressFile!.path;
      } else {
        DialogUtils.showWarningDialog('拍照压缩失败');
      }
    }
    if (state.isModify) {
      state.entity.updateTime = DateTime.now().toString();
      state.entity.updateBy = SpHelper.getStorage(Config.SP_DEPT_ID);
    } else {
      state.entity.unid = state.unid;
      state.entity.createTime = DateTime.now().toString();
      state.entity.createBy = SpHelper.getStorage(Config.SP_DEPT_ID);
    }
    state.entity.uploadStatus = '0';

    ///保存基础信息
    await GlobalService.to.isar.writeTxn(() async => {
          await GlobalService.to.isar.cattleResumeEntitys.put(state.entity),
          state.isCamera = false,
          DialogUtils.showToast('保存基础信息成功'),
          DialogUtils.dismissDialog(),
          Get.back(),
        });
  }

  Future<bool> checkRequiredFields() async {
    if (!EmptyUtils.isStrNotEmpty(state.entity.registrationNo)) {
      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.raiseVarieties)) {
      DialogUtils.showToast('必须选择饲养品种');
      return true;
    }
    if (!EmptyUtils.isStrNotEmpty(state.entity.birthdate)) {
      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;
    // }

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

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

    return false;
  }

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