import 'dart:convert';

import 'package:dio/dio.dart';
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/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/invitation_list.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/flutter_utils.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:huixiang/view_widget/classic_header.dart';
import 'package:huixiang/view_widget/my_footer.dart';
import 'package:huixiang/view_widget/no_data_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';

class InvitationRecord extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _InvitationRecord();
  }
}

class _InvitationRecord extends State<InvitationRecord>
    with AutomaticKeepAliveClientMixin {
  ApiService apiService;
  RefreshController _refreshController = RefreshController();
  ScrollController scrollController = ScrollController();
  List<InvitationList> invitationList = [];
  UserInfo userInfo;
  int pageNum = 1;

  @override
  void initState() {
    super.initState();
    SharedPreferences.getInstance().then((value) {
      apiService = ApiService(Dio(),
          context: context, token: value.getString("token"), pay: true);
      queryInviteMember();
      queryUserInfo();
    });
  }

  ///邀请记录
  queryInviteMember() async {
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(
        Dio(),
        context: context,
        token: value.getString("token"),
      );
    }
    BaseData<PageInfo<InvitationList>> baseData =
    await apiService.inviteMemberList({
      "searchKey": "",
      "pageNum": 1,
      "pageSize": 100,
    }).catchError((error) {
      _refreshController.refreshFailed();
    });
    if (baseData != null && baseData.isSuccess) {
      if (pageNum == 1) {
        invitationList.clear();
      }
      invitationList.addAll(baseData.data.list);
      setState(() {
        _refreshController.refreshCompleted();
      });
    } else {
      _refreshController.refreshFailed();
    }
  }

  queryUserInfo() async {
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(
        Dio(),
        context: context,
        token: value.getString("token"),
      );
    }
    BaseData<UserInfo> baseDate =
    await apiService.queryInfo().catchError((onError) {
      _refreshController.refreshFailed();
    });
    if (baseDate != null && baseDate.isSuccess) {
      setState(() {
        userInfo = baseDate.data;
      });
      SharedPreferences.getInstance().then(
            (value) => {
          value.setString('user', jsonEncode(baseDate.data)),
        },
      );
      _refreshController.refreshCompleted();
    } else {
      _refreshController.refreshFailed();
    }
    EasyLoading.dismiss();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Stack(
      children: [
        Container(
          color: Color(0xFFF7F7F7),
        ),
        Stack(
          children: [
            Container(
              // padding: EdgeInsets.only(top: 40.h),
              height: 230.h,
              decoration: BoxDecoration(
                gradient: new LinearGradient(
                    begin: Alignment.centerRight,
                    end: Alignment.centerLeft,
                    colors: [
                      Color(0xFFE8F5E9),
                      Color(0xFFE5F7FF),
                    ]),
              ),
            ),
            Container(
                padding: EdgeInsets.only(
                    top: MediaQuery.of(context).padding.top,
                    left: 16.w,
                    right: 16.w),
                child: Column(
                  children: [
                    GestureDetector(
                        onTap: (){
                          Navigator.of(context).pop();
                        },
                        child:Padding(
                            padding: EdgeInsets.only(top: 15.h, bottom: 30.h),
                            child: Row(
                              children: [
                                Icon(
                                  Icons.arrow_back_ios,
                                  size: 24,
                                ),
                                SizedBox(
                                  width: 1.w,
                                ),
                                Text(
                                  "我的邀请记录",
                                  style: TextStyle(
                                    fontSize: 18.sp,
                                    color: Color(0xFF000000),
                                    fontWeight: MyFontWeight.semi_bold,
                                  ),
                                ),
                              ],
                            ))
                    ),
                    Container(
                      margin: EdgeInsets.only(bottom: 16.h),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(8),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withAlpha(12),
                            offset: Offset(0, 3),
                            blurRadius: 14,
                            spreadRadius: 0,
                          ),
                        ],
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Expanded(
                              child: Container(
                                  color: Colors.transparent,
                                  padding: EdgeInsets.all(16),
                                  child: Column(
                                    children: [
                                      Text(
                                        (userInfo?.todayInviteNumber ?? 0).toString(),
                                        style: TextStyle(
                                          color: Color(0xFF000000),
                                          fontSize: 30.sp,
                                          fontWeight: MyFontWeight.medium,
                                        ),
                                      ),
                                      SizedBox(
                                        height: 4,
                                      ),
                                      Text(
                                        "今日邀请",
                                        style: TextStyle(
                                          color: Color(0xFF808080),
                                          fontSize: 12.sp,
                                          fontWeight: MyFontWeight.regular,
                                        ),
                                      ),
                                    ],
                                  ))),
                          Container(
                            width: 1.w,
                            height: 32.h,
                            margin: EdgeInsets.only(left: 20.w, right: 20.w),
                            color: Color(0xFFD2D2D2),
                          ),
                          Expanded(
                              child: Container(
                                  color: Colors.transparent,
                                  padding: EdgeInsets.all(16),
                                  child: Column(
                                    children: [
                                      Text(
                                        (userInfo?.inviteNumber ?? 0).toString(),
                                        style: TextStyle(
                                          color: Color(0xFF000000),
                                          fontSize: 30.sp,
                                          fontWeight: MyFontWeight.medium,
                                        ),
                                      ),
                                      SizedBox(
                                        height: 4,
                                      ),
                                      Text(
                                        "累计邀请",
                                        style: TextStyle(
                                          color: Color(0xFF808080),
                                          fontSize: 12.sp,
                                          fontWeight: MyFontWeight.regular,
                                        ),
                                      ),
                                    ],
                                  ))),
                        ],
                      ),
                    ),
                    Expanded(
                        child: Container(
                            width: double.infinity,
                            padding: EdgeInsets.only(
                                top: 20.h, left: 16.w, right: 16.w),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(8),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withAlpha(12),
                                  offset: Offset(0, 3),
                                  blurRadius: 14,
                                  spreadRadius: 0,
                                ),
                              ],
                            ),
                            child: Column(
                              children: [
                                Text(
                                  "邀请记录",
                                  style: TextStyle(
                                    color: Color(0xFF353535),
                                    fontSize: 16.sp,
                                    fontWeight: MyFontWeight.semi_bold,
                                  ),
                                ),
                                SizedBox(
                                  height: 8.h,
                                ),
                                Container(
                                  width: 34.w,
                                  height: 2.h,
                                  margin: EdgeInsets.only(bottom: 20.h),
                                  color: Color(0xFF32A060),
                                ),
                                Row(
                                  children: [
                                    Expanded(
                                      child: Text(
                                        S.of(context).shoujihao,
                                        style: TextStyle(
                                          color: Color(0xFF353535),
                                          fontSize: 12.sp,
                                          fontWeight: MyFontWeight.regular,
                                        ),
                                      ),
                                    ),
                                    Text(
                                      "注册时间",
                                      style: TextStyle(
                                        color: Color(0xFF353535),
                                        fontSize: 12.sp,
                                        fontWeight: MyFontWeight.regular,
                                      ),
                                    ),
                                  ],
                                ),
                                Expanded(child:
                                (invitationList.length == null || invitationList.length == 0)
                                    ? NoDataView(
                                  src: "assets/image/icon_empty.webp",
                                  isShowBtn: false,
                                  text:"还没有邀请记录哦~",
                                  fontSize: 16.sp,
                                  margin: EdgeInsets.only(top: 120.h),
                                ):
                                ListView.builder(
                                  itemCount:invitationList.length,
                                  shrinkWrap: true,
                                  physics: BouncingScrollPhysics(),
                                  scrollDirection: Axis.vertical,
                                  padding: EdgeInsets.symmetric(vertical: 8.h),
                                  itemBuilder: (context, position) {
                                    return Container(
                                      child: invitationItem(invitationList[position]),
                                    );
                                  },
                                ),)
                              ],
                            ))),
                  ],
                )),
          ],
        ),
      ],
    );
  }

  Widget invitationItem(InvitationList invitationList) {
    return Container(
        child: Column(children: [
          Padding(padding: EdgeInsets.symmetric(vertical: 12.h),
          child:
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(child:Text(
                AppUtils.phoneEncode(invitationList?.phone ?? ""),
                style: TextStyle(
                  color: Color(0xFF000000),
                  fontSize: 14.sp,
                  fontWeight: MyFontWeight.medium,
                ),
              ),),
              Text(
                invitationList?.createTime ?? "",
                style: TextStyle(
                  color: Color(0xFF000000),
                  fontSize: 14.sp,
                  fontWeight: MyFontWeight.medium,
                ),
              )
            ],
          ),),
          Container(
            width:double.infinity,
            height:1.h,
            color: Color(0xFFF7F7F7),
          ),
        ]));
  }

  @override
  bool get wantKeepAlive => true;
}