import 'package:anchor_collect_flutter/models/breeding_record_entity.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.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/breeding_record_detail_entity.dart';
import '../../models/cattle_resume_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_state.dart';

class BreedingRecordLogic extends GetxController {
  final BreedingRecordState state = BreedingRecordState();

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

  @override
  void onInit() {
    Map<String, dynamic>? arguments = Get.arguments;
    if (arguments != null) {
      BreedingRecordEntity? entity = arguments['entity'];
      state.cattleResumeEntity = arguments['cattleResumeEntity'];
      state.unid = uuid.v4().hashCode.toString() + uuid.v4().hashCode.toString();
      if (entity != null) {
        state.entity.value = entity;
        state.isModify = true;
        state.unid = state.entity.value.unid!;
        queryBreedingRecordDetail();
      } else {
        ///如果没有配种记录，先要查询一下
        if (state.cattleResumeEntity != null) {
          queryBreedingRecord(state.cattleResumeEntity?.registrationNo ?? '', state.cattleResumeEntity?.individualNo ?? '');
        }
      }
    }
  }

  ///查主表
  queryBreedingRecord(String registrationNo, String individualNo) async {
    BreedingRecordEntity? bre = await GlobalService.to.isar.breedingRecordEntitys
        .filter()
        .optional(state.cattleResumeEntity != null, (q) => q.cattleresumeIdEqualTo(state.cattleResumeEntity!.unid))
        .optional(EmptyUtils.isStrNotEmpty(registrationNo), (q) => q.registrationNoEqualTo(registrationNo))
        .optional(EmptyUtils.isStrNotEmpty(individualNo), (q) => q.individualNoEqualTo(individualNo))
        .sortByCreateTimeDesc()
        .findFirst();

    if (bre != null) {
      copyEntity(bre);
      queryBreedingRecordDetail();
    } else { ///没有就创建新的
      CattleResumeEntity? cre = await GlobalService.to.isar.cattleResumeEntitys
          .filter()
          .optional(EmptyUtils.isStrNotEmpty(registrationNo), (q) => q.registrationNoEqualTo(registrationNo))
          .optional(EmptyUtils.isStrNotEmpty(individualNo), (q) => q.individualNoEqualTo(individualNo))
          .sortByCreateTimeDesc()
          .findFirst();
      if (cre != null) {
        state.entity.value.unid = state.unid;
        state.entity.value.cattleresumeId = cre.unid;
        state.entity.value.registrationNo = cre.registrationNo;
        state.entity.value.individualNo = cre.individualNo;
        state.entity.value.deptId = SpHelper.getStorage(Config.SP_DEPT_ID);
        update();
      } else {
        DialogUtils.showWarningDialog('无此标签数据！');
      }
    }
  }

  ///查子表数据
  queryBreedingRecordDetail() async {
    state.dataList.clear();
    var pageData = await GlobalService.to.isar.breedingRecordDetailEntitys
        .filter()
        .unidIsNotEmpty()
        .fUnidEqualTo(state.entity.value.unid)
        .sortByCreateTimeDesc()
        .findAll();
    //查询出高频耳标和可视耳标
    if (pageData != null) {
      for (int i = 0; i < pageData!.length; i++) {
        // pageData[i].cattleresumeId = state.entity.value.cattleresumeId;
        pageData[i].registrationNo = state.entity.value.registrationNo;
        pageData[i].individualNo = state.entity.value.individualNo;
      }
    }
    state.dataList.addAll(pageData);
    getItemList(state.dataList);
  }

  clean() {
    update();
  }

  Future<void> itemOnClickListener({BreedingRecordDetailEntity? entity}) async {
    if (entity == null) {
      ///保存配种主表
      await GlobalService.to.isar.writeTxn(() async => {
            await GlobalService.to.isar.breedingRecordEntitys.put(state.entity.value),
          });
    }
    Map<String, dynamic> params = {};
    params.putIfAbsent("entity", () => state.entity.value);
    params.putIfAbsent("detailEntity", () => entity);
    var date = await Get.toNamed(AppRoute.BREEDING_RECORD_DETAIL, arguments: params);
    if (date == 'refresh') {
      queryBreedingRecordDetail();
    }
  }

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

  copyEntity(BreedingRecordEntity 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.raiseVarieties = formerEntity.raiseVarieties;
    state.entity.value.location = formerEntity.location;
    state.entity.value.breedingPlantId = formerEntity.breedingPlantId;
    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;
  }

  ///子表item布局
  getItemList(List<BreedingRecordDetailEntity> itemDateList) async {
    List<Widget> list = [];

    if (kDebugMode) {
      print('配种列表数量：${itemDateList.length}');
    }
    for (int i = 0; i < itemDateList.length; i++) {
      list.add(Padding(
        padding: const EdgeInsets.all(15.0),
        child: InkWell(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              SizedBox(
                height: 5,
                child: Container(
                  height: 5,
                  color: Colors.black12,
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(2.0),
                child: Row(
                  children: [
                    // getDialogItemView(
                    //     '配种方式',
                    //     await DictUtils.getDictName(
                    //         'zxgl_cattlemating_matingStyle', itemDateList[i].matingStyle ?? '')),
                    getDialogItemView('冻精信息',  await DictUtils.getDictName(
                        'zxgl_frozen_semen', itemDateList[i].frozenSemenBatch ?? '')),
                    getDialogItemView('冻精注册号', itemDateList[i].cattleresumeId ?? ''),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(2.0),
                child: Row(
                  children: [
                    getDialogItemView('其它', itemDateList[i].other ?? ''),
                    getDialogItemView('配种日期', itemDateList[i].matingDate ?? ''),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(2.0),
                child: Row(
                  children: [
                    getDialogItemView('预产日期', itemDateList[i].dueDate ?? ''),
                    getDialogItemView('备注', itemDateList[i].remark ?? ''),
                  ],
                ),
              ),
              // Padding(
              //   padding: const EdgeInsets.all(2.0),
              //   child: Row(
              //     children: [
              //     ],
              //   ),
              // ),
              const SizedBox(
                height: 5,
              ),
            ],
          ),
          onTap: () => itemOnClickListener(entity: itemDateList[i]),
        ),
      ));
    }

    state.items = list;
    update();
  }

  ///弹窗item
  getDialogItemView(String title, String context) {
    return Expanded(
      child: Container(
        decoration: const BoxDecoration(
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black12,
              blurRadius: 2,
            ),
          ],
        ),
        padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(
              height: 10,
            ),
            Text(
              title,
              style: const TextStyle(
                color: Colors.blue,
                fontSize: 14,
              ),
            ),
            const SizedBox(
              height: 10,
            ),
            SizedBox(
              height: 1,
              child: Container(
                color: Colors.black12,
                height: 1,
              ),
            ),
            const SizedBox(
              height: 10,
            ),
            Text(
              context,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(
                height: 1.5,
                color: Colors.black,
                fontSize: 14,
              ),
            ),
            const SizedBox(
              height: 10,
            ),
          ],
        ),
      ),
    );
  }
}
