import 'package:anchor_collect_flutter/api/HttpUtils.dart';
import 'package:anchor_collect_flutter/congifs.dart';
import 'package:anchor_collect_flutter/controllers/global_service.dart';
import 'package:anchor_collect_flutter/models/breeding_record_detail_entity.dart';
import 'package:anchor_collect_flutter/models/breeding_record_entity.dart';
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:anchor_collect_flutter/models/medical_record_entity.dart';
import 'package:anchor_collect_flutter/models/performance.dart';
import 'package:anchor_collect_flutter/models/weight_man_entity.dart';
import 'package:anchor_collect_flutter/utils/dialog_utils.dart';
import 'package:anchor_collect_flutter/utils/empty_utils.dart';
import 'package:anchor_collect_flutter/utils/sp_helper.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:isar/isar.dart';

import '../../api/apis.dart';
import '../../utils/base64_utils.dart';
import 'sync_state.dart';

class SyncLogic extends GetxController {
  final SyncState state = SyncState();

  @override
  void onInit() {
    DialogUtils.showLoadingDialog('正在查询本地数据');
    queryCount();
  }

  queryCount() async {
    if (state.isCattleResumeCompleteSync) {
      state.dataList[0].count =
          await GlobalService.to.isar.cattleResumeEntitys.filter().uploadStatusEqualTo('0').count();
      state.dataList[0].allCount =
          await GlobalService.to.isar.cattleResumeEntitys.filter().uploadStatusEqualTo('1').count();
      state.dataList[0].errorCount =
          await GlobalService.to.isar.cattleResumeEntitys.filter().uploadStatusEqualTo('2').count();
      state.dataList[0].updateTime = SpHelper.getStorage(Config.SP_CATTLERESUME_UPDATE_TIME);
    }

    if (state.isPerformanceCompleteSync) {
      state.dataList[1].count =
          await GlobalService.to.isar.performanceEntitys.filter().uploadStatusEqualTo('0').count();
      state.dataList[1].allCount =
          await GlobalService.to.isar.performanceEntitys.filter().uploadStatusEqualTo('1').count();
      state.dataList[1].errorCount =
          await GlobalService.to.isar.performanceEntitys.filter().uploadStatusEqualTo('2').count();
      state.dataList[1].updateTime = SpHelper.getStorage(Config.SP_PERFORMANCE_UPDATE_TIME);
    }

    if (state.isWeightManCompleteSync) {
      state.dataList[2].count = await GlobalService.to.isar.weightManEntitys.filter().uploadStatusEqualTo('0').count();
      state.dataList[2].allCount =
          await GlobalService.to.isar.weightManEntitys.filter().uploadStatusEqualTo('1').count();
      state.dataList[2].errorCount =
          await GlobalService.to.isar.weightManEntitys.filter().uploadStatusEqualTo('2').count();
      state.dataList[2].updateTime = SpHelper.getStorage(Config.SP_WEIGHT_MAN_UPDATE_TIME);
    }

    if (state.isMedicalRecordCompleteSync) {
      state.dataList[3].count =
          await GlobalService.to.isar.medicalRecordEntitys.filter().uploadStatusEqualTo('0').count();
      state.dataList[3].allCount =
          await GlobalService.to.isar.medicalRecordEntitys.filter().uploadStatusEqualTo('1').count();
      state.dataList[3].errorCount =
          await GlobalService.to.isar.medicalRecordEntitys.filter().uploadStatusEqualTo('2').count();
      state.dataList[3].updateTime = SpHelper.getStorage(Config.SP_MEDICAL_RECORD_UPDATE_TIME);
    }

    if (state.isImmuneBatchCompleteSync) {
      state.dataList[4].count =
          await GlobalService.to.isar.immuneBatchEntitys.filter().uploadStatusEqualTo('0').count();
      state.dataList[4].allCount =
          await GlobalService.to.isar.immuneBatchEntitys.filter().uploadStatusEqualTo('1').count();
      state.dataList[4].errorCount =
          await GlobalService.to.isar.immuneBatchEntitys.filter().uploadStatusEqualTo('2').count();
      state.dataList[4].updateTime = SpHelper.getStorage(Config.SP_IMMUNE_BATCH_UPDATE_TIME);
    }

    if (state.isImmuneBatchDetailCompleteSync) {
      state.dataList[5].count =
          await GlobalService.to.isar.immuneBatchDetailEntitys.filter().uploadStatusEqualTo('0').count();
      state.dataList[5].allCount =
          await GlobalService.to.isar.immuneBatchDetailEntitys.filter().uploadStatusEqualTo('1').count();
      state.dataList[5].errorCount =
          await GlobalService.to.isar.immuneBatchDetailEntitys.filter().uploadStatusEqualTo('2').count();
      state.dataList[5].updateTime = SpHelper.getStorage(Config.SP_IMMUNE_BATCH_DETAIL_UPDATE_TIME);
    }

    if (state.isBreedingRecordCompleteSync) {
      state.dataList[6].count =
          await GlobalService.to.isar.breedingRecordEntitys.filter().uploadStatusEqualTo('0').count();
      state.dataList[6].allCount =
          await GlobalService.to.isar.breedingRecordEntitys.filter().uploadStatusEqualTo('1').count();
      state.dataList[6].errorCount =
          await GlobalService.to.isar.breedingRecordEntitys.filter().uploadStatusEqualTo('2').count();
      state.dataList[6].updateTime = SpHelper.getStorage(Config.SP_BREEDING_RECORD_UPDATE_TIME);
    }

    if (state.isBreedingRecordDetailCompleteSync) {
      state.dataList[7].count =
          await GlobalService.to.isar.breedingRecordDetailEntitys.filter().uploadStatusEqualTo('0').count();
      state.dataList[7].allCount =
          await GlobalService.to.isar.breedingRecordDetailEntitys.filter().uploadStatusEqualTo('1').count();
      state.dataList[7].errorCount =
          await GlobalService.to.isar.breedingRecordDetailEntitys.filter().uploadStatusEqualTo('2').count();
      state.dataList[7].updateTime = SpHelper.getStorage(Config.SP_BREEDING_RECORD_DETAIL_UPDATE_TIME);
    }

    if (
    state.isCattleResumeCompleteSync
        &&
        state.isPerformanceCompleteSync
        &&
        state.isWeightManCompleteSync
        &&
        state.isMedicalRecordCompleteSync
        &&
        state.isImmuneBatchCompleteSync
        &&
        state.isImmuneBatchDetailCompleteSync
        &&
        state.isBreedingRecordCompleteSync
        &&
        state.isBreedingRecordDetailCompleteSync
    ) {
      DialogUtils.dismissDialog();
    }

    update();
  }

