import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:liftmanager/internal/bbs/bbs_router.dart';
import 'package:liftmanager/internal/bbs/model/banner_model.dart' as prefix;
import 'package:liftmanager/internal/bbs/model/mix_model.dart';
import 'package:liftmanager/internal/bbs/presenter/question_list_presenter.dart';
import 'package:liftmanager/internal/search/presenter/base_list_provider.dart';
import 'package:liftmanager/mvp/base_page_state.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/fast_notification.dart';
import 'package:liftmanager/utils/location_helper.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/utils/utils.dart';
import 'package:liftmanager/widgets/app_city_search_bar.dart';
import 'package:liftmanager/widgets/bbs_content.dart';
import 'package:liftmanager/widgets/my_refresh_list.dart';
import 'package:liftmanager/widgets/state_layout.dart';
import 'package:provider/provider.dart';

class HospitalPage extends StatefulWidget {
  @override
  HospitalPageState createState() => HospitalPageState();
}

class HospitalPageState
    extends BasePageState<HospitalPage, QuestionListPresenter>
    with AutomaticKeepAliveClientMixin {
  BaseListProvider<Records> provider = BaseListProvider<Records>();
  StreamSubscription<Map<String, Object>> _locationListener;
  TabController _tabController;
  PageController _pageController = PageController();
  int _page = 1;

  String _cityName;

  bool display = true;

  getLocation() async {
    if (null != _locationListener) {
      _locationListener.cancel();
    }

    var helper = LocationHelper();

    helper.getLocation((lat, lng, cityName, {provinceName}) {
      if (cityName != null) {
        setState(() {
          _cityName = cityName;
        });
        helper.stopGettingLocation();
      }
    });
  }

  @override
  void initState() {
    super.initState();

    provider.setStateTypeNotNotify(StateType.loading);
    getLocation();
    _onRefresh();
    getBannerList();

    getNotificaList();
    FastNotification.addListener("initNotice", (initThisNotice) {
      if (mounted) {
        setState(() {
          getNotificaList();
        });
      }
    });
    if (!Utils.getAuthByRouter(context, 'question_center', false)) {
      getQuestionList();
    }
  }

  List<dynamic> questionsList;

  Future getQuestionList() async {
    await NewApiService().getQuestionList(1, 4, null, null, null,
        onSuccess: (res) {
      // res.records.forEach((item){
      //   questionsList.addAll(item);
      // });

      questionsList = res.records;
      // print(JsonEncoder().convert(res.records));
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  List<dynamic> bannerList;

  Future getBannerList() async {
    await NewApiService().getBanner(1, 3, onSuccess: (prefix.BannerModel res) {
      bannerList = res.records;
      print(bannerList.length);
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future getNotificaList() async {
    display = true;
    await NewApiService().getNotificationMessageList(1, 10, onSuccess: (res) {
      res.records.forEach((item) {
        if (item.viewFlag == 0) {
          setState(() {
            display = false;
          });
          return;
        }
      });
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  @override
  void dispose() {
    _tabController?.dispose();
    // _timer.cancel();
    _pageController.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<BaseListProvider<Records>>(
        create: (_) => provider,
        child: Scaffold(
          appBar: AppCitySearchAppBar(
            city: "${_cityName ?? '暂无定位'}",
            display: display,
          ),
          body: Container(
            // margin:EdgeInsets.only(left: ScreenUtil().setWidth(10),),
            color: ThemeUtils.getTabsBg(context),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  color: ThemeUtils.getTabsBg(context),
                  child: Column(
                    children: <Widget>[
                      Stack(children: <Widget>[
                        ClipPath(
                          clipper: BottomClipper(), //路
                          child: Container(
                            width: double.infinity,
                            height: 100,
                            decoration: BoxDecoration(
                                gradient: const LinearGradient(colors: [
                              Color(0xFF00ACFF),
                              Color(0xFF5888FF)
                            ])),
                          ),
                        ),
                        Container(
                          child: Diagnosis(),
                        )
                      ]),
                      // Container(
                      //     height: 5,
                      //     color: ThemeUtils.getDialogTextFieldColor(context)),
                      Container(
                        // margin: EdgeInsets.only(
                        //   left: 10
                        //   // ScreenUtil().setWidth(10),
                        // ),
                        child: LabelTitle(
                          title: "热门问题",
                          userTap: () {
                            if (Utils.getAuthByRouter(
                                context, 'question_center')) {
                              NavigatorUtils.push(
                                  context, BbsRouter.questionList);
                            }
                          },
                        ),
                      )
                    ],
                  ),
                ),
                Utils.getAuthByRouter(context, 'question_center', false)
                    ? Expanded(
                        flex: 1,
                        child: Consumer<BaseListProvider<Records>>(
                            builder: (_, provider, __) {
                          return MyListView(
                            key: Key('question_list'),
                            itemCount: provider.list.length,
                            stateType: provider.stateType,
                            onRefresh: _onRefresh,
                            loadMore: _loadMore,
                            hasMore: provider.hasMore,
                            itemBuilder: (_, index) {
                              return Padding(
                                padding: EdgeInsets.only(left: 10, right: 10),
                                child: QuestionCell(item: provider.list[index]),
                              );
                            },
                          );
                        }))
                    : Expanded(
                        child: ListView(
                          children: <Widget>[
                            Container(
                                child:
                                    questionsList != null && questionsList != []
                                        ? HotQuestion(initList: questionsList)
                                        : loadCircle()),
                          ],
                        ),
                      )
              ],
            ),
          ),
        ));
  }

  Widget loadCircle() {
    return Container(
      padding: EdgeInsets.only(top: 10, bottom: 10),
      color: ThemeUtils.getTabsBg(context),
      child: Center(
        child: SpinKitFadingCircle(
          color: Colors.blueAccent,
          size: 30.0,
        ),
      ),
    );
  }

  Widget lineTxt(title, value) {
    return Container(
      padding: EdgeInsets.only(left: 12, top: 5, right: 12),
      child: Row(
        children: <Widget>[
          Text("$title",
              style: TextStyle(fontSize: 13, color: Colours.dark_text_gray)),
          Expanded(
            flex: 1,
            child: Text(
              "$value",
              textAlign: TextAlign.right,
              style: TextStyle(fontSize: 13, color: Colours.dark_text_gray),
            ),
          )
        ],
      ),
    );
  }

  Future _onRefresh() async {
    _page = 1;
    await presenter.getQuestionList(_page);
  }

  Future _loadMore() async {
    _page++;
    await presenter.getQuestionList(_page);
  }

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

  bool get wantKeepAlive => true;
}
