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/cattle_resume_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();

  void getSyncItemList() {
    List<Widget> list = [];
    for (int i = 0; i < state.dataList.length; i++) {
      list.add(ListTile(
        title: Text(state.dataList[i].title),
        subtitle: GetBuilder<SyncLogic>(builder: (logic) {
          return
              //   Text(
              //   '待上传:${state.dataList[i].count}, 错误数量:${state.dataList[i].errorCount},更新时间:${state.dataList[i].updateTime ?? ''}',
              //   maxLines: 1,
              //   overflow: TextOverflow.ellipsis,
              // )
              RichText(
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            text: TextSpan(
              children: [
                TextSpan(
                  text: '待上传:${state.dataList[i].count}',
                  style: const TextStyle(color: Colors.green),
                ),
                TextSpan(
                  text: '  错误数量:${state.dataList[i].errorCount}',
                  style: const TextStyle(color: Colors.red),
                ),
                TextSpan(
                  text: '  更新时间:${state.dataList[i].updateTime ?? ''}',
                  style: const TextStyle(color: Colors.black54),
                ),
              ],
            ),
          );
        }),
      ));
      list.add(SizedBox(
        height: 1,
        child: Container(
          height: 1,
          color: Colors.black12,
        ),
      ));
    }
    state.items = list;
    update();
  }

  @override
  void onInit() {
    queryCount();
  }

  queryCount() async {
    state.dataList[0].count = await GlobalService.to.isar.cattleResumeEntitys.filter().uploadStatusEqualTo('0').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);
    update();
  }

  ///同步数据
  syncData() {
    downloadCattleResumeList();
  }

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

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

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

        ///保存图片
        for (var e in list) {
          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());
        }
        queryCount();
        if (ids.isNotEmpty) {
          cattleResumeListSync(ids);
        } else {
          updatecattleResumeList();
        }
        DialogUtils.showToast('保存完成,数量：${list.length}');
      })
      ..onError((msg, code) {})
      ..build();
  }

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

  ///上传基础信息数据
  Future<void> updatecattleResumeList() 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<void>()
        ..post()
        ..setUrl(APIS.upload_Cattle_List)
        ..showLoading()
        ..setmListParam(entityList)
        ..onResponse((response) async {
          DialogUtils.showToast('上传基础数据成功！');

          ///修改上传状态
          for (int i = 0; i < entityList.length; i++) {
            entityList[i].uploadStatus = '1';
            entityList[i].photo = '';
          }
          await GlobalService.to.isar.writeTxn(() async {
            await GlobalService.to.isar.cattleResumeEntitys.putAll(entityList);
          });
          queryCount();
          DialogUtils.showToast('修改基础数据状态成功！');
        })
        ..onError((msg, code) {
          DialogUtils.showWarningDialog('$code:$msg');
        })
        ..build();
    }
  }
}
