import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/page.dart';
import 'package:huixiang/retrofit/data/user_bill.dart';
import 'package:huixiang/retrofit/data/user_info.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/view_widget/classic_header.dart';
import 'package:huixiang/view_widget/my_footer.dart';
import 'package:huixiang/view_widget/my_tab.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class IntegralDetailedPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _IntegralDetailedPage();
  }
}

class _IntegralDetailedPage extends State<IntegralDetailedPage>
    with SingleTickerProviderStateMixin {
  List<Widget>? _tabs;
  late TabController tabController;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _tabs = [
      MyTab(
        text: S.of(context).huode,
      ),
      MyTab(
        text: S.of(context).xiaofei,
      ),
    ];
    tabController = TabController(length: 2, vsync: this)
      ..addListener(() {
        current = 1;
        if (tabController.index == 0) {
          queryDetail("bill_cate_point_get");
        } else {
          queryDetail("bill_cate_point_sub");
        }
      });
  }

  late ApiService apiService;
  UserInfo? userInfo;

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

  @override
  void initState() {
    super.initState();
    SharedPreferences.getInstance().then((value) => {
          apiService = ApiService(Dio(), token: value.getString("token")),
          userInfo = UserInfo.fromJson(jsonDecode(value.getString('user')!)),
          queryDetail("bill_cate_point_get"),
        });
  }

  int current = 1;
  List<UserBill?> userBill = [];

  queryDetail(category) async {
    BaseData<PageInfo<UserBill>> baseData = await apiService.queryBillInfo({
      "current": current,
      "model": {"category": category, "title": "bill_title_point", "type": ""},
      "order": "descending",
      "size": 10,
      "sort": "id"
    }).catchError((onError) {
      refreshController.loadFailed();
      refreshController.refreshFailed();
    });
    if (current == 1) userBill.clear();
    if (baseData != null && baseData.isSuccess!) {
      userBill.addAll(baseData.data!.records!);
      refreshController.loadComplete();
      refreshController.refreshCompleted();
      if (current * 10 > int.tryParse(baseData.data!.total!)!) {
        refreshController.loadNoData();
      } else {
        current += 1;
      }
      setState(() {});
    } else {
      refreshController.loadFailed();
      refreshController.refreshFailed();
    }
  }

  RefreshController refreshController = RefreshController();

  _onRefresh() {
    current = 1;
    if (tabController.index == 0) {
      queryDetail("bill_cate_point_get");
    } else {
      queryDetail("bill_cate_point_sub");
    }
  }

  _loadMore() {
    if (tabController.index == 0) {
      queryDetail("bill_cate_point_get");
    } else {
      queryDetail("bill_cate_point_sub");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: NestedScrollView(
        headerSliverBuilder: (context, inner) {
          return [
            SliverAppBar(
              pinned: true,
              backgroundColor: Color(0xFF32A060),
              elevation: 0,
              title: Text(
                S.of(context).mingxi,
                style: TextStyle(color: Colors.white),
              ),
              centerTitle: false,
              leading: GestureDetector(
                onTap: () {
                  Navigator.of(context).pop();
                },
                child: Container(
                  alignment: Alignment.centerRight,
                  margin: EdgeInsets.only(left: 10),
                  padding: EdgeInsets.all(6),
                  child: Icon(
                    Icons.arrow_back_ios,
                    color: Colors.white,
                    size: 24,
                  ),
                ),
              ),
              titleSpacing: 2,
              leadingWidth: 56,
              flexibleSpace: FlexibleSpaceBar(
                background: Container(
                  alignment: Alignment.center,
                  margin: EdgeInsets.only(top: 56),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text(
                        userInfo != null ? userInfo!.points! : "0",
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: 48),
                      ),
                      Text(
                        S.of(context).wodejifenzhi,
                        style:
                            TextStyle(color: Color(0xFFF2F2F2), fontSize: 12),
                      ),
                    ],
                  ),
                ),
              ),
              expandedHeight: 228,
              bottom: PreferredSize(
                preferredSize: Size(double.infinity, 38),
                child: TabBar(
                  tabs: _tabs!,
                  controller: tabController,
                  isScrollable: false,
                  indicatorSize: TabBarIndicatorSize.label,
                  labelColor: Colors.white,
                  labelStyle:
                      TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                  unselectedLabelStyle:
                      TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                  indicatorColor: Colors.white,
                  unselectedLabelColor: Color(0xFFE6E6E6),
                ),
              ),
            ),
          ];
        },
        body: Container(
          child: SmartRefresher(
            controller: refreshController,
            enablePullDown: true,
            enablePullUp: true,
            physics: ClampingScrollPhysics(),
            header: MyHeader(),
            footer: CustomFooter(
              builder: (context, mode) {
                return MyFooter(mode);
              },
            ),
            onRefresh: _onRefresh,
            onLoading: _loadMore,
            child: ListView.builder(
                itemCount: userBill != null ? userBill.length : 0,
                padding: EdgeInsets.only(top: 8, bottom: 8),
                itemBuilder: (context, position) {
                  return Container(
                    margin: EdgeInsets.fromLTRB(16, 8, 16, 8),
                    padding: EdgeInsets.fromLTRB(14, 7, 16, 7),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(2)),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withAlpha(25),
                            offset: Offset(0, 1),
                            blurRadius: 12,
                            spreadRadius: 0,
                          )
                        ]),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Image.asset(
                          "assets/image/icon_intergral_sign.png",
                          width: 36.w,
                          height: 34,
                        ),
                        SizedBox(
                          width: 15,
                        ),
                        Expanded(
                            child: Container(
                          height: 34,
                          alignment: Alignment.centerLeft,
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                userBill![position]!.name ?? "",
                                // S.of(context).qiandao,
                                style: TextStyle(
                                    color: Colors.black, fontSize: 12),
                              ),
                              Text(
                                userBill![position]!.createTime ?? "",
                                style: TextStyle(
                                    color: Color(0xFF727272), fontSize: 10),
                              )
                            ],
                          ),
                        )),
                        Container(
                          margin: EdgeInsets.only(top: 2),
                          child: Text(
                            "${tabController.index == 0 ? "+" : "-"}${double.tryParse(userBill[position]!.number ?? "0")!.toInt().toString()}",
                            style: TextStyle(
                                color: Color(0xFF727272), fontSize: 12),
                          ),
                        )
                      ],
                    ),
                  );
                }),
          ),
        ),
      ),
    );
  }
}