  ///同步数据
  syncData() async {
    await downloadCattleResumeList();
    await downloadPerformanceList();
    await downloadWeightManList();
    await downloadMedicalRecordList();
    await downloadImmuneBatchList();
    await downloadImmuneBatchDetailList();
    await downloadBreedingRecordList();
    await downloadBreedingRecordDetailList();
  }

  ///下载基础信息
  downloadCattleResumeList() async {
    Map<String, String> queryMap = {};

    ///1为每次清除
    queryMap.putIfAbsent('SyncState', () => '0');

    HttpUtils<CattleResumeEntity>()
      ..post()
      ..setUrl(APIS.download_cattle_list)
      ..setQueryParameters(queryMap)
      ..setIsList()
      ..onResponseList((list) async {
        List<String> ids = [];
        if (kDebugMode) {
          print('接收基础信息数量：${list.length}');
        }

        ///保存图片
        for (var e in list) {
          e!.uploadStatus = '1';
          ids.add(e!.unid.toString());
          if (e.photo != null && e.photo!.isNotEmpty) {
            e.photoPath = await Base64Utils.base64ToFile(e.photo!, e.unid ?? '');
            e.photo = '';
          }

          ///保存数据库
          await GlobalService.to.isar.writeTxn(() async {
            await GlobalService.to.isar.cattleResumeEntitys.putByUnid(e);
          });
        }
        SpHelper.putStorage(Config.SP_CATTLERESUME_UPDATE_TIME, DateTime.now().toString());
        if (ids.isNotEmpty) {
          cattleResumeListSync(ids);
        } else {
          uploadCattleResumeList();
        }
        DialogUtils.showToast('保存基础数据完成,数量：${list.length}');
      })
      ..onError((msg, code) {
        uploadCattleResumeList();
      })
      ..build();
  }

