import 'package:anchor_collect_flutter/models/cattle_resume_entity.dart';
import 'package:anchor_collect_flutter/models/performance.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 '../../../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 'performance_list_state.dart';

class PerformanceListLogic extends GetxController {
  final PerformanceListState state = PerformanceListState();

  bool isShow = false;

  late TextEditingController highController;
  late TextEditingController personController;

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

  queryByFilter() async {
    state.dataList.clear();
    state.items.clear();
    state.cattleResumeEntity = null;
    if (!EmptyUtils.isStrNotEmpty(state.filterHighNo) &&
        !EmptyUtils.isStrNotEmpty(state.filterVisualNo) &&
        !EmptyUtils.isStrNotEmpty(state.filterFatherNo) &&
        !EmptyUtils.isStrNotEmpty(state.filterMotherNo)) {
      state.isFilter = false;
    } else {
      state.isFilter = true;
      //   state.cattleResumeEntity = await GlobalService.to.isar.cattleResumeEntitys
      //       .filter()
      //       .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))
      //       .optional(EmptyUtils.isStrNotEmpty(state.filterFatherNo), (q) => q.fatherRegEqualTo(state.filterFatherNo))
      //       .optional(EmptyUtils.isStrNotEmpty(state.filterMotherNo), (q) => q.motherRegEqualTo(state.filterMotherNo))
      //       .findFirst();
    }
    isShow = false;
    queryFirstPage();
  }

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

  queryOnePage() async {
    var pageData = await GlobalService.to.isar.performanceEntitys
        .filter()
        .unidIsNotEmpty()
        .optional(!Config.isAdmin, (q) => q.deptIdEqualTo(SpHelper.getStorage(Config.SP_DEPT_ID)))
        .optional(state.cattleResumeEntity != null, (q) => q.cattleresumeIdEqualTo(state.cattleResumeEntity!.unid))
        .optional(Config.isAdmin && EmptyUtils.isStrNotEmpty(state.cattleManId), (q) => q.deptIdEqualTo(state.cattleManId))
        .optional(EmptyUtils.isStrNotEmpty(state.filterHighNo), (q) => q.registrationNoEqualTo(state.filterHighNo))
        .optional(EmptyUtils.isStrNotEmpty(state.filterVisualNo), (q) => q.individualNoEqualTo(state.filterVisualNo))
        .optional(EmptyUtils.isStrNotEmpty(state.filterFatherNo), (q) => q.fatherRegEqualTo(state.filterFatherNo))
        .optional(EmptyUtils.isStrNotEmpty(state.filterMotherNo), (q) => q.motherRegEqualTo(state.filterMotherNo))
        .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()
            .optional(!Config.isAdmin, (q) => q.deptIdEqualTo(SpHelper.getStorage(Config.SP_DEPT_ID)))
            .unidEqualTo(pageData[i].cattleresumeId)
            .findFirst();
        if (cre != null) {
          pageData[i].registrationNo = cre.registrationNo;
          pageData[i].individualNo = cre.individualNo;
        }
      }
    }
    state.dataList.addAll(pageData);
    if (kDebugMode) {
      print('performancequeryOnePage:${pageData.toString()}');
    }
    getItemList(state.dataList);
  }

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

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

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

  ///选择牧户
  selectCattleMan() async {
    DialogUtils.showSingleListDialog(await DictUtils.getDictList('zxgl_breeding_list'),
        onPositive: (selectReslut) => {
          state.cattleManName = selectReslut.key,
          state.cattleManId = selectReslut.value,
          personController.text=state.cattleManName,
          update(),}
    );
  }

  getItemList(List<PerformanceEntity> 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].measureDate),
              const SizedBox(
                height: 5,
              ),
              getCattleResumeItem('畜龄', await DictUtils.getDictName('zxgl_performance_age', itemDateList[i].age ?? '')),
            ],
          ),
          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({PerformanceEntity? entity}) async {
    Map<String, dynamic> params = {};
    params.putIfAbsent("entity", () => entity);
    params.putIfAbsent("cattleResumeEntity", () => state.cattleResumeEntity);
    var date = await Get.toNamed(AppRoute.PERFORMANCE, 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();
      });
    }
  }
}
