import 'package:anchor_collect_flutter/models/cattle_resume_entity.dart';
import 'package:anchor_collect_flutter/routes/routes.dart';
import 'package:anchor_collect_flutter/utils/dialog_utils.dart';
import 'package:anchor_collect_flutter/utils/empty_utils.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/value_model.dart';
import '../../../rfid/rfid_plugin.dart';
import '../../../utils/dict_utils.dart';
import '../../../utils/sp_helper.dart';
import 'cattle_resume_list_state.dart';

class CattleResumeListLogic extends GetxController {
  final CattleResumeListState state = CattleResumeListState();

  bool isShow = false;

  late TextEditingController highController;
  late TextEditingController personController;

  @override
  void onInit() {
    highController = TextEditingController();
    personController = TextEditingController();

    state.status = Get.arguments;
  }

  queryByFilter() async {
    state.dataList.clear();
    if (!EmptyUtils.isStrNotEmpty(state.filterHighNo) &&
        !EmptyUtils.isStrNotEmpty(state.filterVisualNo) &&
        !EmptyUtils.isStrNotEmpty(state.filterFatherNo) &&
        !EmptyUtils.isStrNotEmpty(state.filterMotherNo)) {
      state.isFilter = false;
      queryFirstPage();
    } else {
      state.isFilter = true;
      state.dataList = await GlobalService.to.isar.cattleResumeEntitys
          .filter()
          .optional(EmptyUtils.isStrNotEmpty(state.status), (q) => q.statusEqualTo(state.status))
          .optional(!Config.isAdmin, (q) => q.deptIdEqualTo(SpHelper.getStorage(Config.SP_DEPT_ID)))
          .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))
          .findAll();
    }
    isShow = false;
    getItemList(state.dataList);
  }

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

  queryOnePage() async {
    var pageData = await GlobalService.to.isar.cattleResumeEntitys
        .filter()
        .unidIsNotEmpty()
        .optional(EmptyUtils.isStrNotEmpty(state.status), (q) => q.statusEqualTo(state.status))
        .optional(!Config.isAdmin, (q) => q.deptIdEqualTo(SpHelper.getStorage(Config.SP_DEPT_ID)))
        .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--;
    }
    state.dataList.addAll(pageData);
    getItemList(state.dataList);
  }

  onRefresh() {
    queryFirstPage();
  }

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

  clean() {
    state.filterHighNo = '';
    state.filterVisualNo = '';
    state.filterFatherNo = '';
    state.filterMotherNo = '';
    state.cattleManId = '';
    state.cattleManName = '';
    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<CattleResumeEntity> 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(
              //     '圈舍号', await DictUtils.getDictName('zxgl_circle_list', itemDateList[i].circleNo ?? '')),
              // const SizedBox(
              //   height: 5,
              // ),
              getCattleResumeItem('饲养品种',
                  await DictUtils.getDictName('zxgl_cattle_raiseVarieties', itemDateList[i].raiseVarieties ?? '')),
              const SizedBox(
                height: 5,
              ),
              getCattleResumeItem(
                  '状态', await DictUtils.getDictName('zxgl_cattleresume_status', itemDateList[i].status ?? '')),
            ],
          ),
          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({CattleResumeEntity? entity}) async {
    var date = await Get.toNamed(AppRoute.CATTLE_RESUME, arguments: entity);
    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();
      });
    }
  }
}
