import 'dart:async';

// import 'package:amap_all_fluttify/amap_all_fluttify.dart';
import 'package:amap_location_flutter_plugin/amap_location_flutter_plugin.dart';
import 'package:flutter/material.dart';
import 'package:liftmanager/internal/bbs/bbs_router.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/toast.dart';
import 'package:liftmanager/widgets/app_city_search_bar.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/widgets/my_refresh_list.dart';
import 'package:liftmanager/widgets/state_layout.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:liftmanager/widgets/bbs_content.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liftmanager/internal/means/means_router.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'dart:convert';
import 'package:liftmanager/internal/bbs/model/banner_model.dart' as prefix;
import 'package:liftmanager/internal/bbs/presenter/question_list_presenter.dart';
import 'package:liftmanager/internal/bbs/model/mix_model.dart';
import 'package:liftmanager/utils/time_format.dart';
import 'package:liftmanager/utils/url.dart';
import 'package:liftmanager/utils/utils.dart';
import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/internal/account/account_router.dart';
import 'package:liftmanager/utils/theme_utils.dart';

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

// const timeout = const Duration(seconds: 5);

class HospitalPageState
    extends BasePageState<HospitalPage, QuestionListPresenter>
    with AutomaticKeepAliveClientMixin {
  BaseListProvider<Records> provider = BaseListProvider<Records>();
  AmapLocationFlutterPlugin _locationPlugin = new AmapLocationFlutterPlugin();
  StreamSubscription<Map<String, Object>> _locationListener;
  Map<String, Object> _locationResult;
  TabController _tabController;
  PageController _pageController = PageController();
  int _index = 0;
  Timer _timer;
  String _keyword;
  int _page = 1;

  // Location _location;
  String cityName = "暂无定位";

  ///获取定位权限
  Future<bool> requestPermission() async {
    final permissions = await PermissionHandler()
        .requestPermissions([PermissionGroup.location]);
    if (permissions[PermissionGroup.location] == PermissionStatus.granted) {
      return true;
    } else {
      toasts('需要定位权限!');
      return false;
    }
  }

  ///获取位置信息
  getLocation() async {
    if (await requestPermission()) {
      if (null != _locationPlugin) {
        _locationPlugin.startLocation();
      }
    }
  }

//  getCity() async {
//    LatLng latlng = await _location.latLng;
//    ApiService().getCity(latlng.latitude,latlng.longitude,onSuccess: (res){
//
//    },onError: (code,msg){
//
//    });
//  }

  void _onPageChanged(int index) {
    _index = index;
    _tabController.animateTo(index);
  }

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

    

    ///移除定位监听
    if (null != _locationListener) {
      _locationListener.cancel();
    }

    ///销毁定位
    if (null != _locationPlugin) {
      _locationPlugin.destroy();
    }

    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      setState(() {
        _locationPlugin.stopLocation();
        _locationResult = result;
//        address latitude longitude
        _locationResult.forEach((key, value) {
          if(key == 'city'){
            cityName = '$value';
            setState(() {

            });
          }
          print(111);
          print('key:$key :');
          print('value:$value :');
        });
      });
    });


    

    // Future.delayed(Duration.zero, () {
    // //执行代码写在这里
    //   if(FlutterStars.SpUtil.getString(Constant.userId) == "-1"){
    //     toasts("请登录");
    //     NavigatorUtils.push(context, AccountRouter.loginPage, clearStack: true);
    //   }else {
    //     provider.setStateTypeNotNotify(StateType.loading);
    //     _onRefresh();
    //     getBannerList();
    //     getLocation();
    //     // getQuestionList();
    //     print(66666);
    //   }
    // });

    provider.setStateTypeNotNotify(StateType.loading);
        _onRefresh();
        getBannerList();
        getLocation();
        if (!Utils.getAuthByRouter('question_center',false)) {
          getQuestionList();
        }
        
        print(66666);
    
    
  }

  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);
    });
  }

  @override
  void dispose() {
    _tabController?.dispose();
    // _timer.cancel();
    _pageController.dispose();
    ///移除定位监听
    if (null != _locationListener) {
      _locationListener.cancel();
    }

    ///销毁定位
    if (null != _locationPlugin) {
      _locationPlugin.destroy();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<BaseListProvider<Records>>(
        create: (_) => provider,
        child: Scaffold(
          appBar: AppCitySearchAppBar(
            city: "${cityName}",
          ),
          body: Container(
            color: ThemeUtils.getTabsBg(context),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  color: ThemeUtils.getTabsBg(context),
                                        child: Column(
                                          children: <Widget>[
                                            Container(
                                              child: Diagnosis(),
                                            ),
                                            Container(
                                                height: 5,
                                                color: ThemeUtils.getDialogTextFieldColor(context)),
                                            LableTitle(
                                              title: "问题",
                                              userTap: () {
                                                if (Utils.getAuthByRouter('question_center')) {
                                                  NavigatorUtils.push(context, BbsRouter.questionList);
                                                }
                                              },
                                            ),
                                          ],
                                        ),
                                      ),
                Utils.getAuthByRouter('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 Container(
                            child: Column(
                              children: <Widget>[
                                // index == 0
                                //     ? Container(
                                //         child: Column(
                                //           children: <Widget>[
                                //             Container(
                                //               child: Diagnosis(),
                                //             ),
                                //             Container(
                                //                 height: 5,
                                //                 color: Color(0xffeeeeee)),
                                //             LableTitle(
                                //               title: "热门问题",
                                //               userTap: () {
                                //                 NavigatorUtils.push(context,
                                //                     BbsRouter.questionList);
                                //               },
                                //             ),
                                //           ],
                                //         ),
                                //       )
                                //     : Container(child: null),
                                GestureDetector(
                                  child: Container(
                                    padding: EdgeInsets.only(
                                        left: ScreenUtil().setWidth(15),
                                        right: ScreenUtil().setWidth(10),
                                        top: ScreenUtil().setHeight(10),
                                        bottom: ScreenUtil().setHeight(10)),
                                    decoration: BoxDecoration(
                                        border: Border(
                                          bottom: BorderSide(
                                              width: 0.5, color: Colours.line),
                                        ),
                                        color: ThemeUtils.getTabsBg(context)),
                                    child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: <Widget>[
                                          Text(
                                            "[${provider.list[index].brandName}]${provider.list[index].title}",
                                            textAlign: TextAlign.left,
                                            style: TextStyle(
                                                fontSize:
                                                    ScreenUtil().setSp(15)),
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                          Container(
                                            padding: EdgeInsets.only(
                                                top: ScreenUtil().setHeight(10),
                                                bottom:
                                                    ScreenUtil().setHeight(10)),
                                            child: Row(
                                              children: <Widget>[
                                                ClipRRect(
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            ScreenUtil()
                                                                .setWidth(18)),
                                                    child: Container(
                                                      child: LoadNetworkImage(
                                                        provider.list[index]
                                                            .avatarUrl,
                                                        // fit: BoxFit.fitWidth,
                                                        width: ScreenUtil()
                                                            .setWidth(34),
                                                        height: ScreenUtil()
                                                            .setWidth(34),
                                                      ),
                                                    )),
                                                Container(
                                                  padding: EdgeInsets.only(
                                                      left: ScreenUtil()
                                                          .setWidth(10)),
                                                  child: Column(
                                                    crossAxisAlignment:
                                                        CrossAxisAlignment
                                                            .start,
                                                    children: <Widget>[
                                                      Text(
                                                        provider.list[index].userName ??"",
                                                        style: TextStyle(
                                                            fontSize:
                                                                ScreenUtil()
                                                                    .setSp(14),
                                                            ),
                                                      ),
                                                      Text(
                                                        DateUtils.instance
                                                            .getFormartData(
                                                                timeSamp: provider
                                                                    .list[index]
                                                                    .createTime,
                                                                format:
                                                                    "yyyy-MM-dd"),
                                                        style: TextStyle(
                                                            fontSize:
                                                                ScreenUtil()
                                                                    .setSp(12),
                                                            color: Color(
                                                                0xffaaaaaa)),
                                                      ),
                                                    ],
                                                  ),
                                                )
                                              ],
                                            ),
                                          ),
                                          Text(
                                            provider.list[index].expression ??
                                                "",
                                            textAlign: TextAlign.left,
                                            style: TextStyle(
                                              color: Color(0xff666666),
                                              fontSize: ScreenUtil().setSp(14),
                                            ),
                                            maxLines: 2,
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                          Container(
                                            padding: EdgeInsets.only(
                                                top: ScreenUtil().setHeight(5),
                                                bottom:
                                                    ScreenUtil().setHeight(5)),
                                            child: Row(
                                                mainAxisAlignment:
                                                    MainAxisAlignment.start,
                                                children: provider.list[index]
                                                                .imgs !=
                                                            null &&
                                                        provider.list[index]
                                                            .imgs.isNotEmpty
                                                    ? List<Widget>.from(provider
                                                        .list[index].imgs
                                                        .split(",")
                                                        .asMap()
                                                        .keys
                                                        .map((subindex) {
                                                        // print(item);
                                                        return subindex<3?Container(
                                                          padding: subindex <
                                                                  provider
                                                                          .list[
                                                                              index]
                                                                          .imgs
                                                                          .split(
                                                                              ",")
                                                                          .length -
                                                                      1
                                                              ? EdgeInsets.only(
                                                                  right: 6)
                                                              : EdgeInsets.only(
                                                                  right: 0),
                                                          // color:Colors.red,
                                                          // decoration: BoxDecoration(
                                                          //   borderRadius: BorderRadius.circular(20.0),
                                                          // ),
                                                          child: ClipRRect(
                                                            borderRadius:
                                                                BorderRadius
                                                                    .circular(
                                                                        10),
                                                            child:
                                                                LoadNetworkImage(
                                                              // imgFontUrl + item,
                                                              provider
                                                                      .list[index]
                                                                      .imgs
                                                                      .split(
                                                                          ",")[
                                                                  subindex],
                                                              fit: BoxFit.fill,
                                                              height:
                                                                  ScreenUtil()
                                                                      .setWidth(
                                                                          80),
                                                              width:
                                                                  ScreenUtil()
                                                                      .setWidth(
                                                                          110),
                                                              isWater: true,
                                                            ),
                                                          ),
                                                        ):Container(child: null,);
                                                      }).toList())
                                                    : <Widget>[]),
                                          ),
                                          Text(
                                            "${provider.list[index].likeNum}人赞",
                                            textAlign: TextAlign.right,
                                            style: TextStyle(
                                              color: Color(0xff999999),
                                              fontSize: ScreenUtil().setSp(14),
                                            ),
                                          )
                                        ]),
                                  ),
                                  onTap: () {
                                    // print(item);
                                    NavigatorUtils.push(context,
                                        "${BbsRouter.questionDetail}?id=${provider.list[index].id.toString()}");
                                  },
                                )
                              ],
                            ),
                          );
                        },
                      );
                    })):
                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;
}

