import 'dart:ffi';

import 'package:bot_toast/bot_toast.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:project_telephony/base/base_style.dart';
import 'package:project_telephony/ui/tab_navigator.dart';
import 'package:project_telephony/ui/user/user_page.dart';

import 'package:project_telephony/ui/widget/check_radio.dart';
import 'package:project_telephony/ui/widget/plone_back_button.dart';
import 'package:project_telephony/ui/widget/plone_bottom.dart';
import 'package:project_telephony/ui/widget/putup_widget.dart';
import 'package:project_telephony/utils/headers.dart';
import 'package:project_telephony/utils/user_tool.dart';
import 'package:tobias/tobias.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

import '../../constants/api.dart';
import '../../model/network/api_client.dart';
import '../../model/pay/wx_pay_model.dart';
import '../../utils/pay_util.dart';
import '../../utils/toast/cloud_toast.dart';

class MembersPage extends StatefulWidget {
  const MembersPage({Key? key}) : super(key: key);

  @override
  _MembersPageState createState() => _MembersPageState();
}

List<dynamic>? data;
final List<ChooseItems> _piceList = [
  ChooseItems(
    month: 12,
    pice: 10,
  ),
  ChooseItems(
    month: 1,
    pice: 1,
  ),
];
ChooseItems? _chooseItem = _piceList[0];
int _selectIndex = 0;
List payWay = [
  {
    'payName': '微信支付',
    'payUrl': Assets.icons.weixin.path,
  },
  {'payName': '支付宝支付', 'payUrl': Assets.icons.zhifubao.path}
];

class _MembersPageState extends State<MembersPage> {
  int nowPrice = 1;
  final EasyRefreshController _easyRefreshController = EasyRefreshController();

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: EasyRefresh(
        firstRefresh: true,
        header: MaterialHeader(),
        footer: MaterialFooter(),
        controller: _easyRefreshController,
        onRefresh: () async {
          await UserTool.userProvider.updateUserInfo();

          setState(() {});
        },
        child: Stack(
          children: [
            Align(
              child: SizedBox(
                width: 750.w,
                height: 1624.w,
              ),
            ),
            Positioned(
                child: Image.asset(
              Assets.images.vipbg.path,
            )),
            Positioned(top: 256.w, left: 32.w, child: _getBanner()),
            Positioned(
                top: 480.w,
                child: Container(
                  height: 1208.w,
                  width: 750.w,
                  decoration: const BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(20),
                          topRight: Radius.circular(20))),
                  child: Column(children: [
                    _getRecharge(),
                    _getSpay(payWay),
                    PloneBottom(
                      border: true,
                      onTap: () async {
                        if (_chooseItem == null) {
                          Get.snackbar('提示', "请先选择充值月份");
                        } else {
                          if (_selectIndex == 0) {
                            _wxPayFunc();
                          } else {
                            var result =
                                await isAliPayInstalled(); // 这里判断是否安装支付宝
                            if (!result) {
                              Get.snackbar('提示', "请先安装支付宝");
                            } else {
                              _aliPay();
                              // aliPay("paySign").then((payResult) {
                              //   // map["paySign"]是请求接口返回的字符串直接放进去就好了
                              //   print("支付宝:$payResult");
                              //   if (payResult['resultStatus'] == '9000') {
                              //     Get.snackbar('提示', "充值成功");
                              //   } else {
                              //     Get.snackbar('提示', payResult['memo']);
                              //   }
                              // });
                            }
                          }
                        }
                      },
                      textColor: const Color(0xFF333333),
                      text: UserTool.userProvider.userInfo.isVip != 1
                          ? "立即开通"
                          : "立即续费",
                      color1: const Color(0xFFFFF6D8),
                      color2: const Color(0xFFFFEAB0),
                    )
                  ]),
                )),
            Positioned(
                top: 68.w,
                child: Row(
                  children: [
                    const CloudBackButton(
                      isSpecial: true,
                    ),
                    154.wb,
                    Text('会员中心', style: Theme.of(context).textTheme.headline6),
                  ],
                )),
          ],
        ),
      ),
    );
  }

  //banner
  _getBanner() {
    return SizedBox(
      // margin: EdgeInsets.symmetric(horizontal: 32.w),
      child: Stack(children: [
        Align(
            child: SizedBox(
          width: 686.w,
          child: Image.asset(
            Assets.images.vipbanner.path,
            width: 622.w,
            height: 244.w,
            fit: BoxFit.fill,
          ),
        )),
        Positioned(
            child: Container(
                margin: EdgeInsets.symmetric(horizontal: 64.w, vertical: 50.w),
                child: _getText()))
      ]),
    );
  }

