

// import 'package:amap_all_fluttify/amap_all_fluttify.dart';
import 'package:amap_location_flutter_plugin/amap_location_flutter_plugin.dart';
import 'package:amap_location_flutter_plugin/amap_location_option.dart';
import 'package:flutter/material.dart';
import 'package:liftmanager/internal/bbs/bbs_router.dart';
import 'package:liftmanager/internal/bbs/model/news_comm_entity.dart';
import 'package:liftmanager/internal/bbs/presenter/news_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/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 '../../../utils/toast.dart';
import 'package:liftmanager/internal/means/means_router.dart';
// import '../model/question_model.dart' as qItem;
import 'dart:convert';
import 'package:liftmanager/utils/fast_notification.dart';
import 'package:liftmanager/internal/bbs/model/banner_model.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:liftmanager/utils/utils.dart';
import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:liftmanager/internal/bbs/provide/websocket.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/internal/account/account_router.dart';
import 'package:liftmanager/internal/news/news_router.dart';
import 'package:uni_links/uni_links.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'dart:async';

class BbsPage extends StatefulWidget {
  @override
  BbsPageState createState() => BbsPageState();
}

const timeout = const Duration(seconds: 5);

class BbsPageState extends BasePageState<BbsPage, NewsListPresenter>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  BaseListProvider<NewsItem> provider = BaseListProvider<NewsItem>();
  TabController _tabController;
  PageController _pageController = PageController();
  AmapLocationFlutterPlugin _locationPlugin = new AmapLocationFlutterPlugin();
  StreamSubscription<Map<String, Object>> _locationListener;
  Map<String, Object> _locationResult;
  int _index = 0;
  String _keyword;
  int _page = 1;
  List<String> menuTitle = ["案例中心", "视频学堂", "在线商城", "招聘专区", "资料库"];
  List<int> menuImage = [0xe674, 0xe600, 0xe680, 0xe705, 0xe648];
  List<String> menuColor = [
    "0xffFE6965",
    "0xff5C6BFA",
    "0xffFA8113",
    "0xff2EBA7F",
    "0xff118DFF"
  ];
  bool display = true;
  // Location _location;
  String cityName = "暂无定位";
  StateType _stateType = StateType.loading;

  ///获取定位权限
  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();
      }
    }
  }
//   ///获取位置信息
//   getLocation() async {
//     if (await requestPermission()) {
//       final location = await AmapLocation.fetchLocation();
//       cityName = await location.city;
//       print(cityName + "456456465");
//       LatLng latlng = await location.latLng;
//       print(latlng.latitude);
//       print(latlng.longitude);
//       print(latlng);
//       setState(() {});
// //      getCity();
//     }
//   }

