import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:loopin/IM/controller/im_user_info_controller.dart';
import 'package:loopin/IM/im_friend_listeners.dart';
import 'package:loopin/api/common_api.dart';
import 'package:loopin/pages/my/merchant/balance/model.dart';
import 'package:loopin/service/http.dart';
import 'package:loopin/styles/index.dart';
import 'package:loopin/utils/wechat_business_view.dart';
import 'package:loopin/utils/wxsdk.dart';

class BalanceController extends GetxController {
  /// 钱包余额
  final balance = 0.0.obs;

  final data = <AccountBill>[].obs;

  int currentPage = 1;

  final isLoading = false.obs;

  /// 是否还有更多
  var hasMore = true.obs;

  //
  final RxBool buttonLoading = false.obs;

  @override
  void onInit() {
    super.onInit();
    getAccount();
    getData(reset: true);
  }

  ///获取用户账户信息
  Future<void> getAccount() async {
    final res = await Http.get(CommonApi.userAccount);
    logger.w(res);
    final resData = res['data']['wallet'];
    if (resData != null) {
      balance.value = double.parse(resData);
    } else {
      balance.value = 0.0;
    }
  }

  /// 充值
  Future<void> recharge({required String money}) async {
    // 获取支付参数
    final data = {
      "orderType": "RECHARGE",
      "clientType": "APP",
      "paymentMethod": "WECHAT",
      "paymentClient": "APP",
      "money": money,
    };
    final res = await Http.post(CommonApi.wechatPay, data: data);
    logger.w(res);
    final payParams = res['data'];
    logger.w(payParams);
    // 拉起支付
    await Wxsdk.payWithWx(
      appId: payParams['appid'],
      partnerId: payParams['partnerid'],
      prepayId: payParams['prepayid'],
      packageValue: payParams['package'],
      nonceStr: payParams['noncestr'],
      timestamp: int.parse(payParams['timestamp']),
      sign: payParams['sign'],
    );
    // 在回调结果中获取新的数据
    // getData(reset: true);
  }

  /// 提现
  Future<void> withDraw({required String money}) async {
    final infoCtl = Get.find<ImUserInfoController>();
    final openId = infoCtl.customInfo['openId'];
    if (openId == null || openId.isEmpty) {
      showDialog(
        context: Get.context!,
        builder: (context) {
          return AlertDialog(
            title: Text('微信授权'),
            content: const Text('余额提现至您的微信零钱内，是否前往微信授权？', style: TextStyle(fontSize: 16.0)),
            backgroundColor: Colors.white,
            surfaceTintColor: Colors.white,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.0)),
            elevation: 2.0,
            actionsPadding: const EdgeInsets.all(15.0),
            actions: [
              TextButton(onPressed: () => {Get.back()}, child: Text('取消', style: TextStyle(color: Colors.red))),
              TextButton(
                  onPressed: () async {
                    //去授权
                    await Wxsdk.login();
                    Get.back();
                  },
                  child: Text('确认')),
            ],
          );
        },
      );
      return;
    }

    showDialog(
      context: Get.context!,
      builder: (context) {
        return AlertDialog(
          title: Text('提示！'),
          content: const Text('发起提现申请后，请及时进行确认收款，未进行确认收款金额将于24小后退回', style: TextStyle(fontSize: 16.0)),
          backgroundColor: Colors.white,
          surfaceTintColor: Colors.white,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.0)),
          elevation: 2.0,
          actionsPadding: const EdgeInsets.all(15.0),
          actions: [
            Obx(() {
              return TextButton(
                onPressed: buttonLoading.value
                    ? null
                    : () async {
                        buttonLoading.value = true;
                        try {
                          final res = await Http.post(CommonApi.withdraw, data: {
                            "money": money,
                            "method": "1",
                          });
                          logger.w(res);
                          final pkg = res['data']['packageInfo'];
                          await getData(reset: true);
                          await getAccount();

                          await onWithdrawPressed(packageInfo: pkg);
                          Get.back();
                        } catch (e) {
                          logger.e("提现失败$e");
                        } finally {
                          buttonLoading.value = false;
                        }
                      },
                child: buttonLoading.value
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(FStyle.primaryColor),
                        ),
                      )
                    : const Text('确认'),
              );
            }),
            // TextButton(
            //   onPressed: () async {
            //     //去提现
            //     final res = await Http.post(CommonApi.withdraw, data: {
            //       "money": money,
            //       "method": "1",
            //     });
            //     logger.w(res);
            //     final pkg = res['data']['packageInfo'];
            //     await getData(reset: true);
            //     await getAccount();

            //     await onWithdrawPressed(packageInfo: pkg);
            //     Get.back();
            //   },
            //   child: Text('确认'),
            // ),
          ],
        );
      },
    );
  }

  Future<void> onWithdrawPressed({required String packageInfo}) async {
    String encodedPackage = Uri.encodeComponent(packageInfo);
    String query = 'mchId=1658665710&appId=wxebcdaea31881caab&package=$encodedPackage';
    logger.e(query);
    bool success = await WechatBusinessView.openBusinessView(
      packageInfo: query,
    );

    if (success) {
      logger.w("已唤起微信确认收款码");
    } else {
      logger.e("唤起失败");
    }
  }

  /// 分页数据
  Future<void> getData({bool reset = false}) async {
    if (isLoading.value) {
      logger.w('正在加载中，跳过');
      return;
    }
    isLoading.value = true;
    final res = await Http.post(CommonApi.bills, data: {
      "size": 10,
      "current": currentPage,
    });
    logger.e(res);
    final List resData = res['data']?['records'] ?? [];
    final bills = resData.map((item) => AccountBill.fromJson(item)).toList();

    final total = res['data']['total'] ?? 0;
    if (reset) {
      logger.w('重置数据');
      currentPage = 1;
      data.clear();
      hasMore.value = true;
    }

    data.addAll(bills);

    if (data.length >= total) {
      hasMore.value = false;
      logger.w('没有更多数据了');
    }

    currentPage++;
    logger.w('页码增加到: $currentPage');

    isLoading.value = false;
    logger.w('加载完成');
  }
}
