import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:zhiying_base_widget/pages/search_think_page/bloc/search_think_repository.dart';
import 'package:zhiying_base_widget/pages/search_think_page/model/search_think_model.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

part 'search_think_event.dart';

part 'search_think_state.dart';

class SearchThinkBloc extends Bloc<SearchThinkEvent, SearchThinkState> {
  // SearchThinkBloc() : super(SearchThinkInitial());
  @override
  SearchThinkState get initialState => SearchThinkInitial();

  SearchThinkRepository repository;

  SearchThinkBloc(this.repository);

  @override
  Stream<SearchThinkState> mapEventToState(SearchThinkEvent event,) async* {

    /// 关键字改变的方法
    if (event is SearchThinkKeyWrodsChangeEvent) {
      yield* _mapKeyWordsChangeToState(event);
    }

    /// 修改渠道关键字
    if (event is SearchThinkChangeTypeEvent) {
      _mapChangeTypeToState(event);
    }

    /// 显示原本的视图
    if (event is SearchThinkShowBaseViewEvent) {
      yield* _mapShowBaseViewEventToState();
    }
  }

  /// 关键字改变的方法
  Stream<SearchThinkState> _mapKeyWordsChangeToState(SearchThinkKeyWrodsChangeEvent event) async* {
    var result = await repository.fetchkeyWordsChange(event.keywords);
    if (!EmptyUtil.isEmpty(result)) {
      yield SearchThinkLoadedState(result);
    } else {
      yield SearchThinkErrorState();
    }
  }

  /// 显示原本的视图
  Stream<SearchThinkState> _mapShowBaseViewEventToState() async* {
    yield SearchThinkShowBaseViewStatte();
  }

  /// 修改商品电商类型
  _mapChangeTypeToState(SearchThinkChangeTypeEvent event) {
    repository.changeType(event.type);
  }
}
