import 'dart:convert';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/home/points_mall_view/point_mall_user.dart';
import 'package:huixiang/home/points_mall_view/points_goods_title.dart';
import 'package:huixiang/home/points_mall_view/points_goods_view.dart';
import 'package:huixiang/home/points_mall_view/points_mall_banner.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/goods.dart';
import 'package:huixiang/retrofit/data/goods_category.dart';
import 'package:huixiang/retrofit/data/page.dart';
import 'package:huixiang/retrofit/data/user_info.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:huixiang/view_widget/my_footer.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';

class PointsMallPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _PointsMallPage();
  }
}

class _PointsMallPage extends State<PointsMallPage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  ApiService client;
  final RefreshController _refreshController = RefreshController();

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

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

    eventBus.on<EventType>().listen((event) {
      if (event.type < 3) {
        setState(() {});
      }
      if (event.type == 3) {
        creditGoods();
      }
    });
  }

  int pageNum = 1;

  //排序类型枚举:1-自然排序,2-销量,3-价格
  int orderType = 1;

  //是否降序排列
  bool orderDesc = true;
  List<Goods> goods = [];
  List<GoodsCategory> gooodsCategorys = [];
  UserInfo userInfo;
  List<BannerData> bannerData = [];

  queryUser() async {
    BaseData<PageInfo<BannerData>> banner = await client.queryBanner({
      "model": {"type": "CREDIT_INDEX"},
    }).catchError((onError) {});

    if (banner != null &&
        banner.isSuccess &&
        banner.data != null &&
        banner.data.records != null &&
        banner.data.records.length > 0) {
      bannerData.clear();
      bannerData.addAll(banner.data.records);
    }

    BaseData<UserInfo> baseData = await client.queryInfo().catchError((onError){

    });
    if (baseData != null && baseData.isSuccess) {
      userInfo = baseData.data;
      SharedPreferences.getInstance().then((value) => {
            value.setString('user', jsonEncode(baseData.data)),
          });
    }
  }

  creditGoods() async {
    EasyLoading.show(status: S.current.zhengzaijiazai);

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

    await queryUser();

    BaseData<PageInfo<GoodsCategory>> dataCategory =
        await client.goodsCategory({
      "current": 1,
      "map": {},
      "model": {"pageNum": 1, "pageSize": 20, "searchKey": ""},
      "order": "descending",
      "size": 20,
      "sort": "sortOrder"
    }).catchError((onError) {
      _refreshController.loadFailed();
      _refreshController.refreshFailed();
    });

    if (dataCategory != null &&
        dataCategory.isSuccess &&
        dataCategory.data != null &&
        dataCategory.data.records != null &&
        dataCategory.data.records.length > 0) {
      gooodsCategorys.clear();
      gooodsCategorys.add(GoodsCategory(name: S.of(context).quanbu));
      gooodsCategorys.addAll(dataCategory.data.records);
    }

    var param = {
      "categoryId": categoryId ?? "",
      "orderDesc": orderDesc,
      "orderType": orderType,
      "pageNum": pageNum,
      "pageSize": 10,
      "state": 1
    };
    BaseData<PageInfo<Goods>> baseData = await client.creditGoods(param)
        .catchError((onError) {
      _refreshController.loadFailed();
      _refreshController.refreshFailed();
    });
    EasyLoading.dismiss();
    if (baseData != null && baseData.isSuccess) {
      if (pageNum == 1) {
        goods.clear();
      }
      goods.addAll(baseData.data.list);
      _refreshController.refreshCompleted();
      _refreshController.loadComplete();
      if (baseData.data.pageNum == baseData.data.pages) {
        _refreshController.loadNoData();
      } else {
        pageNum += 1;
      }
    } else {
      _refreshController.loadFailed();
      _refreshController.refreshFailed();
    }
  }

  String categoryId;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: true,
      header: MyHeader(),
      physics: BouncingScrollPhysics(),
      footer: CustomFooter(
        loadStyle: LoadStyle.ShowWhenLoading,
        builder: (BuildContext context, LoadStatus mode) {
          return MyFooter(mode);
        },
      ),
      controller: _refreshController,
      onRefresh: () {
        pageNum = 1;
        setState(() {});
      },
      onLoading: () {
        setState(() {});
      },
      child: SingleChildScrollView(
        child: Container(
          color: Color(0xFFFAFAFA),
          child: FutureBuilder(
            future: creditGoods(),
            builder: (context, snapshot) {
              return Column(
                children: [
                  ///积分商城的banner
                  PointMallBanner(bannerData),

                  ///积分商城的用户信息
                  PointMallUser(userInfo),

                  ///积分商品头Tab
                  PointsGoodsTitle(
                    gooodsCategorys,
                    (orderType, orderDesc) {
                      this.orderType = orderType;
                      this.orderDesc = orderDesc;
                      setState(() {});
                    },
                    (index) {
                      categoryId = gooodsCategorys[index].id;
                      pageNum = 1;
                      setState(() {});
                    },
                  ),

                  ///积分商品列表
                  PointGoods(
                    goods,
                    (index) {
                      _toDetails(index);
                    },
                  ),
                ],
              );
            },
          ),
        ),
      ),
    );
  }

  _toDetails(index) async {
    await Navigator.of(context).pushNamed('/router/integral_store_page',
        arguments: {"goodsId": goods[index].id});
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String token = sharedPreferences.getString("token");
    if (token != null && token != "") queryUser();
  }

  @override
  bool get wantKeepAlive => true;

}