//banner 文字
  _getText() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _getVip(),
        18.hb,
        Text(
          UserTool.userProvider.userInfo.name,
          style: TextStyle(
              color: Colors.white,
              fontSize: BaseStyle.fontSize32,
              fontWeight: FontWeight.bold),
        ),
        16.hb,
        Text(
          UserTool.userProvider.userInfo.isVip != 1
              ? "暂未开通会员"
              : "${DateUtil.formatDateMs(UserTool.userProvider.userInfo.end * 1000, format: DateFormats.y_mo_d)}到期",
          style: TextStyle(color: Colors.white, fontSize: BaseStyle.fontSize24),
        ),
      ],
    );
  }

  _getVip() {
    return Row(
      children: [
        Text(
          "VIP",
          style: TextStyle(
              color: const Color(0xFFFFEAB0),
              fontFamily: "BlackItalic",
              fontSize: 32.sp),
        ),
        Container(
          width: 8.w,
          height: 8.w,
          alignment: Alignment.center,
          margin: EdgeInsets.symmetric(horizontal: 8.w),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(4),
            color: const Color(0xFFFFEAB0),
          ),
        ),
        Text(
          UserTool.userProvider.userInfo.isVip != 1 ? "未开通会员" : "已成为会员",
          style: const TextStyle(
              color: Color(
                0xFFFFEAB0,
              ),
              fontWeight: FontWeight.w700),
        )
      ],
    );
  }

  Future _wxPayFunc() async {
    bool isInstalled = await fluwx.isWeChatInstalled;
    if (!isInstalled) {
      BotToast.showText(text: "请先安装微信");
      return;
    }
    //调起支付
    _wxPay();
    // var wxPayModel = WxPayModel.fromJson({
    //   "prepayId": "wx121434071826969924754d7d3309520000",
    //   "partnerId": "1622850618",
    //   "timeStamp": "1660286047",
    //   "nonceStr": "W14Z6RbKcHcI6QTETFyrxteD3m2P7ZaF",
    //   "package": "Sign=WXPay",
    //   "sign": "i4LDk+FlAfXukLPet6oFdtVkAXHv8aKkajO4i2tiXETBqudWJPzYAaziPH3eBo1yCvkMOyoVddWDKqHXhwrN2uvubz8YpSICt9yZBcndVaXOK+X9hY765sYoFV6sGHz5iuPljTRUWWrmc8GYMEs8TlLDB5Q50NenzJSChdfDtZRV4kXtVK6xY9b0y++eUo/snzpmq/X6GwS9n0auKkT0TKW1C30/Hzpw3SMziXPP02TvBvbqj57f6rHuGJS/LUX2ZwCR8iFZsfuiXo+7lyHHsimr4jVczdS6VtobeekrPq4vTe72d/HU/ECEZRSYxsL5DbyS2TvSNzFA6Z7wGDzkpQ=="
    // });
    // await PayUtil().callWxPay(
    //   payModel: wxPayModel,
    // );
  }

  //    base ={
  //   "content": {
  //     "prepayId": "wx121434071826969924754d7d3309520000",
  //     "partnerId": "1622850618",
  //     "timeStamp": "1660286047",
  //     "nonceStr": "W14Z6RbKcHcI6QTETFyrxteD3m2P7ZaF",
  //     "package": "Sign=WXPay",
  //     "sign": "i4LDk+FlAfXukLPet6oFdtVkAXHv8aKkajO4i2tiXETBqudWJPzYAaziPH3eBo1yCvkMOyoVddWDKqHXhwrN2uvubz8YpSICt9yZBcndVaXOK+X9hY765sYoFV6sGHz5iuPljTRUWWrmc8GYMEs8TlLDB5Q50NenzJSChdfDtZRV4kXtVK6xY9b0y++eUo/snzpmq/X6GwS9n0auKkT0TKW1C30/Hzpw3SMziXPP02TvBvbqj57f6rHuGJS/LUX2ZwCR8iFZsfuiXo+7lyHHsimr4jVczdS6VtobeekrPq4vTe72d/HU/ECEZRSYxsL5DbyS2TvSNzFA6Z7wGDzkpQ=="
  //   }
  // };
  // await apiClient.request(API.user.wallet.assessRecharge, data: {
  //   'count': widget.count,
  //   'payType': 2,
  // });
  //   if (base.code ==null) {
  //
  //   } else {
  //     BotToast.showText(text: "${base.msg}");
  //   }
  // }
  //
  Future _aliPay() async {
    var base = await apiClient.request(API.pay.alipay, data: {
      // 'amount': nowPrice,//注释
      'amount': 0.01,
    });
    if (base.code == 0) {
      await PayUtil().callAliPay(base.data);
      _easyRefreshController.callRefresh();
    } else {
      CloudToast.show(base.msg);
    }
  }

  Future _wxPay() async {
    var base = await apiClient.request(API.pay.wxpay, data: {
      // 'amount': nowPrice,//注释
      'amount': 0.01,
    });
    if (base.code == 0) {
      var wxPayModel = WxPayModel.fromJson(base.data);
      await PayUtil().callWxPay(
        payModel: wxPayModel,
      );
      _easyRefreshController.callRefresh();
    } else {
      CloudToast.show(base.msg);
    }
  }