//  getCity() async {
//    LatLng latlng = await _location.latLng;
//    ApiService().getCity(latlng.latitude,latlng.longitude,onSuccess: (res){
//
//    },onError: (code,msg){
//
//    });
//  }
  @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
        lat = _locationResult["latitude"];
        lng = _locationResult["longitude"];
        cityName = _locationResult["city"];
        if(FlutterStars.SpUtil.getString(Constant.userId) != "-1") {
          isDelayAddress();
        }
      });
    });

    if(FlutterStars.SpUtil.getString(Constant.userId) != "-1") {
      Provider.of<WebSocketProvide>(context,listen: false).createWebsocket(FlutterStars.SpUtil.getString(Constant.userId));
    }

    
    getLocation();
    getBannerList();
    getNewsList();
    getQuestionList();
    getVideoList();
    getShopList();
    getPositionList();
    getNotificaList();
    _initFluwx();
    FastNotification.addListener("initNotice",(initThisNotice){
      if(mounted){
        setState(() {
          
          getNotificaList();
        });
      }
    });

    if(FlutterStars.SpUtil.getString(Constant.userId) == "-1"){
      isCustom = true;
    }
     
  }

  _initFluwx() async {
    await fluwx.registerWxApi(
        appId: "wx0f10e6386fb9969e",
        doOnAndroid: true,
        doOnIOS: true,
        universalLink: "https://www.edtyun.com/");
    var result = await fluwx.isWeChatInstalled();
    setState(() {});
  }

  Timer _timer;
  void startTimer(int intervalTime) {
    //设置 intervalTime 秒回调一次
    print(1234);
    Duration period = Duration(minutes: intervalTime);
    _timer = Timer.periodic(period, (timer) {
      print(1236);
      getStartDelayAddress();
    });
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
  }
  double lat;
  double lng;
  Widget bannerLastWidget;
  List<dynamic> bannerList;
  List<dynamic> questionsList;
  List<dynamic> newsList;
  List<dynamic> videoList;
  List<dynamic> shopList;
  List<dynamic> positionList;
  bool isCustom = false;
  Future isDelayAddress() async {
    await NewApiService().isDelayAddress(onSuccess: (res) {
      print("665-------------------////");
      print(res["id"]);
      print(jsonEncode(res));
      print("666-------------------////");
      if(res["isPush"]!=null && res["isPush"] == 1){
        getStartDelayAddress();
        startTimer(res["intervalTime"]);
      }
      //intervalTime:时间间隔分钟 ; isPush:1推送 2不推送
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future getStartDelayAddress() async {
    String position = lat.toString() +","+ lng.toString();
    await NewApiService().startDelayAddress(
      {
        "mobile":FlutterStars.SpUtil.getString(Constant.phone),
        "mtCompanyId":FlutterStars.SpUtil.getString(Constant.companyId)!=""?int.parse(FlutterStars.SpUtil.getString(Constant.companyId)):"",
        "position":position,
        "userId":int.parse(FlutterStars.SpUtil.getString(Constant.userId))
      }
      ,onSuccess: (res) {
      
      print("668-------------------////");
      
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future getBannerList() async {
    await NewApiService().getBanner(1, 10, onSuccess: (BannerModel res) {
      // print(jsonEncode(res));
      // print(JsonEncoder().convert(res.records));
      bannerList = res.records;
      bannerLastWidget = SwipeWidget(banners: bannerList,);
      // print(bannerList.length);
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future getNotificaList() async {
    display = true;
    await NewApiService().myNotificaList(1, 10, onSuccess: (res) {
      // print(jsonEncode(res));
      // print(JsonEncoder().convert(res.records));
      res.records.forEach((item){
        if(item.viewFlag == 0){
          setState(() {
            display = false;
          });
          return;
        }
      });
      // print(bannerList.length);
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future getNewsList() async {
    await NewApiService().newsList(1, 3, 1, "", cityName, onSuccess: (res) {
      newsList = res.topNews;
      // print(JsonEncoder().convert(res.topNews));
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future getQuestionList() async {
    await NewApiService().getQuestionList(1, 2, 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);
    });
  }

  Future getVideoList() async {
    await NewApiService().getVideoList(1, 3, null, null, null, "app",
        onSuccess: (res) {
      videoList = res.records;
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future getShopList() async {
    await NewApiService().getShopList(1, 2, null, null, onSuccess: (res) {
      shopList = res.records;
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future getPositionList() async {
    await NewApiService().getPositionList(1, 3, onSuccess: (res) {
      // res.records.forEach((item){
      //   questionsList.addAll(item);
      // });
      positionList = res.records;
      // print(JsonEncoder().convert(res.records));
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

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

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

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

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

  static const diagnosisObj = [
    {
      "title": "快速问诊",
      "img": "tab_first/Diagnosis_first",
      "desc": "搜电梯品牌 找专家咨询电梯疑问",
    },
    {
      "title": "出诊",
      "img": "tab_first/Diagnosis_second",
      "desc": "在线预约专家上门维修服务",
    },
  ];
  static const diagnosisObjMaster = [
    {
      "title": "工作台",
      "img": "tab_first/Diagnosis_third",
      "desc": "问诊、出诊工作快捷入口",
    },
  ];

  showAlertEvent(){
    showAlert(
                              context,
                              "提示",
                              "确定登录？",
                              "确定",
                              () {
                                NavigatorUtils.push(context, AccountRouter.loginPage, clearStack: true);
                              },
                              txt2: "取消",
                              onPre2: () {
                                NavigatorUtils.goBack(context);
                              },
                            );
  }

  @override
  Widget build(BuildContext context) {
    return 
    RefreshIndicator(
        onRefresh:()async{
          
          print("123----------------------------------");
          setState(() {
            bannerLastWidget = null;
            getLocation();
            getBannerList();
            getNewsList();
            getQuestionList();
            getVideoList();
            getShopList();
            getPositionList();
          });
        },
        child: ChangeNotifierProvider<BaseListProvider<NewsItem>>(
        create: (_) => provider,
        child: Scaffold(
          appBar: AppCitySearchAppBar(
            // city: "暂无定位",
            city: "${cityName}",
            display:display
          ),
          body: Container(
            color: ThemeUtils.getTabsBg(context),
            child: ListView(
              children: <Widget>[
                bannerLastWidget != null
                    ? bannerLastWidget
                    : Container(child: loadCircle()),
                Container(
                  padding: EdgeInsets.only(top: 10),
                  color: ThemeUtils.getTabsBg(context),
                  child: _ToolsItem(menuTitle, menuImage, menuColor, (index) {
                      
                      if (index == 0) {
                        if (!Utils.getAuthByRouter('question_center',false) && isCustom){
                          showAlertEvent();
                        }else if (Utils.getAuthByRouter('question_center')){
                          NavigatorUtils.push(context, BbsRouter.questionList);
                        }
                      } else if (index == 1) {
                        // if (Utils.getAuthByRouter('video_center')) {
                        //   NavigatorUtils.push(context, BbsRouter.videoList);
                        // }else if (!Utils.getAuthByRouter('video_center',false) && isCustom){
                        //   showAlertEvent();
                        // }

                        if (!Utils.getAuthByRouter('video_center',false) && isCustom){
                          showAlertEvent();
                        }else if (Utils.getAuthByRouter('video_center')){
                          NavigatorUtils.push(context, BbsRouter.videoList);
                        }
                      } else if (index == 2) {
                        // if (Utils.getAuthByRouter('shopping_center')) {
                        //   NavigatorUtils.push(context, BbsRouter.productList);
                        // }else if (!Utils.getAuthByRouter('shopping_center',false) && isCustom){
                        //   showAlertEvent();
                        // }

                        if (!Utils.getAuthByRouter('shopping_center',false) && isCustom){
                          showAlertEvent();
                        }else if (Utils.getAuthByRouter('shopping_center')){
                          NavigatorUtils.push(context, BbsRouter.productList);
                        }
                      } else if (index == 3) {
                        // if (Utils.getAuthByRouter('job_center')) {
                        //   NavigatorUtils.push(context, BbsRouter.positionList);
                        // }else if (!Utils.getAuthByRouter('job_center',false) && isCustom){
                        //   showAlertEvent();
                        // }

                        if (!Utils.getAuthByRouter('job_center',false) && isCustom){
                          showAlertEvent();
                        }else if (Utils.getAuthByRouter('job_center')){
                          NavigatorUtils.push(context, BbsRouter.positionList);
                        }
                      } else if (index == 4) {
                        if (!Utils.getAuthByRouter('database',false) && isCustom){
                          showAlertEvent();
                        }else if (Utils.getAuthByRouter('database')){
                          NavigatorUtils.push(context, MeansRouter.meansPage);
                        }
                      }
                    
                    
                  }),
                ),
                Container(height: 5, color: ThemeUtils.getDialogTextFieldColor(context)),
                LableTitle(
                  title: "新闻",
                  userTap: () {
                    if(isCustom){
                      showAlertEvent();
                    }else {
                      NavigatorUtils.push(context, NewsRouter.newsTopList);
                    }
                  },
                ),
                Container(
                    color: Colors.white,
                    // padding: EdgeInsets.only(bottom: 20),
                    child: newsList != null && newsList != []
                        ? HotNews(newsList: newsList)
                        : loadCircle()),
                Container(height: 5, color: ThemeUtils.getDialogTextFieldColor(context)),
                LableTitle(
                  title: "问题",
                  userTap: () {
                    if (!Utils.getAuthByRouter('question_center',false) && isCustom){
                          showAlertEvent();
                        }
                    else {
                      if (Utils.getAuthByRouter('question_center')) {
                          NavigatorUtils.push(context, BbsRouter.questionList);
                        }
                    }
                    // NavigatorUtils.push(context, BbsRouter.chatRoom);
                  },
                ),
                // Expanded(
                //     flex: 1,
                //     child: HotQuestion(),
                // )
                Container(
                    child: questionsList != null && questionsList != []
                        ? HotQuestion(initList: questionsList)
                        : loadCircle()),
                Container(height: 5, color: ThemeUtils.getDialogTextFieldColor(context)),
                LableTitle(
                  title: "学堂",
                  userTap: () {
                    if (!Utils.getAuthByRouter('video_center',false) && isCustom){
                          showAlertEvent();
                        }else {
                      if (Utils.getAuthByRouter('video_center')) {
                          NavigatorUtils.push(context, BbsRouter.videoList);
                        }
                    }
                  },
                ),
                videoList != null && videoList != []
                    ? Container(
                        color: ThemeUtils.getTabsBg(context),
                        height: ScreenUtil().setWidth(210),
                        padding:
                            EdgeInsets.only(top: ScreenUtil().setWidth(10)),
                        child: HotClass(initList: videoList),
                      )
                    : Container(child: loadCircle()),
                Container(height: 5, color: ThemeUtils.getDialogTextFieldColor(context)),
                LableTitle(
                  title: "商品",
                  userTap: () {
                    // if(isCustom){
                    //   toasts("请登录");
                    //   NavigatorUtils.push(context, AccountRouter.loginPage, clearStack: true);
                    // }else {
                    //   if (Utils.getAuthByRouter('shopping_center')) {
                    //       NavigatorUtils.push(context, BbsRouter.productList);
                    //     }
                    // }
                    if (!Utils.getAuthByRouter('shopping_center',false) && isCustom){
                          showAlertEvent();
                        }
                    else {
                      if(Utils.getAuthByRouter('shopping_center')) {
                          NavigatorUtils.push(context, BbsRouter.productList);
                        }
                    }
                    
                  },
                ),
                Container(  
                    child: shopList != null && shopList != []
                        ? HotProduct(productList: shopList)
                        : loadCircle()),
                Container(height: 5, color: ThemeUtils.getDialogTextFieldColor(context)),
                LableTitle(
                  title: "职位",
                  userTap: () {
                    // if(isCustom){
                    //   toasts("请登录");
                    //   NavigatorUtils.push(context, AccountRouter.loginPage, clearStack: true);
                    // }else {
                    //   if (Utils.getAuthByRouter('job_center')) {
                    //       NavigatorUtils.push(context, BbsRouter.positionList);
                    //     }
                    // }
                    if (!Utils.getAuthByRouter('job_center',false) && isCustom){
                          showAlertEvent();
                        }else {
                          if (Utils.getAuthByRouter('job_center')) {
                          NavigatorUtils.push(context, BbsRouter.positionList);
                        }
                        }
                    
                  },
                ),
                Container(
                    color: ThemeUtils.getTabsBg(context),
                    padding: EdgeInsets.only(bottom: 20),
                    child: positionList != null && positionList != []
                        ? HotPosition(positionList: positionList)
                        : loadCircle()),

                // Container(
                //   child:GestureDetector(
                //     child: Text("0000000"),
                //     onTap: (){
                //       Map<String,dynamic> cc = FlutterStars.SpUtil.getObj("vgfhvfk", (v){
                //        return v;
                //      });
                //      print(cc);
                //      print(6556);
                //       Map<String,dynamic> res = {
                //         "one3":"1"
                //       };
                //      Map<String,dynamic> a = FlutterStars.SpUtil.getObj("sessionIdObj", (v){
                //        return v;
                //      });
                //      a.addAll(res);
                //       FlutterStars.SpUtil.putObject("sessionIdObj", a);

                //       print(a["one3"]);
                //       print(123);
                //     },
                //   )
                // ),
                // SizedBox(
                //   height:300,
                // ),
                // Container(
                //   child:GestureDetector(
                //     child: Text("11111111"),
                //     onTap: (){
                //       Map<String,dynamic> res = {
                //         "two3":"2"
                //       };
                //       Map<String,dynamic> a = FlutterStars.SpUtil.getObj("sessionIdObj", (v){
                //        return v;
                //      });
                //      a.addAll(res);
                //       FlutterStars.SpUtil.putObject("sessionIdObj", a);

                //       print(a);
                //       print(123);
                //       print(123);
                //     },
                //   )
                // ),
              ],
            ),
          ),
        )),
    )
    ;
  }

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

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

  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: 5, childAspectRatio: 0.9, crossAxisSpacing: 2),
      itemCount: titles.length,
      itemBuilder: (_, index) {
        return InkWell(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              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(12)),
              ),
              Gaps.vGap10,
            ],
          ),
          onTap: () {
            onTap(index);
          },
        );
      },
    );
  }
}
