import 'dart:convert';

import 'package:zhiying_base_widget/pages/message_notice_page/model/message_notice_data_model.dart';
import 'package:zhiying_base_widget/pages/message_notice_page/model/message_notice_style_model.dart';
import 'package:zhiying_comm/util/empty_util.dart';
import 'package:zhiying_comm/util/global_config.dart';
import 'package:zhiying_comm/util/log/let_log.dart';
import 'package:zhiying_comm/util/net_util.dart';

class MessageNoticeRepository {
  String _type;
  String _title;

  final int _maxSize = 5;
  int _currentPage = 1;
  bool _hasMoreData = true;
  MessageNoticeStyleModel _styleModel;
  List<MessageNoticeDataItemModel> _oldData = [];

  MessageNoticeRepository(final Map<String, dynamic> data) {
    try {
      _type = !EmptyUtil.isEmpty(data) ? data.containsKey('NoticePageType') ? data['NoticePageType'] : 'main' : 'main';
      _title = !EmptyUtil.isEmpty(data) ? data.containsKey('NoticePageTitle') ? data['NoticePageTitle'] : '消息中心' : '消息中心';
    } catch (e, s) {
      _type = 'main';
    }
  }

  /// 获取样式数据
  MessageNoticeStyleModel getStyleModel() {
    return _styleModel;
  }

  /// 样式初始化(获取网络)
  Future<MessageNoticeStyleModel> fetchNetStyle() async {
    try {
      var result = await NetUtil.post('/api/v1/mod/pub.flutter.message_center', cache: true, method: NetMethod.GET);
      if (NetUtil.isSuccess(result) && !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
        var modListData = result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]['mod_list'][0]['data'];
        if (!EmptyUtil.isEmpty(modListData)) {
          _styleModel = MessageNoticeStyleModel.fromJson(jsonDecode(modListData.toString()));
          if (_type == 'main') {
            _styleModel.isFist = true;
          } else {
            _styleModel.isFist = false;
          }
          _styleModel.styleType = _type;
          _styleModel.styleTitle = _title ?? _styleModel.app_bar_name;
          return _styleModel;
        }
      }
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }

  /// 样式初始化(获取缓存)
  Future<MessageNoticeStyleModel> fetchCachedStyle() async {
    try {
      var result = await NetUtil.getRequestCachedData('/api/v1/mod/pub.flutter.message_center');
      if (!EmptyUtil.isEmpty(result)) {
        var modListData = result['mod_list'][0]['data'];
        if (!EmptyUtil.isEmpty(modListData)) {
          _styleModel = MessageNoticeStyleModel.fromJson(jsonDecode(modListData.toString()));
          if (_type == 'main') {
            _styleModel.isFist = true;
          } else {
            _styleModel.isFist = false;
          }
          _styleModel.styleType = _type;
          _styleModel.styleTitle = _title ?? _styleModel.app_bar_name;
          return _styleModel;
        }
      }
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }

  /// 消除消息红点
  Future<MessageNoticeDataModel> fetchClearPointData(String selectId) async{
    try{
      _oldData.forEach((element){
        if(element.id == selectId) {
          element.unread_count = '';
        }
      });
      return MessageNoticeDataModel()..list = _oldData;
    }catch(e, s){
      Logger.error(e,s);
    }
    return null;
  }

  /// 下拉刷新
  Future<MessageNoticeDataModel> fetchRefreshData() async {
    return fetchInitData();
  }

  /// 上拉更多
  Future<MessageNoticeDataModel> fetchLoadData() async {
    if (_hasMoreData) {
      return _baseRequest();
    }
    return null;
  }

  /// 数据初始化
  Future<MessageNoticeDataModel> fetchInitData() async {
    _currentPage = 1;
    _hasMoreData = true;
    _oldData.clear();
    return _baseRequest();
  }

  /// 基础请求
  Future<MessageNoticeDataModel> _baseRequest() async {
    try {
      var result = await NetUtil.post('/api/v1/user/notice/$_type?page=${_currentPage.toString()}', method: NetMethod.GET);
      if (NetUtil.isSuccess(result) && !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
        MessageNoticeDataModel dataModel = MessageNoticeDataModel.fromJson(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]);
        if (!EmptyUtil.isEmpty(dataModel) && !EmptyUtil.isEmpty(dataModel.list)) {
          // if (dataModel.list.length >= _maxSize) {
          ++_currentPage;
          _hasMoreData = true;
          dataModel.list.insertAll(0, _oldData);
          // }
          _oldData.addAll(dataModel.list);
          return dataModel;
        }
      }
      _hasMoreData = false;
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }
}
