import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:zhiying_base_widget/dialog/loading/loading.dart';
import 'package:zhiying_base_widget/dialog/loading/loading_dialog.dart';
import 'package:zhiying_base_widget/widgets/hot_ranking/hot_ranking_list/model/hot_ranking_list_data_model.dart';
import 'package:zhiying_comm/util/base_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class HotRankingListBloc extends BlocBase {
  HotRankingListDataModel _pageData;

  StreamController<HotRankingListDataModel> _dataController =
      StreamController<HotRankingListDataModel>();

  Stream<HotRankingListDataModel> get outData => _dataController.stream;

  String currentTypeId;

  int currentPage = 1;

  bool isLoading = false;

  @override
  void dispose() {
    _dataController.close();
    _dataController = null;
  }

  void loadData(String typeId, int page, Function complete) {
    if (isLoading) {
      complete();
      return;
    }
    isLoading = true;
    currentTypeId = typeId;
    NetUtil.request(
        '/api/v1/rec/taobao?type_id=' + typeId + '&page=' + page.toString(),
        method: NetMethod.GET, onSuccess: (data) {
      complete();
      isLoading = false;
      _loadData(data);
      Loading.dismiss();
    }, onError: (e) {
      Loading.dismiss();
      complete();
      isLoading = false;
    });
  }

  void loadMoreData(String typeId, Function complete) {
    if (isLoading) {
      complete();
      return;
    }
    currentPage++;
    isLoading = true;
    NetUtil.request(
        '/api/v1/rec/taobao?type_id=' +
            typeId +
            '&page=' +
            currentPage.toString(),
        method: NetMethod.GET, onSuccess: (data) {
      complete();
      isLoading = false;
      _loadMoreData(data);
    }, onError: (e) {
      complete();
      isLoading = false;
    });
  }

  void _loadData(dynamic data) {
    if (_pageData != null && _pageData.good != null) {
      _pageData.good.clear();
      _pageData.good.addAll(HotRankingListDataModel.fromJson(data).good);
    } else {
      _pageData = HotRankingListDataModel.fromJson(data);
    }
    _dataController.add(_pageData);
  }

  void _loadMoreData(dynamic data) {
    if (_pageData != null && _pageData.good != null) {
      _pageData.good.addAll(HotRankingListDataModel.fromJson(data).good);
      _dataController.add(_pageData);
    }
  }
}
// http://192.168.0.113:5000/api/v1/rec/taobao?page=1
// http://192.168.0.113:5000/api/v1/rec/taobao?page=1
