import 'dart:convert';

import 'package:anchor_collect_flutter/utils/empty_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:isar/isar.dart';

import '../../../api/HttpUtils.dart';
import '../../../api/apis.dart';
import '../../../controllers/global_service.dart';
import '../../../generated/json/base/json_convert_content.dart';
import '../../../models/cattle_resume_entity.dart';
import '../../../models/message.dart';
import '../../../routes/routes.dart';
import '../../../utils/dialog_utils.dart';
import 'message_detail_state.dart';

class MessageDetailLogic extends GetxController {
  final MessageDetailState state = MessageDetailState();

  @override
  void onInit() {
    state.entity = Get.arguments;
    initList();
    updateMessageState(state.entity.id ?? '');
  }

  @override
  void onReady() {}

  initList() {
    if (EmptyUtils.isStrNotEmpty(state.entity.detail)) {
      state.cattleResumeList = (jsonDecode(state.entity.detail!) as List)
          .map((e) => jsonConvert.convert<CattleResumeEntity>(e) as CattleResumeEntity)
          .toList();
      print(state.cattleResumeList.length);
      // var detailList = state.entity.detail as List<dynamic>;
      // state.cattleResumeList = detailList.map((item) =>  CattleResumeEntity.fromJson(item as Map<String, dynamic>)).toList();
      // state.cattleResumeList
      update();
      // state.entity.detail=json.decode(state.entity.detail!);
    }
  }

  // getMessageDetail(String id) {
  //   Map<String, String> parameters = {};
  //   parameters.putIfAbsent('id', () => id);
  //   HttpUtils<MessageModel>()
  //     ..get()
  //     ..setUrl(APIS.get_message_detail)
  //     ..setQueryParameters(parameters)
  //     ..showLoading()
  //     ..onResponse((response) {
  //       if (response != null) {
  //         state.entity = response!;
  //         update();
  //       }
  //     })
  //     ..onError((msg, code) {
  //       DialogUtils.showWarningDialog('获取消息详情失败');
  //     })
  //     ..build();
  // }

  ///上传消息已读状态
  updateMessageState(String id) {
    Map<String, String> parameters = {};
    parameters.putIfAbsent('id', () => id);
    parameters.putIfAbsent('state', () => '1');
    HttpUtils<void>()
      ..post()
      ..setUrl(APIS.upload_message_state)
      ..setParams(parameters)
      ..onResponse((response) {
        state.entity.state = '1';
        DialogUtils.showToast('上传消息已读成功');
      })
      ..onError((msg, code) {
        DialogUtils.showWarningDialog('上传消息已读失败');
      })
      ..build();
  }


  queryCattleResume(String unid) async {
    List<CattleResumeEntity> cattleEntityList = await GlobalService.to.isar.cattleResumeEntitys
        .filter()
        .unidEqualTo(unid).findAll();

    if(EmptyUtils.isListNotEmpty(cattleEntityList)){
      Get.toNamed(AppRoute.CATTLE_RESUME, arguments: cattleEntityList[0]);
    }else{
      DialogUtils.showWarningDialog('此耳标数据库不存在，请同步数据');
    }
  }
}
