import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:huixiang/community/headlines/headlines_collection.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/main.dart';
import 'package:huixiang/retrofit/data/article.dart';
import 'package:huixiang/retrofit/data/banner.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/brand.dart';
import 'package:huixiang/retrofit/data/headlines_list.dart';
import 'package:huixiang/retrofit/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/event_type.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/view_widget/classic_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:huixiang/view_widget/my_footer.dart';
import 'package:huixiang/view_widget/store_title_tab.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'activity_top_list.dart';
import 'article_list.dart';

class ArticlePage extends StatefulWidget {
  final Function onScroll;

  ArticlePage(this.onScroll);

  @override
  State<StatefulWidget> createState() {
    return _ArticlePage();
  }
}

class _ArticlePage extends State<ArticlePage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  final RefreshController refreshController = RefreshController();
  ScrollController sc = ScrollController();

  ApiService apiService;
  List<GlobalKey> globaKeys = [];
  List<Brand> brands = [];
  List<BannerData> bannerData = [];
  List<Article> articles = [];
  List<Article> articleTop = [];
  List<HeadlinesList> headlines = [];
  int pageNum = 1;
  bool isLoading = false;

  @override
  void initState() {
    super.initState();
    sc.addListener(() {
      widget.onScroll();
    });
    eventBus.on<EventType>().listen((event) {
      print("object: ArticlePage");
      if (event.type < 3) {
        setState(() {});
      }
    });
    queryArticleList(false);
    queryArticleList(true);
    queryHeadlinesBanner();
    queryHeadlinesList();
  }

  @override
  void dispose() {
    super.dispose();
    refreshController.dispose();
  }

  ///banner
  queryHeadlinesBanner() async {
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(
        Dio(),
        context: context,
        token: value.getString("token"),
      );
    }
    BaseData<PageInfo<BannerData>> baseData = await apiService.queryBanner({
      "model": {"type": "INFORMATION"},
    }).catchError((onError) {
      refreshController.refreshFailed();
    });
    if (baseData != null && baseData.isSuccess) {
      bannerData.clear();
      bannerData.addAll(baseData.data.records);
      refreshController.refreshCompleted();
    } else {
      refreshController.refreshFailed();
      // SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
    }
    EasyLoading.dismiss();
  }

  ///文章列表
  queryArticleList(bool isHot) async {
    if(!isHot && isLoading){
      return;
    }else if(!isHot && !isLoading){
      isLoading = true;
    }
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(
        Dio(),
        context: context,
        token: value.getString("token"),
      );
    }
    BaseData<PageInfo<Article>> baseData = await apiService.queryArticle({
      "pageNum": pageNum,
      "pageSize": 10,
      "searchKey": "",
      "state": 1,
      "type": 2,
      "storeId":"",
      "isHot":isHot
    }).catchError((onError) {
      refreshController.refreshFailed();
      refreshController.loadFailed();
    });
    if (baseData != null && baseData.isSuccess) {
      refreshController.refreshCompleted();
      refreshController.loadComplete();
      if (pageNum == 1) {
        if(!isHot)
        articles.clear();
        else
        articleTop.clear();
      }
      if(!isHot)
      articles.addAll(baseData.data.list);
      else
      articleTop.addAll(baseData.data.list);
      if (baseData.data.pageNum == baseData.data.pages && !isHot) {
        refreshController.loadNoData();
      } else {
        pageNum += 1;
        refreshController.loadComplete();
      }
      isLoading = false;
      setState(() {});
    } else {
      refreshController.refreshFailed();
      refreshController.loadFailed();
    }
  }

  ///文章合集列表
  queryHeadlinesList() async {
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(
        Dio(),
        context: context,
        token: value.getString("token"),
      );
    }
    BaseData<List<HeadlinesList>> baseData =
        await apiService.headlinesList().catchError((onError) {});
    if (baseData != null && baseData.isSuccess) {
      setState(() {
        headlines.clear();
        headlines.addAll(baseData.data);
        headlines.forEach((element) {
          // collectCourse(element.id);
        });
      });
    }
    EasyLoading.dismiss();
  }

  _onRefresh() {
    isLoading = true;
    pageNum = 1;
    queryHeadlinesBanner();
    queryHeadlinesList(); //分类列表
    queryArticleList(false);
    queryArticleList(true);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Stack(
      children: [
        Positioned(
          child: Container(
            child: SmartRefresher(
              controller: refreshController,
              enablePullDown: true,
              enablePullUp:true,
              header: MyHeader(),
              footer: CustomFooter(
                builder: (context, mode) {
                  return MyFooter(mode);
                },
              ),
              onRefresh: _onRefresh,
              onLoading: () {
                queryArticleList(false);
              },
              physics: BouncingScrollPhysics(),
              scrollController: sc,
              child: Container(
                child: SingleChildScrollView(
                  physics: BouncingScrollPhysics(),
                  child: Container(
                    color: Color(0xFFF7F7F7),
                    margin: EdgeInsets.only(top: 16.h),
                    child: Column(
                      children: classChildItem(),
                    ),
                  ),
                ),
              ),
            ),
          ),
          bottom: 0,
          top: 0,
          left: 0,
          right: 0,
        ),
        if (brands != null && brands.length > 0)
          Positioned(
            child: Container(
              color: Colors.white,
              child: StoreTitleTab(
                brands,
                globaKeys,
                sc,
                isScroll: true,
              ),
            ),
            top: 0,
            left: 0,
            right: 0,
          ),
      ],
    );
  }

  List<Widget> classChildItem() {
    var widgets = <Widget>[
      ///文章banner
      // HeadlinesBanner(
      //   bannerData,
      // ),

      ActivityTopList(articleTop),

      SizedBox(height: 28),

      Container(
        width: double.infinity,
        margin: EdgeInsets.only(left: 16,bottom:5),
        child:Text(
         S.of(context).wenzhangzhuanlan,
          overflow: TextOverflow.ellipsis,
          maxLines: 2,
          style: TextStyle(
            fontSize: 15.sp,
            fontWeight: MyFontWeight.semi_bold,
            color: Colors.black,
          ),
        )
      ),

      ///头条合集列表
      HeadlinesCollection(headlines, articles),

      ///文章列表
      ArticleList(
        articles,
      ),
    ];

    return widgets;
  }

  @override
  bool get wantKeepAlive => true;
}