  ///同步保存成功的基础信息id给后台
  cattleResumeListSync(List<String> mList) {
    HttpUtils<void>()
      ..post()
      ..setUrl(APIS.download_cattle_list_sync)
      ..setmListParam(mList)
      ..onResponse((response) async {
        downloadCattleResumeList();
      })
      ..onError((msg, code) {
        DialogUtils.showToast('同步基础数据:$code:$msg');
        uploadCattleResumeList();
      })
      ..build();
  }

  ///上传基础信息数据
  Future<void> uploadCattleResumeList() async {
    List<CattleResumeEntity> entityList =
        await GlobalService.to.isar.cattleResumeEntitys.filter().uploadStatusEqualTo('0').limit(10).findAll();

    ///转图片为base64
    for (int i = 0; i < entityList.length; i++) {
      if (EmptyUtils.isStrNotEmpty(entityList[i].photoPath)) {
        entityList[i].photo = await Base64Utils.fileToBase64(entityList[i].photoPath!);
      }
    }
    if (entityList.isNotEmpty) {
      HttpUtils<String>()
        ..post()
        ..setUrl(APIS.upload_cattle_List)
        ..setIsList()
        ..setmListParam(entityList)
        ..onResponseList((response) async {
          ///修改上传状态
          for (int i = 0; i < entityList.length; i++) {
            entityList[i].uploadStatus = '2';
            entityList[i].photo = '';
            if (response != null) {
              for (int j = 0; j < response!.length; j++) {
                if (entityList[i].unid == response[j]) {
                  entityList[i].uploadStatus = '1';
                }
              }
            }
          }
          await GlobalService.to.isar.writeTxn(() async {
            await GlobalService.to.isar.cattleResumeEntitys.putAll(entityList);
          });
          state.isCattleResumeCompleteSync = true;
          queryCount();
        })
        ..onError((msg, code) {
          DialogUtils.showToast('上传基础数据:$code:$msg');
          state.isCattleResumeCompleteSync = true;
          queryCount();
        })
        ..build();
    } else {
      state.isCattleResumeCompleteSync = true;
      queryCount();
    }
  }

  ///==================================性能测定=========================================

  ///下载性能测定
  downloadPerformanceList() async {
    Map<String, String> queryMap = {};

    ///1为每次清除
    queryMap.putIfAbsent('SyncState', () => '0');

    HttpUtils<PerformanceEntity>()
      ..post()
      ..setUrl(APIS.download_performance_list)
      ..setQueryParameters(queryMap)
      ..setIsList()
      ..onResponseList((list) async {
        List<String> ids = [];
        if (kDebugMode) {
          print('接收性能测定数量：${list.length}');
        }

        for (var e in list) {
          e!.uploadStatus = '1';
          ids.add(e!.unid.toString());

          ///保存数据库
          await GlobalService.to.isar.writeTxn(() async {
            await GlobalService.to.isar.performanceEntitys.putByUnid(e);
          });
        }
        SpHelper.putStorage(Config.SP_PERFORMANCE_UPDATE_TIME, DateTime.now().toString());
        if (ids.isNotEmpty) {
          performanceListSync(ids);
        } else {
          uploadPerformanceList();
        }
        DialogUtils.showToast('性能测定保存完成,数量：${list.length}');
      })
      ..onError((msg, code) {
        uploadPerformanceList();
      })
      ..build();
  }

  ///同步保存成功的性能测定id给后台
  performanceListSync(List<String> mList) {
    HttpUtils<void>()
      ..post()
      ..setUrl(APIS.download_performance_list_sync)
      ..setmListParam(mList)
      ..onResponse((response) {
        downloadPerformanceList();
      })
      ..onError((msg, code) {
        DialogUtils.showToast('同步性能测定:$code:$msg');
        uploadPerformanceList();
      })
      ..build();
  }

