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/my_appbar.dart';
import 'package:huixiang/view_widget/sign_in_widget.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/flutter_screenutil.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;

  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) {});
    if (rankData != null && rankData.isSuccess) {
      ranks.clear();
      ranks.addAll(rankData.data);
    }

    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;
    }
    EasyLoading.dismiss();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Positioned(
          child: Container(
            height: 122.h + kToolbarHeight + MediaQuery.of(context).padding.top,
            decoration: BoxDecoration(
              gradient: RadialGradient(
                center: Alignment.center,
                colors: [Color(0xFF36426E), Color(0xFF2D3247)],
                focal: Alignment.center,
                radius: 1,
              ),
            ),
          ),
          top: 0,
          left: 0,
          right: 0,
        ),
        Scaffold(
          backgroundColor: Colors.transparent,
          appBar: MyAppBar(
            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');
                },
                child: Text(
                  S.of(context).mingxi,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontWeight: MyFontWeight.bold,
                  ),
                ),
              ),
            ),
          ),
          body: Container(
            child: SingleChildScrollView(
              physics: BouncingScrollPhysics(),
              child: FutureBuilder(
                future: querySignInfo(),
                builder: (context, snap) {
                  return Column(
                    children: [
                      /// 上面的积分和VIP等级显示
                      IntegralVip(rankLevel, signInfo, userInfo),

                      ///立即签到
                      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);
    BaseData baseData = await apiService.signIn();
    if (baseData != null && baseData.isSuccess) {
      setState(() {});
      SmartDialog.show(
          widget: SignInWidget("${signInfo.signInList.length + 1}",
              "${signInfo.rewardList[signInfo.signInList.length]}"));
    } else {
      EasyLoading.dismiss();
    }
  }
}