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:flutter_html/flutter_html.dart';
import 'package:flutter_html/image_render.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/main.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/brand_data.dart';
import 'package:huixiang/retrofit/data/founder.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/view_widget/classic_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.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 'huixiang_view/huixiang_banner.dart';
import 'huixiang_view/origin_info.dart';

class BrandPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _BrandPage();
  }
}

class _BrandPage extends State<BrandPage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  final ScrollController scrollController = ScrollController();
  final RefreshController refreshController = RefreshController();

  ApiService apiService;
  List<Brand> brands = [];
  BrandData brandData;
  List<GlobalKey> globaKeys = [];
  List<BannerData> bannerData = [];
  Founder founder;

  queryHome() async {
    EasyLoading.show(status: S.current.zhengzaijiazai,maskType: EasyLoadingMaskType.black);

    final SharedPreferences value = await SharedPreferences.getInstance();
    apiService = ApiService(
      Dio(),
      context: context,
      token: value.getString('token'),
    );

    BaseData<BrandData> baseData =
        await apiService.queryHome().catchError((error) {
      refreshController.refreshFailed();
    });
    if (baseData != null && baseData.isSuccess) {
      brandData = baseData.data;
    } else {
      refreshController.refreshFailed();
    }

    BaseData<PageInfo<BannerData>> banner = await apiService.queryBanner({
      "model": {"type": "BRAND_APP"},
    }).catchError((error) {
      refreshController.refreshFailed();
    });
    bannerData.clear();
    bannerData.addAll(banner.data.records);

    BaseData brand = await apiService.queryHomeBrand().catchError((error) {
      refreshController.refreshFailed();
    });
    if (brand != null && brand.isSuccess) {
      brands.clear();
      globaKeys.clear();
      brands.addAll((brand.data["brandList"] as List<dynamic>)
          .map((e) => Brand.fromJson(e))
          .toList());
      founder = Founder.fromJson(brand.data["founder"]);
      brands.forEach((element) {
        globaKeys.add(GlobalKey());
      });
    } else {
      refreshController.refreshFailed();
    }
    EasyLoading.dismiss();
    refreshController.refreshCompleted();
    if (mounted) setState(() {});
  }

  @override
  void initState() {
    super.initState();
    eventBus.on<EventType>().listen((event) {
      print("object: BrandPage");
      if (event.type < 3) {
        setState(() {});
      }
    });
    queryHome();
  }

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

  List<Widget> homeChildItem() {
    var widgets = <Widget>[
      ///回乡banner
      HuiXiangBanner(bannerData),

      ///公司信息
      OriginInfo(founder),

      StoreTitleTab(
        brands,
        globaKeys,
        scrollController,
        isScroll: false,
      ),
    ];
    if (brands == null) return widgets;
    brands.forEach((value) {
      widgets.add(
        Container(
          key: globaKeys[brands.indexOf(value)],
          child: Container(
            color: Colors.white,
            child: Html(
              data: value.content,
              customImageRenders: {
                assetUriMatcher(): assetImageRender(),
                networkSourceMatcher(extension: "svg"): svgNetworkImageRender(),
                networkSourceMatcher(): networkImageRender(
                  loadingWidget: () {
                    return Container();
                  },
                ),
              },
            ),
          ),
        ),
      );
    });
    return widgets;
  }

  @override
  bool get wantKeepAlive => true;
}