  ///上传性能测定数据
  Future<void> uploadPerformanceList() async {
    List<PerformanceEntity> entityList =
        await GlobalService.to.isar.performanceEntitys.filter().uploadStatusEqualTo('0').limit(10).findAll();

    if (entityList.isNotEmpty) {
      HttpUtils<String>()
        ..post()
        ..setUrl(APIS.upload_performance_List)
        ..setIsList()
        ..setmListParam(entityList)
        ..onResponseList((response) async {
          ///修改上传状态
          for (int i = 0; i < entityList.length; i++) {
            entityList[i].uploadStatus = '2';
            if (response != null) {
              for (int j = 0; j < response!.length; j++) {
                if (entityList[i].unid == response[j]) {
                  entityList[i].uploadStatus = '1';
                }
              }
            }
          }
          await GlobalService.to.isar.writeTxn(() async {
            await GlobalService.to.isar.performanceEntitys.putAll(entityList);
          });
          state.isPerformanceCompleteSync = true;
          queryCount();
        })
        ..onError((msg, code) {
          DialogUtils.showToast('上传性能测定:$code:$msg');
          state.isPerformanceCompleteSync = true;
          queryCount();
        })
        ..build();
    } else {
      state.isPerformanceCompleteSync = true;
      queryCount();
    }
  }

  ///==================================称重记录=========================================

  ///下载称重记录
  downloadWeightManList() async {
    Map<String, String> queryMap = {};

    ///1为每次清除
    queryMap.putIfAbsent('SyncState', () => '0');

    HttpUtils<WeightManEntity>()
      ..post()
      ..setUrl(APIS.download_weight_man_list)
      ..setQueryParameters(queryMap)
      ..setIsList()
      ..onResponseList((list) async {
        List<String> ids = [];
        if (kDebugMode) {
          print('接收称重记录数量：${list.length}');
        }

        for (var e in list) {
          e!.uploadStatus = '1';
          ids.add(e!.unid.toString());

          ///保存数据库
          await GlobalService.to.isar.writeTxn(() async {
            await GlobalService.to.isar.weightManEntitys.putByUnid(e);
          });
        }
        SpHelper.putStorage(Config.SP_WEIGHT_MAN_UPDATE_TIME, DateTime.now().toString());
        if (ids.isNotEmpty) {
          weightManListSync(ids);
        } else {
          uploadWeightManList();
        }
        DialogUtils.showToast('称重记录保存完成,数量：${list.length}');
      })
      ..onError((msg, code) {
        uploadWeightManList();
      })
      ..build();
  }

  ///同步保存成功的称重记录id给后台
  weightManListSync(List<String> mList) {
    HttpUtils<void>()
      ..post()
      ..setUrl(APIS.download_weight_man_list_sync)
      ..setmListParam(mList)
      ..onResponse((response) {
        downloadWeightManList();
      })
      ..onError((msg, code) {
        DialogUtils.showToast('称重记录同步:$code:$msg');
        uploadWeightManList();
      })
      ..build();
  }

  ///上传称重记录数据
  Future<void> uploadWeightManList() async {
    List<WeightManEntity> entityList =
        await GlobalService.to.isar.weightManEntitys.filter().uploadStatusEqualTo('0').limit(10).findAll();

    if (entityList.isNotEmpty) {
      HttpUtils<String>()
        ..post()
        ..setUrl(APIS.upload_weight_man_list)
        ..setIsList()
        ..setmListParam(entityList)
        ..onResponseList((response) async {
          ///修改上传状态
          for (int i = 0; i < entityList.length; i++) {
            entityList[i].uploadStatus = '2';
            if (response != null) {
              for (int j = 0; j < response!.length; j++) {
                if (entityList[i].unid == response[j]) {
                  entityList[i].uploadStatus = '1';
                }
              }
            }
          }
          await GlobalService.to.isar.writeTxn(() async {
            await GlobalService.to.isar.weightManEntitys.putAll(entityList);
          });
          state.isWeightManCompleteSync = true;
          queryCount();
        })
        ..onError((msg, code) {
          DialogUtils.showToast('$code:$msg');
          state.isWeightManCompleteSync = true;
          queryCount();
        })
        ..build();
    } else {
      state.isWeightManCompleteSync = true;
      queryCount();
    }
  }

