import 'package:anchor_collect_flutter/models/breeding_record_entity.dart';
import 'package:anchor_collect_flutter/utils/dict_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:isar/isar.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/empty_utils.dart';
import '../../../utils/sp_helper.dart';
import 'breeding_record_list_state.dart';

class BreedingRecordListLogic extends GetxController {
  final BreedingRecordListState state = BreedingRecordListState();
  bool isShow = false;

  late TextEditingController highController;

  @override
  void onInit() {
    highController = TextEditingController();
    Map<String, dynamic>? arguments = Get.arguments;
    if (arguments != null) {
      state.cattleResumeEntity = arguments['cattleResumeEntity'];
    }
  }

  queryByFilter() async {
    state.dataList.clear();
    state.items.clear();
    if (!EmptyUtils.isStrNotEmpty(state.filterHighNo) && !EmptyUtils.isStrNotEmpty(state.filterVisualNo)) {
      state.isFilter = false;
    } else {
      state.isFilter = true;
      // CattleResumeEntity? cattleResumeEntity = await GlobalService.to.isar.cattleResumeEntitys
      //     .filter()
      //     .optional(state.cattleResumeEntity != null, (q) => q.unidEqualTo(state.cattleResumeEntity!.unid))
      //     .optional(EmptyUtils.isStrNotEmpty(state.filterHighNo), (q) => q.registrationNoEqualTo(state.filterHighNo))
      //     .optional(EmptyUtils.isStrNotEmpty(state.filterVisualNo), (q) => q.individualNoEqualTo(state.filterVisualNo))
      //     .findFirst();
    }
    isShow = false;
    queryFirstPage();
  }

  queryFirstPage() {
    state.dataList.clear();
    state.pagination = 1;
    queryOnePage();
  }

  queryOnePage() async {
    var pageData = await GlobalService.to.isar.breedingRecordEntitys
        .filter()
        .unidIsNotEmpty()
        .optional(state.cattleResumeEntity != null, (q) => q.cattleresumeIdEqualTo(state.cattleResumeEntity!.unid))
        .optional(!Config.isAdmin, (q) => q.deptIdEqualTo(SpHelper.getStorage(Config.SP_DEPT_ID)))
        .optional(EmptyUtils.isStrNotEmpty(state.filterHighNo), (q) => q.registrationNoEqualTo(state.filterHighNo))
        .optional(EmptyUtils.isStrNotEmpty(state.filterVisualNo), (q) => q.individualNoEqualTo(state.filterVisualNo))
        .sortByCreateTimeDesc()
        .offset(state.pageCount * (state.pagination - 1))
        .limit(state.pageCount)
        .findAll();
    if (pageData.isEmpty) {
      state.pagination--;
    }
    //查询出高频耳标和可视耳标
    if (pageData != null) {
      for (int i = 0; i < pageData!.length; i++) {
        CattleResumeEntity? cre = await GlobalService.to.isar.cattleResumeEntitys
            .filter()
            .unidEqualTo(pageData[i].cattleresumeId)
            .findFirst();
        if (cre != null) {
          pageData[i].cattleresumeId = cre.unid;
          pageData[i].registrationNo = cre.registrationNo;
          pageData[i].individualNo = cre.individualNo;
          pageData[i].breedingPlantId = await DictUtils.getDictName('zxgl_breeding_list', cre.deptId ?? '');
          pageData[i].raiseVarieties = await DictUtils.getDictName('zxgl_cattle_raiseVarieties', cre.raiseVarieties ?? '');
        }
      }
    }
    state.dataList.addAll(pageData);
    getItemList(state.dataList);
  }

  onRefresh() {
    state.isFilter = false;
    queryFirstPage();
  }

  onLoad() {
    if (!state.isFilter) {
      state.pagination++;
      queryOnePage();
    }
  }

  clean() {
    state.filterHighNo = '';
    state.filterVisualNo = '';
    highController.text = '';
    update();
  }

  getItemList(List<BreedingRecordEntity> 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: [
              getCattleResumeItem('电子耳标', itemDateList[i].registrationNo),
              const SizedBox(
                height: 5,
              ),
              getCattleResumeItem('可视耳标', itemDateList[i].individualNo),
              const SizedBox(
                height: 5,
              ),
              getCattleResumeItem('所属种蓄站', itemDateList[i].breedingPlantId),
              const SizedBox(
                height: 5,
              ),
              getCattleResumeItem('饲养品种', itemDateList[i].raiseVarieties ?? ''),
            ],
          ),
          onTap: () => itemOnClickListener(entity: itemDateList[i]),
        ),
      ));
    }

    state.items = list;
    update();
  }

  getCattleResumeItem(String title, String? context) {
    // print('why:$title:$context');
    return Row(
      children: [
        Text(
          title,
          style: const TextStyle(
            color: Colors.black,
            fontSize: 15,
          ),
        ),
        const Expanded(
          child: SizedBox(
            height: 1,
          ),
        ),
        Text(
          context ?? '',
          style: const TextStyle(
            color: Colors.black45,
            fontSize: 15,
          ),
        ),
      ],
    );
  }

  Future<void> itemOnClickListener({BreedingRecordEntity? entity}) async {
    Map<String, dynamic> params = {};
    params.putIfAbsent("entity", () => entity);
    params.putIfAbsent("cattleResumeEntity", () => state.cattleResumeEntity);
    var date = await Get.toNamed(AppRoute.BREEDING_RECORD, arguments: params);
    if (date == 'refresh') {
      queryFirstPage();
    }
  }

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