import 'dart:async';
import 'dart:convert';

import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/internal/account/account_router.dart';
import 'package:liftmanager/internal/bbs/bbs_router.dart';
import 'package:liftmanager/internal/bbs/model/banner_model.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/bbs/provide/websocket.dart';
import 'package:liftmanager/internal/means/means_router.dart';
import 'package:liftmanager/internal/news/news_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/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/fast_notification.dart';
import 'package:liftmanager/utils/image_utils.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/news_roller.dart';
import 'package:provider/provider.dart';

import '../../../utils/toast.dart';

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();
  List<String> menuTitle = ["案例中心", "视频学堂", "配件商城", "招聘求职", "资料库"];
  List<String> menuImage = ['case', 'video', 'mall', 'recruitment', 'resource'];
  bool display = true;

  String _cityName;
  String _provinceName;
  Timer _timer;
  String latitude;
  String longitude;
  Widget bannerLastWidget;
  List<dynamic> bannerList;
  List<dynamic> questionsList;
  List<dynamic> newsList;
  List<dynamic> videoList;
  List<dynamic> shopList;
  List<dynamic> positionList;
  bool isCustom = false;

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

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

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

    cancelTimer();

    super.dispose();
  }

  getLocation() async {
    var helper = LocationHelper();

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

      latitude = lat;
      longitude = lng;

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

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

  void startTimer(int intervalTime) {
    Duration period = Duration(minutes: intervalTime);
    _timer = Timer.periodic(period, (timer) {
      getStartDelayAddress();
    });
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
  }

  Future isDelayAddress() async {
    await NewApiService().isDelayAddress(onSuccess: (res) {
      print(res["id"]);
      print(jsonEncode(res));
      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 = latitude.toString() + "," + longitude.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) {}, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future getBannerList() async {
    await NewApiService().getBanner(1, 10, onSuccess: (BannerModel res) {
      bannerList = res.records;
      bannerLastWidget = Stack(
        children: [
          SizedBox(
            width: double.infinity,
            height: 40,
            child: Image.asset(
              ImageUtils.getImgPath('background_arch_blue'),
              fit: BoxFit.fill,
            ),
          ),
          Container(
            margin: EdgeInsets.all(10),
            child: SwipeWidget(
              banners: bannerList,
            ),
          )
        ],
      );
      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);
    });
  }

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

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

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

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

  Future getPositionList() async {
    await NewApiService().getPositionList(1, 3, onSuccess: (res) {
      positionList = res.records;
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  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 ChangeNotifierProvider<BaseListProvider<NewsItem>>(
      create: (_) => provider,
      child: RefreshIndicator(
          onRefresh: () async {
            setState(() {
              bannerLastWidget = null;
              getLocation();
              getBannerList();
              getNewsList();
              getQuestionList();
              getVideoList();
              getShopList();
              getPositionList();
            });
          },
          child: Scaffold(
            appBar: AppCitySearchAppBar(
                city: "${_cityName ?? '暂无定位'}", display: display),
            backgroundColor: Colors.transparent,
            body: Container(
                child: CustomScrollView(
              slivers: [
                SliverList(
                    delegate: SliverChildListDelegate([
                  bannerLastWidget != null
                      ? bannerLastWidget
                      : Container(child: loadCircle()),
                  Container(
                      padding: EdgeInsets.only(top: 10),
                      height: 100,
                      color: ThemeUtils.getTabsBg(context),
                      child: quickEntriesSection()),
                  ClipRRect(
                      child: Container(
                          padding: EdgeInsets.fromLTRB(10, 10, 0, 10),
                          margin: EdgeInsets.fromLTRB(10, 0, 10, 10),
                          height: 63,
                          decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.all(
                                Radius.circular(10),
                              ),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.grey.withOpacity(0.2),
                                  spreadRadius: 1,
                                  blurRadius: 3,
                                  offset: Offset(
                                      0, 3), // changes position of shadow
                                ),
                              ]),
                          child:
                              newsList != null ? newsSection() : loadCircle())),
                  LabelTitle(
                    title: "热门视频",
                    userTap: () {
                      if (!Utils.getAuthByRouter(
                              context, 'video_center', false) &&
                          isCustom) {
                        showAlertEvent();
                      } else {
                        if (Utils.getAuthByRouter(context, 'video_center')) {
                          NavigatorUtils.push(context, BbsRouter.videoList);
                        }
                      }
                    },
                  ),
                ])),
                if (videoList != null && videoList.length > 0)
                  SliverPadding(
                    padding: EdgeInsets.only(
                        left: 10, right: 10, top: 10, bottom: 20),
                    sliver: SliverGrid.count(
                      crossAxisCount: 2,
                      crossAxisSpacing: 10,
                      mainAxisSpacing: 15,
                      childAspectRatio: 1,
                      children:
                          HotClass(videoList: videoList).listWidget(context),
                    ),
                  ),
                SliverList(
                  delegate: SliverChildListDelegate(
                    [
                      Container(
                        height: 10,
                        color: Color(0xffF9F9F9),
                      ),
                      LabelTitle(
                        title: "热销商品",
                        userTap: () {
                          if (!Utils.getAuthByRouter(
                                  context, 'shopping_center', false) &&
                              isCustom) {
                            showAlertEvent();
                          } else {
                            if (Utils.getAuthByRouter(
                                context, 'shopping_center')) {
                              NavigatorUtils.push(
                                  context, BbsRouter.productList);
                            }
                          }
                        },
                      ),
                      Container(
                          padding: EdgeInsets.symmetric(horizontal: 10),
                          child: shopList != null && shopList.length > 0
                              ? HotProduct(productList: shopList)
                              : loadCircle()),
                      SizedBox(
                        height: 10,
                      ),
                      Container(
                        height: 10,
                        color: Color(0xffF9F9F9),
                      ),
                      LabelTitle(
                        title: "热门问题",
                        userTap: () {
                          if (!Utils.getAuthByRouter(
                                  context, 'question_center', false) &&
                              isCustom) {
                            showAlertEvent();
                          } else {
                            if (Utils.getAuthByRouter(
                                context, 'question_center')) {
                              NavigatorUtils.push(
                                  context, BbsRouter.questionList);
                            }
                          }
                        },
                      ),
                      Container(
                          child:
                              questionsList != null && questionsList.length > 0
                                  ? HotQuestion(initList: questionsList)
                                  : loadCircle()),
                      Container(
                        height: 10,
                        color: Color(0xffF9F9F9),
                      ),
                      LabelTitle(
                        title: "热招职位",
                        userTap: () {
                          if (!Utils.getAuthByRouter(
                                  context, 'job_center', false) &&
                              isCustom) {
                            showAlertEvent();
                          } else {
                            if (Utils.getAuthByRouter(context, 'job_center')) {
                              NavigatorUtils.push(context,
                                  "${BbsRouter.positionList}?city=${Uri.encodeComponent(_cityName ?? '')}&provinceName=${Uri.encodeComponent(_provinceName ?? '')}");
                            }
                          }
                        },
                      ),
                      Container(
                          padding: EdgeInsets.symmetric(
                              horizontal: 10, vertical: 10),
                          color: ThemeUtils.getTabsBg(context),
                          child: positionList != null && positionList.length > 0
                              ? HotPosition(positionList: positionList)
                              : loadCircle()),
                    ],
                  ),
                )
              ],
            )),
          )),
    );
  }

  Widget quickEntriesSection() => _ToolsItem(menuTitle, menuImage, (index) {
        if (index == 0) {
          if (!Utils.getAuthByRouter(context, 'question_center', false) &&
              isCustom) {
            showAlertEvent();
          } else if (Utils.getAuthByRouter(context, 'question_center')) {
            NavigatorUtils.push(context, BbsRouter.questionList);
          }
        } else if (index == 1) {
          if (!Utils.getAuthByRouter(context, 'video_center', false) &&
              isCustom) {
            showAlertEvent();
          } else if (Utils.getAuthByRouter(context, 'video_center')) {
            NavigatorUtils.push(context, BbsRouter.videoList);
          }
        } else if (index == 2) {
          if (!Utils.getAuthByRouter(context, 'shopping_center', false) &&
              isCustom) {
            showAlertEvent();
          } else if (Utils.getAuthByRouter(context, 'shopping_center')) {
            NavigatorUtils.push(context, BbsRouter.productList);
          }
        } else if (index == 3) {
          if (!Utils.getAuthByRouter(context, 'job_center', false) &&
              isCustom) {
            showAlertEvent();
          } else if (Utils.getAuthByRouter(context, 'job_center')) {
            // _cityName = '武汉市';
            // _provinceName = '湖北省';

            NavigatorUtils.push(context,
                "${BbsRouter.positionList}?city=${Uri.encodeComponent(_cityName ?? '')}&provinceName=${Uri.encodeComponent(_provinceName ?? '')}");
          }
        } else if (index == 4) {
          if (!Utils.getAuthByRouter(context, 'database', false) && isCustom) {
            showAlertEvent();
          } else if (Utils.getAuthByRouter(context, 'database')) {
            NavigatorUtils.push(context, MeansRouter.meansPage);
          }
        }
      });

  Widget newsSection() =>
      Row(crossAxisAlignment: CrossAxisAlignment.center, children: [
        Image.asset(ImageUtils.getImgPath('hotnews')),
        Expanded(child: NewsRoller(newsList), flex: 1),
        Expanded(
            flex: 0,
            child: GestureDetector(
              onTap: () {
                if (!Utils.getAuthByRouter(context, 'news', false) &&
                    isCustom) {
                  showAlertEvent();
                } else {
                  if (Utils.getAuthByRouter(context, 'news')) {
                    NavigatorUtils.push(context, NewsRouter.newsTopList);
                  }
                }
              },
              child: Container(
                  width: 40,
                  height: 21,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      gradient: LinearGradient(colors: [
                        Color(0xff00ACFF),
                        Color(0xff568AFF),
                      ]),
                      borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(10),
                          bottomLeft: Radius.circular(10))),
                  child: Text(
                    '更多',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 11,
                    ),
                  )),
            ))
      ]);

  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.onTap, {Key key}) : super(key: key);

  final List<String> titles;
  final List<String> imgs;
  final Function onTap;

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      shrinkWrap: true,
      padding: const EdgeInsets.fromLTRB(0, 0, 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>[
              Image.asset(ImageUtils.getImgPath(imgs[index])),
              Expanded(
                  child: Text(
                titles[index],
                style: TextStyle(fontSize: ScreenUtil().setSp(12)),
              )),
            ],
          ),
          onTap: () {
            onTap(index);
          },
        );
      },
    );
  }
}