  ///==================================诊疗记录=========================================

  ///下载诊疗记录
  downloadMedicalRecordList() async {
    Map<String, String> queryMap = {};

    ///1为每次清除
    queryMap.putIfAbsent('SyncState', () => '0');

    HttpUtils<MedicalRecordEntity>()
      ..post()
      ..setUrl(APIS.download_medical_record_list)
      ..setQueryParameters(queryMap)
      ..setIsList()
      ..onResponseList((list) async {
        List<String> ids = [];
        if (kDebugMode) {
          print('接收诊疗记录数量：${list.length}');
        }

        for (var e in list) {
          e!.uploadStatus = '1';
          ids.add(e!.unid.toString());

          ///保存数据库
          await GlobalService.to.isar.writeTxn(() async {
            await GlobalService.to.isar.medicalRecordEntitys.putByUnid(e);
          });
        }
        SpHelper.putStorage(Config.SP_MEDICAL_RECORD_UPDATE_TIME, DateTime.now().toString());
        if (ids.isNotEmpty) {
          medicalRecordListSync(ids);
        } else {
          uploadMedicalRecordList();
        }
        DialogUtils.showToast('诊疗记录保存完成,数量：${list.length}');
      })
      ..onError((msg, code) {
        uploadMedicalRecordList();
      })
      ..build();
  }

  ///同步保存成功的诊疗记录id给后台
  medicalRecordListSync(List<String> mList) {
    HttpUtils<void>()
      ..post()
      ..setUrl(APIS.download_medical_record_list_sync)
      ..setmListParam(mList)
      ..onResponse((response) {
        downloadMedicalRecordList();
      })
      ..onError((msg, code) {
        DialogUtils.showToast('诊疗记录同步:$code:$msg');
        uploadMedicalRecordList();
      })
      ..build();
  }

  ///上传诊疗记录数据
  Future<void> uploadMedicalRecordList() async {
    List<MedicalRecordEntity> entityList =
        await GlobalService.to.isar.medicalRecordEntitys.filter().uploadStatusEqualTo('0').limit(10).findAll();

    if (entityList.isNotEmpty) {
      HttpUtils<String>()
        ..post()
        ..setUrl(APIS.upload_medical_record_List)
        ..setIsList()
        ..setmListParam(entityList)
        ..onResponseList((response) async {
          ///修改上传状态
          for (int i = 0; i < entityList.length; i++) {
            entityList[i].uploadStatus = '2';
            if (response != null) {
              for (int j = 0; j < response!.length; j++) {
                if (entityList[i].unid == response[j]) {
                  entityList[i].uploadStatus = '1';
                }
              }
            }
          }
          await GlobalService.to.isar.writeTxn(() async {
            await GlobalService.to.isar.medicalRecordEntitys.putAll(entityList);
          });
          state.isMedicalRecordCompleteSync = true;
          queryCount();
        })
        ..onError((msg, code) {
          DialogUtils.showToast('$code:$msg');
          state.isMedicalRecordCompleteSync = true;
          queryCount();
        })
        ..build();
    } else {
      state.isMedicalRecordCompleteSync = true;
      queryCount();
    }
  }

  ///==================================免疫记录=========================================

