import 'package:anchor_collect_flutter/models/cattle_resume_entity.dart';
import 'package:anchor_collect_flutter/models/weight_man_entity.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/empty_utils.dart';
import '../../../utils/sp_helper.dart';
import 'weight_man_list_state.dart';

class WeightManListLogic extends GetxController {
  final WeightManListState state = WeightManListState();

  bool isShow = false;

  late TextEditingController highController;

  @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();
    state.cattleResumeEntity = null;
    if (!EmptyUtils.isStrNotEmpty(state.filterHighNo) && !EmptyUtils.isStrNotEmpty(state.filterVisualNo)) {
      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))
      //     .findFirst();
    }
    isShow = false;
      queryFirstPage();
  }

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

  queryOnePage() async {
    var pageData = await GlobalService.to.isar.weightManEntitys
        .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(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()
            .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);
    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<WeightManEntity> 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].wTime),
              const SizedBox(
                height: 5,
              ),
              getCattleResumeItem('重量', (itemDateList[i].weight ?? '').toString()),
            ],
          ),
          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({WeightManEntity? entity}) async {
    Map<String, dynamic> params = {};
    params.putIfAbsent("entity", () => entity);
    params.putIfAbsent("cattleResumeEntity", () => state.cattleResumeEntity);
    var date = await Get.toNamed(AppRoute.WEIGHT_MAN, 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();
      });
    }
  }
}
