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/utils/font_weight.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';

import '../view_widget/no_data_view.dart';

class IntegralDetailedPage extends StatefulWidget {
  final arguments;
  IntegralDetailedPage({this.arguments});

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

class _IntegralDetailedPage extends State<IntegralDetailedPage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  List<Widget> _tabs;
  TabController tabController;
  ApiService apiService;
  UserInfo userInfo;
  int current = 1;
  List<UserBill> userBill = [];
  RefreshController refreshController = RefreshController();

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _tabs = [
      MyTab(
        text: widget.arguments["titleType"] == 1 ? "印章获得" : S.of(context).huode,
      ),
      MyTab(
        text: widget.arguments["titleType"] == 1 ? "印章使用" : S.of(context).xiaofei,
      ),
    ];
    tabController = TabController(length: 2, vsync: this)
      ..addListener(() {
        current = 1;
        if (tabController.index == 0) {
          queryDetail(widget.arguments["titleType"] == 1 ? "" : "bill_cate_point_get",widget.arguments["titleType"] == 1 ?"BILL_TYPE_BEAN_ADD" :"");
        } else {
          queryDetail(widget.arguments["titleType"] == 1 ? "" : "bill_cate_point_sub",widget.arguments["titleType"] == 1 ?"BILL_TYPE_BEAN_SUB" :"");
        }
      });
  }


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

  @override
  void initState() {
    super.initState();
    SharedPreferences.getInstance().then((value) => {
          apiService = ApiService(Dio(),
              context: context, token: value.getString("token")),
          userInfo = UserInfo.fromJson(jsonDecode(value.getString('user'))),
          queryDetail(widget.arguments["titleType"] == 1 ? "" : "bill_cate_point_get",widget.arguments["titleType"] == 1 ?"BILL_TYPE_BEAN_ADD" :""),
        });
  }

  queryDetail(category,type) async {
    BaseData<PageInfo<UserBill>> baseData = await apiService.queryBillInfo({
      "current": current,
      "model": {"category": category, "title": widget.arguments["titleType"] == 1 ? "":"bill_title_point", "type": 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();
    }
  }


  _onRefresh() {
    current = 1;
    if (tabController.index == 0) {
      queryDetail(widget.arguments["titleType"] == 1 ? "" : "bill_cate_point_get",widget.arguments["titleType"] == 1 ?"BILL_TYPE_BEAN_ADD" :"");
    } else {
      queryDetail(widget.arguments["titleType"] == 1 ? "" : "bill_cate_point_sub",widget.arguments["titleType"] == 1 ?"BILL_TYPE_BEAN_SUB" :"");
    }
  }

  _loadMore() {
    if (tabController.index == 0) {
      queryDetail(widget.arguments["titleType"] == 1 ? "" : "bill_cate_point_get",widget.arguments["titleType"] == 1 ?"BILL_TYPE_BEAN_SUB" :"");
    } else {
      queryDetail(widget.arguments["titleType"] == 1 ? "" : "bill_cate_point_sub",widget.arguments["titleType"] == 1 ?"BILL_TYPE_BEAN_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(fontWeight: FontWeight.w500, 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: Stack(
                  children: [
                    Image.asset(
                      "assets/image/ming_xi.webp",
                      width:double.infinity,
                      fit: BoxFit.fill,
                      height:259.h,
                    ),
                    Container(
                      alignment: Alignment.center,
                      margin: EdgeInsets.only(top: 56.h),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text(
                            userInfo != null ? (widget.arguments["titleType"] == 1 ? (userInfo?.happyBean ?? 0) : userInfo.points) : "0",
                            style: TextStyle(
                                color: Colors.white,
                                fontWeight: MyFontWeight.medium,
                                fontSize: 48.sp),
                          ),
                          Text(
                            widget.arguments["titleType"] == 1 ? "我的印章" : S.of(context).wodejifenzhi,
                            style: TextStyle(
                                color: Color(0xFFF2F2F2),
                                fontSize: 12.sp,
                                fontWeight: MyFontWeight.regular),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
              expandedHeight: 228,
              bottom: PreferredSize(
                  preferredSize: Size(double.infinity, 38),
                  child: Theme(
                    data: ThemeData(
                      splashColor: Colors.transparent, // 点击时的水波纹颜色设置为透明
                      highlightColor: Colors.transparent, // 点击时的背景高亮颜色设置为透明
                    ),
                    child: TabBar(
                      tabs: _tabs,
                      controller: tabController,
                      isScrollable: false,
                      indicatorSize: TabBarIndicatorSize.label,
                      labelColor: Colors.white,
                      labelStyle: TextStyle(
                          fontSize: 16.sp, fontWeight: MyFontWeight.medium),
                      unselectedLabelStyle: TextStyle(
                          fontSize: 16.sp, fontWeight: MyFontWeight.medium),
                      indicatorColor: Colors.white,
                      unselectedLabelColor: Color(0xFFE6E6E6),
                    ),
                  )),
            ),
          ];
        },
        body: Container(
          color: Colors.white,
          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: (userBill == null || userBill.length == 0)
                ? NoDataView(
              src: "assets/image/xiao_fei.webp",
              isShowBtn: false,
              text: "当前暂无记录哦~",
              fontSize: 16.sp,
              margin: EdgeInsets.all(60.h),
            ):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.all(12),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(6)),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withAlpha(25),
                            offset: Offset(0, 2),
                            blurRadius: 3,
                            spreadRadius: 0,
                          )
                        ]),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Expanded(
                            child: Container(
                              // height: 34.h,
                              alignment: Alignment.centerLeft,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.spaceAround,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Padding(padding: EdgeInsets.only(bottom: 8.h),
                                    child: Text(
                                      userBill[position].type ?? "",
                                      // S.of(context).qiandao,
                                      style: TextStyle(
                                          color: Colors.black,
                                          fontSize: 14.sp,
                                          fontWeight: FontWeight.bold),
                                    ),),
                                  Text(
                                    userBill[position].createTime ?? "",
                                    style: TextStyle(
                                        color: Color(0xFF4D4D4D),
                                        fontSize: 12.sp,
                                        fontWeight: MyFontWeight.regular),
                                  )
                                ],
                              ),
                            )),
                        Container(
                          margin: EdgeInsets.only(top: 2.h),
                          child: Text(
                            "${tabController.index == 0 ? "+" : "-"}${double.tryParse(userBill[position].number ?? "0").toInt().toString()}",
                            style: TextStyle(
                                color: Color(0xFF4D4D4D),
                                fontSize: 14.sp,
                                fontFamily: 'JDZhengHT',
                                fontWeight: MyFontWeight.regular),
                          ),
                        )
                      ],
                    )
                    // Row(
                    //   mainAxisAlignment: MainAxisAlignment.start,
                    //   crossAxisAlignment: CrossAxisAlignment.center,
                    //   children: [
                    //     Image.asset(
                    //       "assets/image/icon_intergral_sign.webp",
                    //       width: 36.w,
                    //       height: 34.h,
                    //     ),
                    //     SizedBox(
                    //       width: 15,
                    //     ),
                    //     Expanded(
                    //         child: Container(
                    //       // height: 34.h,
                    //       alignment: Alignment.centerLeft,
                    //       child: Column(
                    //         mainAxisAlignment: MainAxisAlignment.spaceAround,
                    //         crossAxisAlignment: CrossAxisAlignment.start,
                    //         children: [
                    //           Text(
                    //             userBill[position].type ?? "",
                    //             // S.of(context).qiandao,
                    //             style: TextStyle(
                    //                 color: Colors.black,
                    //                 fontSize: 12.sp,
                    //                 fontWeight: FontWeight.w400),
                    //           ),
                    //           Text(
                    //             userBill[position].createTime ?? "",
                    //             style: TextStyle(
                    //                 color: Color(0xFF727272),
                    //                 fontSize: 10.sp,
                    //                 fontWeight: MyFontWeight.regular),
                    //           )
                    //         ],
                    //       ),
                    //     )),
                    //     Container(
                    //       margin: EdgeInsets.only(top: 2.h),
                    //       child: Text(
                    //         "${tabController.index == 0 ? "+" : "-"}${double.tryParse(userBill[position].number ?? "0").toInt().toString()}",
                    //         style: TextStyle(
                    //             color: Color(0xFF727272),
                    //             fontSize: 12.sp,
                    //             fontWeight: MyFontWeight.regular),
                    //       ),
                    //     )
                    //   ],
                    // ),
                  );
                }),
          ),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}