  ///下载免疫记录
  downloadImmuneBatchList() async {
    Map<String, String> queryMap = {};

    ///1为每次清除
    queryMap.putIfAbsent('SyncState', () => '0');

    HttpUtils<ImmuneBatchEntity>()
      ..post()
      ..setUrl(APIS.download_immune_batch_list)
      ..setQueryParameters(queryMap)
      ..setIsList()
      ..onResponseList((list) async {
        List<String> ids = [];
        if (kDebugMode) {
          print('接收免疫记录数量：${list.length}');
        }

        for (var e in list) {
          e!.uploadStatus = '1';
          ids.add(e!.unid.toString());

          ///保存数据库
          await GlobalService.to.isar.writeTxn(() async {
            await GlobalService.to.isar.immuneBatchEntitys.putByUnid(e);
          });
        }
        SpHelper.putStorage(Config.SP_IMMUNE_BATCH_UPDATE_TIME, DateTime.now().toString());
        if (ids.isNotEmpty) {
          immuneBatchListSync(ids);
        } else {
          uploadImmuneBatchList();
        }
        DialogUtils.showToast('免疫记录保存完成,数量：${list.length}');
      })
      ..onError((msg, code) {
        uploadImmuneBatchList();
      })
      ..build();
  }

  ///同步保存成功的免疫记录id给后台
  immuneBatchListSync(List<String> mList) {
    HttpUtils<void>()
      ..post()
      ..setUrl(APIS.download_immune_batch_list_sync)
      ..setmListParam(mList)
      ..onResponse((response) {
        downloadImmuneBatchList();
      })
      ..onError((msg, code) {
        DialogUtils.showToast('免疫记录同步:$code:$msg');
        uploadImmuneBatchList();
      })
      ..build();
  }

  ///上传免疫记录数据
  Future<void> uploadImmuneBatchList() async {
    List<ImmuneBatchEntity> entityList =
        await GlobalService.to.isar.immuneBatchEntitys.filter().uploadStatusEqualTo('0').limit(10).findAll();

    if (entityList.isNotEmpty) {
      HttpUtils<String>()
        ..post()
        ..setUrl(APIS.upload_immune_batch_List)
        ..setIsList()
        ..setmListParam(entityList)
        ..onResponseList((response) async {
          ///修改上传状态
          for (int i = 0; i < entityList.length; i++) {
            entityList[i].uploadStatus = '2';
            if (response != null) {
              for (int j = 0; j < response!.length; j++) {
                if (entityList[i].unid == response[j]) {
                  entityList[i].uploadStatus = '1';
                }
              }
            }
          }
          await GlobalService.to.isar.writeTxn(() async {
            await GlobalService.to.isar.immuneBatchEntitys.putAll(entityList);
          });
          state.isImmuneBatchCompleteSync = true;
          queryCount();
        })
        ..onError((msg, code) {
          DialogUtils.showToast('$code:$msg');
          state.isImmuneBatchCompleteSync = true;
          queryCount();
        })
        ..build();
    } else {
      state.isImmuneBatchCompleteSync = true;
      queryCount();
    }
  }

  ///==================================免疫记录-详情=========================================

  ///下载免疫记录-详情
  downloadImmuneBatchDetailList() async {
    Map<String, String> queryMap = {};

    ///1为每次清除
    queryMap.putIfAbsent('SyncState', () => '0');

    HttpUtils<ImmuneBatchDetailEntity>()
      ..post()
      ..setUrl(APIS.download_immune_batch_detail_list)
      ..setQueryParameters(queryMap)
      ..setIsList()
      ..onResponseList((list) async {
        List<String> ids = [];
        if (kDebugMode) {
          print('接收免疫记录-详情数量：${list.length}');
        }

        for (var e in list) {
          e!.uploadStatus = '1';
          ids.add(e!.unid.toString());

          ///保存数据库
          await GlobalService.to.isar.writeTxn(() async {
            await GlobalService.to.isar.immuneBatchDetailEntitys.putByUnid(e);
          });
        }
        SpHelper.putStorage(Config.SP_IMMUNE_BATCH_DETAIL_UPDATE_TIME, DateTime.now().toString());
        if (ids.isNotEmpty) {
          immuneBatchDetailListSync(ids);
        } else {
          uploadImmuneBatchDetailList();
        }
        DialogUtils.showToast('免疫记录-详情保存完成,数量：${list.length}');
      })
      ..onError((msg, code) {
        uploadImmuneBatchDetailList();
      })
      ..build();
  }

