import 'package:anchor_collect_flutter/congifs.dart';
import 'package:anchor_collect_flutter/models/message_page.dart';
import 'package:anchor_collect_flutter/pages/message/widget/messageItem.dart';
import 'package:anchor_collect_flutter/utils/dialog_utils.dart';
import 'package:anchor_collect_flutter/utils/empty_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../api/HttpUtils.dart';
import '../../api/apis.dart';
import '../../models/message.dart';
import '../../routes/routes.dart';
import '../main/main_logic.dart';
import 'message_state.dart';

class MessageLogic extends GetxController {
  final MessageState state = MessageState();
  MainLogic mainLogic = Get.find<MainLogic>();

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

  void getListData() {
    List<Widget> list = [];

    for (int i = 0; i < state.mListData.length; i++) {
      list.add(MessageItem(
        title: state.mListData[i].title,
        iconData: state.mListData[i].iconData,
        iconColor: state.mListData[i].iconColor,
        count: state.mListData[i].count,
        onItemClick: () {
          if (!Config.isOnLine) {
            DialogUtils.showWarningDialog('请在联机模式查询消息内容');
            return;
          }
          Get.toNamed(AppRoute.MESSAGE_LIST, arguments: state.mListData[i].title);
        },
      ));
    }
    state.items = list;
    update();
  }

  ///获取通知数量
  getMessageCount() {
    if (!Config.isOnLine) {
      return;
    }
    HttpUtils<MessageModel>()
      ..get()
      ..setUrl(APIS.get_message_count)
      ..showLoading()
      ..setIsList()
      ..onResponseList((response) {
        ///设置通知上的小红点
        mainLogic.setMessageStatus(EmptyUtils.isListNotEmpty(response));
        if (EmptyUtils.isListNotEmpty(response)) {
          for (int i = 0; i < response.length; i++) {
            for (int i1 = 0; i1 < state.mListData.length; i1++) {
              if (response[i]?.type == state.mListData[i1].title) {
                state.mListData[i1].count = response[i]?.num ?? 0;
                break;
              }
            }
          }
        }
        update();
      })
      ..onError((msg, code) {
        DialogUtils.showWarningDialog('拉取消息数量失败');
      })
      ..build();
  }
}
