import 'package:anchor_collect_flutter/models/breeding_record_detail_entity.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:uuid/uuid.dart';
import 'package:flutter/material.dart';
import '../../../congifs.dart';
import '../../../controllers/global_service.dart';
import '../../../models/breeding_record_entity.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 'breeding_record_detail_state.dart';

class BreedingRecordDetailLogic extends GetxController {
  final BreedingRecordDetailState state = BreedingRecordDetailState();

  BreedingRecordDetailEntity? detailEntity;
  BreedingRecordEntity? entity;

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

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

    if (entity == null) {
      DialogUtils.showToast('数据信息问题');
      Get.back(result: 'refresh');
    } else {
      if (detailEntity != null) {
        state.entity.value = detailEntity!;
        state.isModify = true;
        state.unid = state.entity.value.unid!;
      } else {
        state.entity.value.unid = uuid.v4().hashCode.toString() + uuid.v4().hashCode.toString();
        // state.entity.value.cattleresumeId = entity.cattleresumeId;
        state.entity.value.registrationNo = entity!.registrationNo;
        state.entity.value.individualNo = entity!.individualNo;
        state.entity.value.fUnid = entity!.unid;
        state.entity.value.matingStyle == '2';
      }
      refreshDictData();
    }
  }

  ///初始化字典项
  refreshDictData() async {
    state.matingStyle =
        await DictUtils.getDictName('zxgl_cattlemating_matingStyle', state.entity.value.matingStyle ?? '');
    state.frozenSemenBatch =
        await DictUtils.getDictName('zxgl_frozen_semen', state.entity.value.frozenSemenBatch ?? '');
    // state.grade = await DictUtils.getDictName('zxgl_cattleresume_grade', state.entity.value.grade ?? '');

    update();
  }

  ///计算预产期
  calculateDueDate(String matingDate) {
    DateTime startDate = DateTime.parse(matingDate);
    int daysToAdd = 280;
    DateTime endDate = startDate.add(Duration(days: daysToAdd));

    String formattedEndDate = DateFormat('yyyy-MM-dd').format(endDate);
    state.entity.value.dueDate = formattedEndDate;
    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.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.breedingRecordDetailEntitys.put(state.entity.value),
        });
    DialogUtils.showToast('保存配种详情成功');
    DialogUtils.dismissDialog();
    Get.back(result: 'refresh');
  }

  Future<bool> checkRequiredFields() async {
    if (entity == null || !EmptyUtils.isStrNotEmpty(entity!.cattleresumeId)) {
      DialogUtils.showToast('高频耳标或者可视耳标无效');
      return true;
    }
    if (!EmptyUtils.isStrNotEmpty(state.entity.value.matingDate)) {
      DialogUtils.showToast('必须选择配种日期');
      return true;
    }
    if (!EmptyUtils.isStrNotEmpty(state.entity.value.matingStyle)) {
      DialogUtils.showToast('必须选择配种方式');
      return true;
    }
    return false;
  }

  copyEntity(BreedingRecordDetailEntity 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.fUnid = formerEntity.fUnid;
    state.entity.value.matingStyle = formerEntity.matingStyle;
    state.entity.value.frozenSemenBatch = formerEntity.frozenSemenBatch;
    state.entity.value.matingDate = formerEntity.matingDate;
    state.entity.value.other = formerEntity.other;
    state.entity.value.isReturn = formerEntity.isReturn;
    state.entity.value.backLoveDate = formerEntity.backLoveDate;
    state.entity.value.dueDate = formerEntity.dueDate;
    state.entity.value.pregnancy = formerEntity.pregnancy;
    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;
  }
}