  ///同步保存成功的免疫记录-详情id给后台
  immuneBatchDetailListSync(List<String> mList) {
    HttpUtils<void>()
      ..post()
      ..setUrl(APIS.download_immune_batch_detail_list_sync)
      ..setmListParam(mList)
      ..onResponse((response) {
        downloadImmuneBatchDetailList();
      })
      ..onError((msg, code) {
        DialogUtils.showToast('免疫记录-详情同步:$code:$msg');
        uploadImmuneBatchDetailList();
      })
      ..build();
  }

  ///上传免疫记录-详情数据
  Future<void> uploadImmuneBatchDetailList() async {
    List<ImmuneBatchDetailEntity> entityList =
        await GlobalService.to.isar.immuneBatchDetailEntitys.filter().uploadStatusEqualTo('0').limit(10).findAll();

    if (entityList.isNotEmpty) {
      HttpUtils<String>()
        ..post()
        ..setUrl(APIS.upload_immune_batch_detail_List)
        ..setIsList()
        ..setmListParam(entityList)
        ..onResponseList((response) async {
          ///修改上传状态
          for (int i = 0; i < entityList.length; i++) {
            entityList[i].uploadStatus = '2';
            if (response != null) {
              for (int j = 0; j < response!.length; j++) {
                if (entityList[i].unid == response[j]) {
                  entityList[i].uploadStatus = '1';
                }
              }
            }
          }
          await GlobalService.to.isar.writeTxn(() async {
            await GlobalService.to.isar.immuneBatchDetailEntitys.putAll(entityList);
          });
          state.isImmuneBatchDetailCompleteSync = true;
          queryCount();
        })
        ..onError((msg, code) {
          DialogUtils.showToast('$code:$msg');
          state.isImmuneBatchDetailCompleteSync = true;
          queryCount();
        })
        ..build();
    } else {
      state.isImmuneBatchDetailCompleteSync = true;
      queryCount();
    }
  }

  ///==================================配种记录=========================================

  ///下载配种记录
  downloadBreedingRecordList() async {
    Map<String, String> queryMap = {};

    ///1为每次清除
    queryMap.putIfAbsent('SyncState', () => '0');

    HttpUtils<BreedingRecordEntity>()
      ..post()
      ..setUrl(APIS.download_breeding_record_list)
      ..setQueryParameters(queryMap)
      ..setIsList()
      ..onResponseList((list) async {
        List<String> ids = [];
        if (kDebugMode) {
          print('接收配种记录数量：${list.length}');
        }

        for (var e in list) {
          e!.uploadStatus = '1';
          ids.add(e!.unid.toString());

          ///保存数据库
          await GlobalService.to.isar.writeTxn(() async {
            await GlobalService.to.isar.breedingRecordEntitys.putByUnid(e);
          });
        }
        SpHelper.putStorage(Config.SP_BREEDING_RECORD_UPDATE_TIME, DateTime.now().toString());
        if (ids.isNotEmpty) {
          breedingRecordListSync(ids);
        } else {
          uploadBreedingRecordList();
        }
        DialogUtils.showToast('配种记录保存完成,数量：${list.length}');
      })
      ..onError((msg, code) {
        uploadBreedingRecordList();
      })
      ..build();
  }

  ///同步保存成功的配种记录id给后台
  breedingRecordListSync(List<String> mList) {
    HttpUtils<void>()
      ..post()
      ..setUrl(APIS.download_breeding_record_list_sync)
      ..setmListParam(mList)
      ..onResponse((response) {
        downloadBreedingRecordList();
      })
      ..onError((msg, code) {
        DialogUtils.showToast('配种记录同步:$code:$msg');
        uploadBreedingRecordList();
      })
      ..build();
  }

