import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/integral/intergra_view/in_for_points.dart';
import 'package:huixiang/integral/intergra_view/integral_vip.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/rank.dart';
import 'package:huixiang/retrofit/data/sign_info.dart';
import 'package:huixiang/retrofit/data/user_info.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/view_widget/classic_header.dart';
import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:huixiang/view_widget/my_footer.dart';
import 'package:huixiang/view_widget/sign_in_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../utils/flutter_utils.dart';
import 'intergra_view/integral_task.dart';

class IntegralPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _IntegralPage();
  }
}

class _IntegralPage extends State<IntegralPage> {
  ApiService apiService;
  SignInfo signInfo;

  UserInfo userInfo;
  List<Rank> ranks = [];
  int rankLevel = 1;
  final ScrollController scrollController = ScrollController();
  final RefreshController refreshController = RefreshController();

  querySignInfo() async {
    // EasyLoading.show(status: S.of(context).zhengzaijiazai);

    SharedPreferences value = await SharedPreferences.getInstance();
    apiService = ApiService(
      Dio(),
      context: context,
      token: value.getString("token"),
      showLoading: false,
    );
    userInfo = UserInfo.fromJson(jsonDecode(value.getString("user")));

    BaseData<List<Rank>> rankData =
        await apiService.rankList().catchError((onError) {
      SmartDialog.showToast(AppUtils.dioErrorTypeToString(onError.type),
          alignment: Alignment.center);
      refreshController.refreshFailed();
    });
    if (rankData != null && rankData.isSuccess) {
      ranks.clear();
      ranks.addAll(rankData.data);
      refreshController.refreshCompleted();
    } else {
      refreshController.refreshFailed();
    }

    if (userInfo != null &&
        userInfo.memberRankVo != null &&
        ranks != null &&
        ranks.length > 0) {
      rankLevel = (ranks
              .indexWhere((element) => element.id == userInfo.memberRankVo.id) +
          1);
    }

    BaseData<SignInfo> baseData =
        await apiService.signInInfo().catchError((onError) {});
    if (baseData != null && baseData.isSuccess) {
      signInfo = baseData.data;
      refreshController.refreshCompleted();
    }
    EasyLoading.dismiss();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Stack(
        children: [
          // Positioned(
          //   child: Container(
          //     height: 122.h + kToolbarHeight + MediaQuery.of(context).padding.top,
          //     decoration: BoxDecoration(
          //       image: DecorationImage(
          //         fit: BoxFit.fill,
          //         image: AssetImage("assets/image/jifen.webp"),
          //       ),
          //     ),
          //   ),
          //   top: 0,
          //   left: 0,
          //   right: 0,
          // ),
          Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                fit: BoxFit.fill,
                image: AssetImage("assets/image/jifen.webp"),
              ),
            ),
            width: double.infinity,
            height: 215.h,
          ),
          Scaffold(
            backgroundColor: Colors.transparent,
            appBar: MyAppBar(
              exit: () {
                Navigator.of(context).pop(signInfo?.todayHasSignin ?? false);
              },
              background: Colors.transparent,
              leadingColor: Colors.white,
              title: "",
              titleColor: Colors.white,
              titleSize: 16.sp,
              brightness: Brightness.dark,
              action: Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(right: 16.w),
                child: GestureDetector(
                  onTap: () {
                    Navigator.of(context).pushNamed(
                        '/router/integral_detailed_page',
                        arguments: {"titleType": 2});
                  },
                  child: Text(
                    S.of(context).mingxi,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.sp,
                      fontWeight: MyFontWeight.bold,
                    ),
                  ),
                ),
              ),
            ),
            body: SmartRefresher(
              controller: refreshController,
              enablePullDown: true,
              enablePullUp: false,
              header: MyHeader(color: Colors.white,),
              footer: CustomFooter(
                builder: (context, mode) {
                  return MyFooter(mode);
                },
              ),
              onRefresh: () {
                setState(() {
                  querySignInfo();
                });
              },
              physics: BouncingScrollPhysics(),
              scrollController: scrollController,
              child: Container(
                child: SingleChildScrollView(
                  physics: BouncingScrollPhysics(),
                  child: FutureBuilder(
                    future: querySignInfo(),
                    builder: (context, snap) {
                      return Column(
                        children: [
                          /// 上面的积分和VIP等级显示
                          IntegralVip(
                              rankLevel,
                              signInfo,
                              userInfo,
                              "${(signInfo?.signInList?.length) ?? "0"}",
                              ((signInfo?.rewardList != null &&
                                          signInfo.rewardList.length >
                                              (signInfo?.signInList?.length ??
                                                  0))
                                      ? signInfo.rewardList[
                                          signInfo?.signInList?.length ?? 0]
                                      : 0)
                                  .toString()),

                          ///立即签到
                          InForPoints(signInfo, _signIn),

                          ///积分任务
                          IntegralTask(signInfo),
                        ],
                      );
                    },
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  ///立即签到
  _signIn() async {
    if ((signInfo != null && signInfo.todayHasSignin)) {
      SmartDialog.showToast("今日已签到了", alignment: Alignment.center);
      return;
    }
    EasyLoading.show(
        status: S.of(context).zhengzaijiazai,
        maskType: EasyLoadingMaskType.black);
    BaseData baseData = await apiService.signIn().catchError((onError) {});
    if (baseData != null && baseData.isSuccess) {
      setState(() {});
      SmartDialog.show(
          widget: SignInWidget("${signInfo.signInList.length + 1}",
              "${signInfo.rewardList[signInfo.signInList.length]}"));
    } else {
      EasyLoading.dismiss();
    }
  }
}