//充值金额
  _getRecharge() {
    return Container(
      width: double.infinity,
      decoration: const BoxDecoration(),
      clipBehavior: Clip.antiAlias,
      child: ListView(
        shrinkWrap: true,
        children: [
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 80.w, vertical: 32.w),
            child: SortWidget(
              crossAxisSpacing: 24.w,
              itemList: _piceList,
              childAspectRatio: 288 / 216,
              crossAxisCount: 2,
              mainAxisSpacing: 20.w,
              callback: (item, index) {
                _chooseItem = item;
                nowPrice = _piceList[index].pice;
                setState(() {});
              },
              pickItem: _chooseItem,
            ),
          ),
          // 762.hb,
          //40.hb,
        ],
      ),
    );
  }

  _getSpay(List item) {
    return Container(
      // color: Colors.red,
      width: double.infinity,
      height: 500.w,
      margin: EdgeInsets.symmetric(horizontal: 64.w),
      child: ListView.builder(
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {
              _selectIndex = index;
              // print(_selectIndex);
              setState(() {});
            },
            child: Container(
                padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 40.w),
                color: Colors.white,
                child: Row(
                  children: [
                    SizedBox(
                      child: Image.asset(
                        item[index]['payUrl'],
                        width: 40.w,
                        height: 40.h,
                      ),
                    ),
                    20.wb,
                    SizedBox(
                      width: 200.w,
                      child: Text(
                        item[index]['payName'],
                        style: TextStyle(
                            fontWeight: FontWeight.w700,
                            color: BaseStyle.color333333,
                            fontSize: BaseStyle.fontSize28),
                      ),
                    ),
                    const Spacer(),
                    BeeCheckRadio(
                      value: index,
                      groupValue: [_selectIndex],
                    ),
                  ],
                )),
          );
        },
        itemCount: item.length,
      ),
    );

    // ListView.builder(
    //   itemBuilder: (context, index) {
    //     return GestureDetector(
    //       onTap: () {
    //         _selectIndex = index;
    //         // setState(() {});
    //       },
    //       child: Container(
    //           padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 40.w),
    //           color: Colors.white,
    //           child: Row(
    //             children: [
    //               SizedBox(
    //                 child: Image.asset(
    //                   item[index]['payUrl'],
    //                   width: 40.w,
    //                   height: 40.h,
    //                 ),
    //               ),
    //               20.wb,
    //               SizedBox(
    //                 width: 200.w,
    //                 child: Text(
    //                   item[index]['payName'],
    //                   style: TextStyle(
    //                       color: BaseStyle.color333333,
    //                       fontSize: BaseStyle.fontSize28),
    //                 ),
    //               ),
    //               const Spacer(),
    //               BeeCheckRadio(
    //                 value: index,
    //                 groupValue: [_selectIndex],
    //               ),
    //             ],
    //           )),
    //     );
    //   },
    //   itemCount: item.length,
    // );
  }
}