  ///上传配种记录数据
  Future<void> uploadBreedingRecordList() async {
    List<BreedingRecordEntity> entityList =
        await GlobalService.to.isar.breedingRecordEntitys.filter().uploadStatusEqualTo('0').limit(10).findAll();

    if (entityList.isNotEmpty) {
      HttpUtils<String>()
        ..post()
        ..setUrl(APIS.upload_breeding_record_List)
        ..setIsList()
        ..setmListParam(entityList)
        ..onResponseList((response) async {
          ///修改上传状态
          for (int i = 0; i < entityList.length; i++) {
            entityList[i].uploadStatus = '2';
            if (response != null) {
              for (int j = 0; j < response!.length; j++) {
                if (entityList[i].unid == response[j]) {
                  entityList[i].uploadStatus = '1';
                }
              }
            }
          }
          await GlobalService.to.isar.writeTxn(() async {
            await GlobalService.to.isar.breedingRecordEntitys.putAll(entityList);
          });
          state.isBreedingRecordCompleteSync = true;
          queryCount();
        })
        ..onError((msg, code) {
          DialogUtils.showToast('$code:$msg');
          state.isBreedingRecordCompleteSync = true;
          queryCount();
        })
        ..build();
    } else {
      state.isBreedingRecordCompleteSync = true;
      queryCount();
    }
  }

  ///==================================配种记录-详情=========================================

  ///下载配种记录-详情
  downloadBreedingRecordDetailList() async {
    Map<String, String> queryMap = {};

    ///1为每次清除
    queryMap.putIfAbsent('SyncState', () => '0');

    HttpUtils<BreedingRecordDetailEntity>()
      ..post()
      ..setUrl(APIS.download_breeding_record_detail_list)
      ..setQueryParameters(queryMap)
      ..setIsList()
      ..onResponseList((list) async {
        List<String> ids = [];
        if (kDebugMode) {
          print('接收配种记录-详情数量：${list.length}');
        }

        for (var e in list) {
          e!.uploadStatus = '1';
          ids.add(e!.unid.toString());

          ///保存数据库
          await GlobalService.to.isar.writeTxn(() async {
            await GlobalService.to.isar.breedingRecordDetailEntitys.putByUnid(e);
          });
        }
        SpHelper.putStorage(Config.SP_BREEDING_RECORD_DETAIL_UPDATE_TIME, DateTime.now().toString());
        if (ids.isNotEmpty) {
          breedingRecordDetailListSync(ids);
        } else {
          uploadBreedingRecordDetailList();
        }
        DialogUtils.showToast('配种记录-详情保存完成,数量：${list.length}');
      })
      ..onError((msg, code) {
        uploadBreedingRecordDetailList();
      })
      ..build();
  }

  ///同步保存成功的配种记录-详情id给后台
  breedingRecordDetailListSync(List<String> mList) {
    HttpUtils<void>()
      ..post()
      ..setUrl(APIS.download_breeding_record_detail_list_sync)
      ..setmListParam(mList)
      ..onResponse((response) {
        downloadBreedingRecordDetailList();
      })
      ..onError((msg, code) {
        DialogUtils.showToast('配种记录-详情同步:$code:$msg');
        uploadBreedingRecordDetailList();
      })
      ..build();
  }

  ///上传配种记录数据-详情
  Future<void> uploadBreedingRecordDetailList() async {
    List<BreedingRecordDetailEntity> entityList =
        await GlobalService.to.isar.breedingRecordDetailEntitys.filter().uploadStatusEqualTo('0').limit(10).findAll();

    if (entityList.isNotEmpty) {
      HttpUtils<String>()
        ..post()
        ..setUrl(APIS.upload_breeding_record_detail_List)
        ..setIsList()
        ..setmListParam(entityList)
        ..onResponseList((response) async {
          ///修改上传状态
          for (int i = 0; i < entityList.length; i++) {
            entityList[i].uploadStatus = '2';
            if (response != null) {
              for (int j = 0; j < response!.length; j++) {
                if (entityList[i].unid == response[j]) {
                  entityList[i].uploadStatus = '1';
                }
              }
            }
          }
          await GlobalService.to.isar.writeTxn(() async {
            await GlobalService.to.isar.breedingRecordDetailEntitys.putAll(entityList);
          });
          state.isBreedingRecordDetailCompleteSync = true;
          queryCount();
        })
        ..onError((msg, code) {
          DialogUtils.showToast('$code:$msg');
          state.isBreedingRecordDetailCompleteSync = true;
          queryCount();
        })
        ..build();
    } else {
      state.isBreedingRecordDetailCompleteSync = true;
      queryCount();
    }
  }
}
