import 'dart:convert';
import 'dart:io';

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_appbar.dart';
import 'package:huixiang/view_widget/my_footer.dart';
import 'package:huixiang/view_widget/no_data_view.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'package:number_precision/number_precision.dart';

import '../utils/flutter_utils.dart';

class MineWalletPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MineWalletPage();
  }
}

class _MineWalletPage extends State<MineWalletPage> {
  dynamic pBalance = 0; //平台总余额
  dynamic mBalance = 0; // 余额
  dynamic mgreenMoney = 0;//绿币余额
  dynamic activityMoney = 0;//活动余额
  dynamic mRaiseMoney = 0;//众筹金余额
  bool integralTips = false;

  @override
  void initState() {
    super.initState();

    loadBalance();
  }

  UserInfo userInfo;
  ApiService apiService;
  int current = 1;
  List<UserBill> userBills = [];

  loadBalance() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    userInfo =
        UserInfo.fromJson(jsonDecode(sharedPreferences.getString('user')));
    mgreenMoney = double.tryParse(userInfo.greenMoney);
    mRaiseMoney = double.tryParse(userInfo.raiseMoney);
    mBalance = double.tryParse(userInfo.money);
    pBalance = mBalance + mgreenMoney;
    activityMoney = double.tryParse(userInfo.activityMoney);
    if (mounted) setState(() {});
    String token = sharedPreferences.getString("token");
    apiService = ApiService(Dio(), context: context, token: token);
    loadBillInfo();
  }

  _onRefresh() {
    current = 1;
    loadBillInfo();
  }

  queryUserBalance() async {
    BaseData<UserInfo> baseData =
        await apiService.queryInfo().catchError((onError) {});
    if (baseData != null && baseData.isSuccess) {
      userInfo = baseData.data;
      mgreenMoney = double.tryParse(userInfo.greenMoney);
      mRaiseMoney = double.tryParse(userInfo.raiseMoney);
      activityMoney = double.tryParse(userInfo.activityMoney);
      mBalance = double.tryParse(userInfo.money);
      pBalance = mBalance + mgreenMoney;
      if (mounted) setState(() {});
    }
  }

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

  RefreshController refreshController = RefreshController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        title: S.of(context).huixiangqianbao,
        titleColor: Colors.black,
        background: Color(0xFFF7F7F7),
        leadingColor: Colors.black,
      ),
      body: SmartRefresher(
        controller: refreshController,
        enablePullDown: true,
        enablePullUp: true,
        physics: BouncingScrollPhysics(),
        header: MyHeader(),
        footer: CustomFooter(
          builder: (context, mode) {
            return MyFooter(mode);
          },
        ),
        onRefresh: _onRefresh,
        onLoading: loadBillInfo,
        child: SingleChildScrollView(
          child: Container(
            color: Color(0xFFF7F7F7),
            child: Column(
              children: [
                balance(),
                // rechargeWithdrawal(),
                balanceHistory(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget balance() {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.fromLTRB(14.w, 16.h, 14.w, 8.h),
      padding: EdgeInsets.only(bottom: 12.h),
      decoration: BoxDecoration(
        color: Color(0xFF32A060),
        borderRadius: BorderRadius.circular(10),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withAlpha(25),
            offset: Offset(0, 3),
            blurRadius: 14,
            spreadRadius: 0,
          ),
        ],
      ),
      child: Stack(
        children: [
          Container(
            padding: EdgeInsets.symmetric(horizontal: 26.w),
            width: double.infinity,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
            ),
            child: IntrinsicHeight(
              child: Column(
                children: [
                  Padding(
                    padding: EdgeInsets.only(top: 18.h, bottom: 6.h),
                    child: Text(
                      S.of(context).zongzichanyuan,
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: MyFontWeight.semi_bold,
                        fontSize: 16.sp,
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(bottom: 14.h),
                    child: Text(
                      "${NP.plus(mBalance, mgreenMoney)}",
                      style: TextStyle(
                        fontWeight: MyFontWeight.medium,
                        fontSize: 24.sp,
                        fontFamily: 'JDZhengHT',
                        color: Colors.white,
                      ),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      toRecharge();
                    },
                    child: Container(
                      width: 106.w,
                      height: 32.h,
                      alignment: Alignment.center,
                      margin: EdgeInsets.only(bottom: 16.h),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(100),
                      ),
                      child: Text(
                        "去充值",
                        style: TextStyle(
                          fontWeight: MyFontWeight.semi_bold,
                          fontSize: 14.sp,
                          fontFamily: 'JDZhengHT',
                          color: Color(0xFF35BB6D),
                        ),
                      ),
                    ),
                  ),

                  ///余额
                  Row(
                    children: [
                      Expanded(
                          child: Text(
                        "${S.of(context).yue}(含活动)",
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: MyFontWeight.semi_bold,
                          color: Colors.white,
                        ),
                      )),
                      Text(
                        "${NP.strip(mBalance)}",
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontFamily: 'JDZhengHT',
                          fontWeight: MyFontWeight.medium,
                          color: Colors.white,
                        ),
                      )
                    ],
                  ),
                  Container(
                    margin: EdgeInsets.symmetric(vertical: 8.h),
                    width: double.infinity,
                    height: 1.h,
                    color: Color(0x33FFFCFC),
                  ),

                  ///充值活动赠送余额/活动余额
                  Row(
                    children: [
                      Expanded(
                          child: Text(
                        "赠送余额",
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: MyFontWeight.semi_bold,
                          color: Colors.white,
                        ),
                      )),
                      Text(
                        "${NP.strip(activityMoney)}",
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontFamily: 'JDZhengHT',
                          fontWeight: MyFontWeight.medium,
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                  Container(
                    margin: EdgeInsets.symmetric(vertical: 8.h),
                    width: double.infinity,
                    height: 1.h,
                    color: Color(0x33FFFCFC),
                  ),

                  ///绿币余额
                  if (mgreenMoney != 0)
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            "绿币余额",
                            style: TextStyle(
                              fontSize: 14.sp,
                              fontWeight: MyFontWeight.semi_bold,
                              color: Colors.white,
                            ),
                          ),
                        ),
                        Text(
                          "${NP.strip(mgreenMoney)}",
                          style: TextStyle(
                            fontSize: 14.sp,
                            fontFamily: 'JDZhengHT',
                            fontWeight: MyFontWeight.medium,
                            color: Colors.white,
                          ),
                        )
                      ],
                    ),
                  if (mgreenMoney != 0)
                    Container(
                      margin: EdgeInsets.symmetric(vertical: 8.h),
                      width: double.infinity,
                      height: 1.h,
                      color: Color(0x33FFFCFC),
                    ),
                  ///助农积分
                  if (mRaiseMoney != 0)
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        integralTips = !integralTips;
                      });
                    },
                    child: Row(
                      children: [
                        Text(
                          "助农积分",
                          style: TextStyle(
                            fontSize: 14.sp,
                            fontWeight: MyFontWeight.semi_bold,
                            color: Colors.white,
                          ),
                        ),
                        SizedBox(
                          width: 4.w,
                        ),
                        Image.asset(
                          "assets/image/tips_white.webp",
                          fit: BoxFit.cover,
                          width: 16.w,
                          height: 16.h,
                        ),
                        Expanded(
                            child: Text(
                          integralTips ? " 有效期至${userInfo.raiseExpireTime.split(" ")[0]}" : "",
                          style: TextStyle(
                            fontSize: 10.sp,
                            fontFamily: 'JDZhengHT',
                            fontWeight: MyFontWeight.light,
                            color: Colors.white,
                          ),
                        )),
                        Text(
                          "${NP.strip(mRaiseMoney)}",
                          style: TextStyle(
                            fontSize: 14.sp,
                            fontFamily: 'JDZhengHT',
                            fontWeight: MyFontWeight.medium,
                            color: Colors.white,
                          ),
                        )
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          Align(
            alignment: Alignment.topRight,
            child: Image.asset(
              "assets/image/wallet_logo.webp",
              fit: BoxFit.fill,
              width: 116.w,
              height: 73.h,
            ),
          ),
        ],
      ),
    );
  }

  Widget balanceHistory() {
    return Container(
      margin: EdgeInsets.fromLTRB(16.w, 16.h, 16.w, 0),
      padding: EdgeInsets.fromLTRB(24.w, 24.h, 24.w, 24.h),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(8)),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withAlpha(25),
            offset: Offset(0, 3),
            blurRadius: 14,
            spreadRadius: 0,
          )
        ],
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            S.of(context).xiaofeijilu,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: Colors.black,
              fontSize: 16.sp,
            ),
          ),
          SizedBox(
            height: 16.h,
          ),
          Container(
            child: (userBills == null || userBills.length == 0)
                ? NoDataView(
                    src: "assets/image/xiao_fei.webp",
                    isShowBtn: false,
                    text: S.of(context).muqianwujilu,
                    fontSize: 16.sp,
                    margin: EdgeInsets.only(top: 120.h),
                  )
                : ListView.builder(
                    itemCount: userBills != null ? userBills.length : 0,
                    shrinkWrap: true,
                    padding: EdgeInsets.only(bottom: 20.h),
                    physics: NeverScrollableScrollPhysics(),
                    itemBuilder: (context, position) {
                      return historyItem(userBills[position], position);
                    },
                  ),
          ),
        ],
      ),
    );
  }

  Widget historyItem(UserBill userBill, position) {
    return Container(
      margin: EdgeInsets.only(top: 10.h, bottom: 10.h),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                  flex: 7,
                  child: Text(
                    userBill.type,
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 12.sp,
                    ),
                  )),
              Expanded(
                flex: 4,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: calculateBalance(userBill, 0)
                      .map(
                        (e) => e == S.of(context).yue
                            ? Container(
                                width: e == S.of(context).yue
                                    ? (12.sp * 4)
                                    : double.infinity,
                                alignment: Alignment.centerRight,
                                child: Text(
                                  e,
                                  style: TextStyle(
                                    color: Color(0xFF32A060),
                                    fontFamily: 'JDZhengHT',
                                    fontWeight: MyFontWeight.bold,
                                    fontSize: 12.sp,
                                  ),
                                ),
                              )
                            : Text(
                                e,
                                style: TextStyle(
                                  color: Color(0xFF32A060),
                                  fontWeight: MyFontWeight.bold,
                                  fontFamily: 'JDZhengHT',
                                  fontSize: 12.sp,
                                ),
                              ),
                      )
                      .toList(),
                ),
              ),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                flex: 7,
                child: Text(
                  userBill.createTime,
                  style: TextStyle(
                    color: Color(0xFF727272),
                    fontSize: 10.sp,
                  ),
                ),
              ),
              if (calculateBalance(userBill, 1).isNotEmpty)
                Expanded(
                  flex: 4,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: calculateBalance(userBill, 1)
                        .map(
                          (e) => e == S.of(context).yue
                              ? Container(
                                  width: e == S.of(context).yue
                                      ? (12.sp * 4)
                                      : double.infinity,
                                  alignment: Alignment.centerRight,
                                  child: Text(
                                    e,
                                    style: TextStyle(
                                      color: Color(0xFF20662A),
                                      fontWeight: FontWeight.bold,
                                      fontSize: 12.sp,
                                    ),
                                  ),
                                )
                              : Text(
                                  e,
                                  style: TextStyle(
                                    color: Color(0xFF20662A),
                                    fontWeight: FontWeight.bold,
                                    fontSize: 12.sp,
                                  ),
                                ),
                        )
                        .toList(),
                  ),
                ),
            ],
          ),
          SizedBox(
            height: 4,
          ),
          Row(
            children: [
              Expanded(
                flex: 7,
                child: Text(
                  S.of(context).pingtaizongyue(userBill.balance),
                  style: TextStyle(
                    color: Color(0xFF727272),
                    fontFamily: 'JDZhengHT',
                    fontWeight: MyFontWeight.regular,
                    fontSize: 10.sp,
                  ),
                ),
              ),
              if (calculateBalance(userBill, 2).isNotEmpty)
                Expanded(
                  flex: 4,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: calculateBalance(userBill, 2)
                        .map(
                          (e) => e == S.of(context).yue
                              ? Container(
                                  width: e == S.of(context).yue
                                      ? (12.sp * 4)
                                      : double.infinity,
                                  alignment: Alignment.centerRight,
                                  child: Text(
                                    e,
                                    style: TextStyle(
                                      color: Color(0xFF20662A),
                                      fontWeight: FontWeight.bold,
                                      fontSize: 12.sp,
                                    ),
                                  ),
                                )
                              : Text(
                                  e,
                                  style: TextStyle(
                                    color: Color(0xFF20662A),
                                    fontWeight: FontWeight.bold,
                                    fontSize: 12.sp,
                                  ),
                                ),
                        )
                        .toList(),
                  ),
                ),
            ],
          ),
        ],
      ),
    );
  }

  bool isZero(String money) {
    if (money == null || money.isEmpty) return true;
    double zero = double.tryParse(money);
    return zero == 0;
  }

  List<String> calculateBalance(UserBill userBill, int index) {
    double tbalance = double.tryParse(userBill.number ?? "0");

    /// 总余额
    String surplusGreenMoney = userBill.surplusGreenMoney;
    String surplusActivityMoney = userBill.surplusActivityMoney;
    double surplusMoney = double.tryParse(surplusGreenMoney ?? "0");
    double surplusActivity = double.tryParse(surplusActivityMoney ?? "0");

    // double balance = tbalance - (surplusMoney ?? 0) - (surplusActivity ?? 0);
    String greenMoney = userBill.greenMoney;
    String activityMoney = userBill.activityMoney;

    double money = double.tryParse(greenMoney ?? "0");
    double activity = double.tryParse(activityMoney ?? "0");
    if (index == 0) {
      if (money > 0) {
        return [S.of(context).lvbiyue, "${userBill.pm == 0 ? '-' : '+'}$money"];
      }
      if (activity > 0) {
        return [
          S.of(context).huodongyue,
          "${userBill.pm == 0 ? '-' : '+'}$activity"
        ];
      }
      if (tbalance > 0) {
        return [S.of(context).yue, "${userBill.pm == 0 ? '-' : '+'}$tbalance"];
      }
      return [];
    } else if (index == 1) {
      if (money > 0 && activity > 0) {
        return [
          S.of(context).huodongyue,
          "${userBill.pm == 0 ? '-' : '+'}$activity"
        ];
      }
      if (money > 0 && (tbalance - money) > 0) {
        return [
          S.of(context).yue,
          "${userBill.pm == 0 ? '-' : '+'}${(tbalance - money)}"
        ];
      } else {
        return [];
      }
    } else {
      if (activity > 0 && money > 0) {
        return [
          S.of(context).yue,
          "${userBill.pm == 0 ? '-' : '+'}${(tbalance - money - activity)}"
        ];
      } else {
        return [];
      }
    }
  }

  //assets/image/recharge,Btn.png

  toRecharge() async {
    await Navigator.of(context).pushNamed('/router/recharge_page');
    loadBillInfo();
  }
}