import 'package:anchor_collect_flutter/models/cattle_resume_entity.dart';
import 'package:anchor_collect_flutter/models/immune_batch_detail_entity.dart';
import 'package:anchor_collect_flutter/models/immune_batch_entity.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/dict_utils.dart';
import '../../../utils/empty_utils.dart';
import '../../../utils/sp_helper.dart';
import 'immune_batch_list_state.dart';

class ImmuneBatchListLogic extends GetxController {
  final ImmuneBatchListState state = ImmuneBatchListState();
  bool isShow = false;

  late TextEditingController highController;

  List<String>? unidList;

  @override
  void onInit() {
    highController = 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();
    if (!EmptyUtils.isStrNotEmpty(state.filterCircleNo) && !EmptyUtils.isStrNotEmpty(state.filterVaccineName)) {
      state.isFilter = false;
    } else {
      state.isFilter = true;
      // state.dataList = await GlobalService.to.isar.immuneBatchEntitys
      //     .filter()
      //     .optional(!Config.isAdmin, (q) => q.deptIdEqualTo(SpHelper.getStorage(Config.SP_DEPT_ID)))
      //     .optional(EmptyUtils.isStrNotEmpty(state.filterCircleNo), (q) => q.circleNoEqualTo(state.filterCircleNo))
      //     .optional(EmptyUtils.isStrNotEmpty(state.filterVaccineName), (q) => q.vaccineNameEqualTo(state.filterVaccineName))
      //     .findAll();
      // getItemList(state.dataList);
    }
    isShow = false;
    queryFirstPage();
  }

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

  queryOnePage() async {
    if (state.cattleResumeEntity != null) {
      var immuneDetailList = await GlobalService.to.isar.immuneBatchDetailEntitys
          .filter()
          .cattleresumeUnidEqualTo(state.cattleResumeEntity!.unid)
          .cattleresumeUnidIsNotEmpty()
          .findAll();

      unidList = immuneDetailList.map((e) => e.immunebatchUnid!).toList();
    }
    var pageData = await GlobalService.to.isar.immuneBatchEntitys
        .filter()
        .unidIsNotEmpty()
        .optional(!Config.isAdmin, (q) => q.deptIdEqualTo(SpHelper.getStorage(Config.SP_DEPT_ID)))
        .optional(EmptyUtils.isStrNotEmpty(state.filterCircleNo), (q) => q.circleNoEqualTo(state.filterCircleNo))
        .optional(
            EmptyUtils.isStrNotEmpty(state.filterVaccineName), (q) => q.vaccineNameEqualTo(state.filterVaccineName))
        .sortByCreateTimeDesc()
        .offset(state.pageCount * (state.pagination - 1))
        .limit(state.pageCount)
        .findAll();
    //如果有牛信息，过滤一下
    List<ImmuneBatchEntity> newPageData = [];
    if (state.cattleResumeEntity != null) {
      if (EmptyUtils.isListNotEmpty(unidList) && EmptyUtils.isListNotEmpty(pageData)) {
        for (int i = 0; i < pageData!.length; i++) {
          if (unidList!.contains(pageData[i].unid)) {
            newPageData.add(pageData[i]);
          }
        }
      }
    } else {
      newPageData.addAll(pageData);
    }
    if (newPageData.isEmpty) {
      state.pagination--;
    }
    state.dataList.addAll(newPageData);
    getItemList(state.dataList);
  }

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

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

  clean() {
    state.filterCircleNo = '';
    state.filterCircleName = '';
    state.filterVaccineName = '';
    highController.text = '';
    update();
  }

  getItemList(List<ImmuneBatchEntity> 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(
                  '圈舍号', await DictUtils.getDictName('zxgl_circle_list', itemDateList[i].circleNo ?? '')),
              const SizedBox(
                height: 5,
              ),
              getCattleResumeItem('免疫日期', itemDateList[i].immuneDate),
              const SizedBox(
                height: 5,
              ),
              getCattleResumeItem('疫苗名称', itemDateList[i].vaccineName),
            ],
          ),
          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({ImmuneBatchEntity? entity}) async {
    Map<String, dynamic> params = {};
    params.putIfAbsent("entity", () => entity);
    var date = await Get.toNamed(AppRoute.IMMUNE_BATCH, arguments: params);
    if (date == 'refresh') {
      queryFirstPage();
    }
  }
}
