import 'dart:async';

import 'package:zhiying_base_widget/pages/custom_page/event/reload_event.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class CustomItemPageRepository {
  final Map<String, dynamic> data;
  final int tabIndex;
  final String modId;
  final String modPid;

  CustomItemPageRepository(this.data, this.tabIndex, this.modId, this.modPid);

  /// 获取网络Style
  Future<List<Map<String, dynamic>>> fetchNetStyle() async {
    try {
      String reqUrl = _buildRequestUrl();
      if (!EmptyUtil.isEmpty(reqUrl)) {
        var result = await NetUtil.post(reqUrl, method: NetMethod.GET, cache: true);
        if (NetUtil.isSuccess(result) && !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
          List mobList =
              !EmptyUtil.isEmpty(data) ? List.from(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA][tabIndex.toString()]) : List.from(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]);
          if (!EmptyUtil.isEmpty(mobList)) {
            ReloadEvent.com = 0;
            return mobList.map((e) => Map<String, dynamic>.from(e)).toList();
          }
        } else {
          Timer(Duration(milliseconds: 1000), () {
            EventUtil.instance.fire(ReloadEvent());
          });
        }
      }
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }

  /// 获取缓存Style
  Future<List<Map<String, dynamic>>> fetchCacheStyle() async {
    try {
      String reqUrl = _buildRequestUrl();
      if (!EmptyUtil.isEmpty(reqUrl)) {
        var result = await NetUtil.getRequestCachedData(reqUrl);
        if (!EmptyUtil.isEmpty(result)) {
          List mobList = !EmptyUtil.isEmpty(data) ? List.from(result[tabIndex.toString()]) : List.from(result);
          if (!EmptyUtil.isEmpty(mobList)) {
            return mobList.map((e) => Map<String, dynamic>.from(e)).toList();
          }
        }
      }
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }

  String _buildRequestUrl() {
    if (!EmptyUtil.isEmpty(data)) {
      return '/api/v1/custom/mod/$modId';
    } else {
      return '/api/v1/custom/mod/${modPid}?is_cate=1';
    }
  }
}