class _ToolsItem extends StatelessWidget {
  _ToolsItem(this.titles, this.imgs, this.colors, this.onTap, {Key key})
      : super(key: key);

  List<String> titles;
  List<int> imgs;
  List<String> colors;
  Function onTap;

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      shrinkWrap: true,
      padding: const EdgeInsets.fromLTRB(8.0, 0, 8.0, 0),
      physics: NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4, childAspectRatio: 0.9, crossAxisSpacing: 2),
      itemCount: titles.length,
      itemBuilder: (_, index) {
        return InkWell(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                // LoadAssetImage(
                //   "work/${imgs[index]}",
                //   width: 45.0,
                //   height: 45,
                // ),
                Container(
                  width: ScreenUtil().setWidth(40),
                  height: ScreenUtil().setWidth(40),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(20.0),
                    color: Color(
                      int.parse(colors[index]),
                    ),
                  ),
                  child: Icon(
                    IconData(imgs[index], fontFamily: "myfont"),
                    size: 22.0,
                    color: Color.fromRGBO(255, 255, 255, 1),
                  ),
                ),
                Gaps.vGap8,
                Text(titles[index],
                    style: TextStyle(fontSize: ScreenUtil().setSp(14))),
                Gaps.vGap10,
              ],
            ),
            onTap: () {
              onTap(index);
            });
      },
    );
  }
}
