import 'package:flutter/material.dart';
import 'package:liftmanager/internal/search/model/search_entity.dart';
import 'package:liftmanager/internal/search/presenter/base_list_provider.dart';
import 'package:liftmanager/internal/search/presenter/search_presenter.dart';
import 'package:liftmanager/mvp/base_page_state.dart';
import 'package:liftmanager/widgets/my_refresh_list.dart';
import 'package:liftmanager/widgets/search_app_bar.dart';
import 'package:liftmanager/widgets/state_layout.dart';
import 'package:provider/provider.dart';


class SearchPage extends StatefulWidget {
  @override
  SearchPageState createState() => SearchPageState();
}

class SearchPageState extends BasePageState<SearchPage, SearchPresenter> {

  BaseListProvider<SearchItem> provider = BaseListProvider<SearchItem>();

  String _keyword;
  int _page = 1;

  @override
  void initState() {
    /// 默认为加载中状态，本页面场景默认为空
    provider.setStateTypeNotNotify(StateType.loading);
    super.initState();
    _onRefresh();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<BaseListProvider<SearchItem>>(
      create: (_) => provider,
      child: Scaffold(
        appBar: SearchAppBar(
          hintText: "请输入需要搜索的内容",
          onPressed: (text){
            if (text.isEmpty){
              showToast("搜索关键字不能为空！");
              return;
            }
            FocusScope.of(context).unfocus();
            _keyword = text;
            provider.setStateType(StateType.loading);
            _page = 1;
            presenter.search(_keyword, _page, true);
          },
        ),
        body: Consumer<BaseListProvider<SearchItem>>(
            builder: (_, provider, __) {
              return MyListView(
                key: Key('order_search_list'),
                itemCount: provider.list.length,
                stateType: provider.stateType,
                onRefresh: _onRefresh,
                loadMore: _loadMore,
                itemExtent: 50.0,
                hasMore: provider.hasMore,
                itemBuilder: (_, index){
                  return Container(
                    padding: const EdgeInsets.symmetric(horizontal: 16.0),
                    alignment: Alignment.centerLeft,
                    child: Text(provider.list[index].name),
                  );
                },
              );
            }
        ),
      ),
    );
  }

  Future _onRefresh() async {
    _page = 1;
    await presenter.search(_keyword, _page, false);
  }

  Future _loadMore() async {
    _page++;
    await presenter.search(_keyword, _page, false);
  }

  @override
  SearchPresenter createPresenter() {
    return SearchPresenter();
  }
}
