import 'dart:async';
import 'dart:io';

import 'package:chat/data/UserData.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/home/BindBank.dart';
import 'package:chat/home/money_detail.dart';
import 'package:chat/models/money_change.dart';
import 'package:chat/utils/ChargeMoney.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/TokenMgr.dart';
import 'package:chat/utils/app_navigator.dart';
import 'package:chat/utils/screen.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inapp_purchase/flutter_inapp_purchase.dart';

import 'package:fluwx_no_pay/fluwx_no_pay.dart' as fluwx;
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

import 'VipPage.dart';

class MoneyPage extends StatefulWidget {
  MoneyPage({Key key}) : super(key: key);

  MoneyPageState createState() => MoneyPageState();
}

class MoneyPageState extends State<MoneyPage>
    with SingleTickerProviderStateMixin {
  List list = new List(); //列表要展示的数据
  ScrollController _scrollController = ScrollController(); //listview的控制器

  int _page = 1; //加载的页数
  int rows = 20;
  bool isLoading = false; //是否正在加载数据
  bool isLoadingFish = false;
  bool showMore = false;

  TabController tabCtrl;

  var bindAccount;
  messageGetBindBank(data) {
    getBinkInfo();
  }

  @override
  void initState() {
    super.initState();
    print('MoneyPage initState');
    tabCtrl = TabController(length: 2, vsync: this);
    getBinkInfo();
    MessageMgr().on('bind_bank', messageGetBindBank);

    fluwx.responseFromPayment.listen((data) {
      if (data.errCode == 0) {
        Navigator.of(context).pop();
        setState(() {});
        showToast(I18n.of(context).payment_successful);
      }
    });

    getNewData(initList);
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        setState(() {
          showMore = true;
        });
        _getMore();
      }
    });
  }

  void addList(data) {
    data == null || data.length == 0 ? _page-- : list.addAll(data);
    isLoading = false;
    showMore = false;
    setState(() {});
  }

  Future _getMore() async {
    if (!isLoading) {
      setState(() {
        isLoading = true;
      });
      _page++;
      getNewData(addList);
    }
  }

  void changeMoney() async {
    int minMoney = 350;
    int maxMoney = 4000;
    if (UserData().incomeMoney < minMoney) {
      showToast(I18n.of(context).not_enough);
      return;
    }

    //自己是女性，且未认证,提示去认证
    if (!UserData().isMan() && !UserData().basicInfo.isAttestation) {
      CustomUI.buildNotTrue(context);
      return;
    }
    //如果是男性非会员，提示去开会员
    if (UserData().isMan() && !UserData().isVip) {
      CustomUI.buildOneConfirm(context, I18n.of(context).no_vip_cannot_withdraw,
          I18n.of(context).joinvip, () {
        Navigator.of(context).push(
          new MaterialPageRoute(
            builder: (context) {
              return VipPage();
            },
          ),
        );
      });
      return;
    }

    if (Platform.isIOS) {
      AppNavigator.pushServicePage(context, questionIndex: 1);
      return;
    }
    if (bindAccount == null || bindAccount['CId'] == null) {
      showToast(I18n.of(context).needCard);
      return;
    }

    String money;

    var confirm =
        CustomUI.buildConfirmBotton(I18n.of(context).determine, () async {
      var m;
      if (money == null || money == '' || (m = int.parse(money)) == 0) {
        showToast(I18n.of(context).enter_num_qian1);
        return;
      }

      if (m > Provider.of<MoneyChangeProvider>(context).money) {
        showToast(I18n.of(context).not_enough);
        return;
      }

      if (m < minMoney) {
        showToast(I18n.of(context)
            .little_min
            .replaceFirst('/s1', (minMoney * 1000).toString()));
        return;
      }

      if (m > maxMoney) {
        showToast(I18n.of(context)
            .more_big
            .replaceFirst('/s1', (maxMoney * 1000).toString()));
        return;
      }

      var data = {
        "userId": UserData().basicInfo.userId,
        "cId": bindAccount['CId'],
        "amount": m * 1000,
      };
      data['sign'] = TokenMgr().getSign(data);

      Response res = await HttpUtil().post('wallet/draw/order', data: data);
      Map resData = res.data;
      showToast(resData['msg']);
      if (resData['code'] == 0) {
        Navigator.of(context).pop();
        UserData().incomeMoney -= m;
        MessageMgr().emit('refresh_money');
      }
    });
    var tip = Column(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(top: 20),
          child: Text(
            I18n.of(context).withdrawal_application,
            textScaleFactor: 1.0,
            style: TextStyle(color: Constants.BlackTextColor, fontSize: 16),
          ),
        ),
        Container(
          margin: EdgeInsets.only(top: 23, bottom: 25),
          decoration: BoxDecoration(
              color: Colors.grey[200],
              borderRadius: BorderRadius.all(Radius.circular(8))),
          child: TextField(
            keyboardAppearance: Brightness.light,
            textAlign: TextAlign.center,
            textInputAction: TextInputAction.search,
            style:
                TextStyle(textBaseline: TextBaseline.alphabetic, fontSize: 14),
            decoration: InputDecoration(
              hintText: I18n.of(context).enter_num_qian1,
              filled: true,
              contentPadding: EdgeInsets.only(top: 10, bottom: 10),
              fillColor: Colors.transparent,
              border: InputBorder.none,
            ),
            keyboardType: TextInputType.phone,
            maxLines: 1,
            inputFormatters: [
              WhitelistingTextInputFormatter(RegExp("^([1-9][0-9]*)\$")),
              WhitelistingTextInputFormatter.digitsOnly,
              LengthLimitingTextInputFormatter(5)
            ],
            onChanged: (str) {
              money = str;
            },
          ),
        )
      ],
    );
    var content = CustomUI.buildConfirmContent(tip, confirm);
    CustomUI.buildTip(context, '', content);
  }

  void changeHCoin() async {
    int minMoney = 1;
    int maxMoney = UserData().incomeMoney - UserData().frozenMoney;
    if (UserData().incomeMoney < minMoney) {
      showToast(I18n.of(context).not_enough);
      return;
    }

    String money;

    var confirm =
        CustomUI.buildConfirmBotton(I18n.of(context).determine, () async {
      var m;
      if (money == null || money == '' || (m = int.parse(money)) == 0) {
        showToast(I18n.of(context).enter_num_qian);
        return;
      }

      if (m > maxMoney) {
        showToast(I18n.of(context).not_enough);
        return;
      }

      if (m < minMoney) {
        showToast(I18n.of(context)
            .little_min
            .replaceFirst('/s1', minMoney.toString()));
        return;
      }

      Map data = {
        "userId": UserData().basicInfo.userId,
        "amount": m * 1000,
      };
      data['sign'] = TokenMgr().getSign(data);

      Response res =
          await HttpUtil().post('/wallet/income/exchange', data: data);
      Map resData = res.data;
      showToast(resData['msg']);
      if (resData['code'] == 0) {
        Navigator.of(context).pop();
        UserData().incomeMoney -= m;
        Provider.of<MoneyChangeProvider>(context, listen: false).addMoney(m);
        MessageMgr().emit('refresh_money');
        setState(() {});
      }
    });
    var tip = Column(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(top: 20),
          child: Text(
            I18n.of(context).charge_h,
            textScaleFactor: 1.0,
            style: TextStyle(color: Constants.BlackTextColor, fontSize: 16),
          ),
        ),
        Container(
          margin: EdgeInsets.only(top: 23, bottom: 25),
          decoration: BoxDecoration(
              color: Colors.grey[200],
              borderRadius: BorderRadius.all(Radius.circular(8))),
          child: TextField(
            keyboardAppearance: Brightness.light,
            textAlign: TextAlign.center,
            textInputAction: TextInputAction.search,
            style:
                TextStyle(textBaseline: TextBaseline.alphabetic, fontSize: 14),
            decoration: InputDecoration(
              hintText: I18n.of(context).enter_num_qian,
              filled: true,
              contentPadding: EdgeInsets.only(top: 10, bottom: 10),
              fillColor: Colors.transparent,
              border: InputBorder.none,
            ),
            keyboardType: TextInputType.phone,
            maxLines: 1,
            inputFormatters: [
              WhitelistingTextInputFormatter(RegExp("^([1-9][0-9]*)\$")),
              WhitelistingTextInputFormatter.digitsOnly,
              LengthLimitingTextInputFormatter(5)
            ],
            onChanged: (str) {
              money = str;
            },
          ),
        )
      ],
    );
    var content = CustomUI.buildConfirmContent(tip, confirm);
    CustomUI.buildTip(context, '', content);
  }

  void getBinkInfo() async {
    Map data = {
      "userId": UserData().basicInfo.userId,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil().post('wallet/bind/bankInfo',
        data: data, failback: () => Navigator.of(context).pop());
    Map resData = res.data;
    if (resData['code'] == 0) {
      bindAccount = resData['data'];
      isLoadingFish = true;
      setState(() {});
    }
  }

  @override
  void dispose() {
    tabCtrl.dispose();
    MessageMgr().off('bind_bank', messageGetBindBank);
    if (_conectionSubscription != null) {
      _conectionSubscription.cancel();
      _conectionSubscription = null;
    }
    if (_purchaseUpdatedSubscription != null) {
      _purchaseUpdatedSubscription.cancel();
      _purchaseUpdatedSubscription = null;
    }

    if (_purchaseErrorSubscription != null) {
      _purchaseErrorSubscription.cancel();
      _purchaseErrorSubscription = null;
    }

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Widget content = Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        backgroundColor: AppColors.NewAppbarBgColor,
        leading: CustomUI.buildCustomLeading(context),
        title: Text(
          I18n.of(context).wallet,
          textScaleFactor: 1.0,
        ),
        centerTitle: true,
        bottom: PreferredSize(
            preferredSize: Size.fromHeight(Platform.isIOS ? 0 : 49),
            child: Platform.isIOS ? Container() : _buildBindAccount()),
      ),
      body: SafeArea(child: showCoin()),
    );
    return CustomUI.buildPageLoading(context, content, !isLoadingFish);
  }

  Widget _buildBindAccount() {
    return InkWell(
        onTap: () {
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (context) {
                return BindBankPage(
                  isBind: (bindAccount == null || bindAccount == ''),
                  bankInfo: bindAccount,
                );
              },
            ),
          );
        },
        child: Container(
          color: Colors.white,
          padding: EdgeInsets.only(top: 15, bottom: 15, left: 30, right: 8),
          child: Row(
            children: <Widget>[
              Text(
                I18n.of(context).bind_account.replaceFirst('/s1', ''),
                textScaleFactor: 1.0,
                style: TextStyle(fontWeight: FontWeight.normal),
              ),
              Expanded(
                child: Container(
                    alignment: Alignment.centerRight,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: <Widget>[
                        (bindAccount == null || bindAccount == '')
                            ? Container()
                            : Text(
                                bindAccount['Name'],
                                textScaleFactor: 1.0,
                                style: TextStyle(),
                              ),
                        Icon(
                          IconData(0xe63c, fontFamily: 'iconfont'),
                          size: 22.0,
                          color: Colors.grey,
                        )
                      ],
                    )),
              )
            ],
          ),
        ));
  }

  Widget _buildCard1() {
    var chargeButton = InkWell(
        onTap: () {
          ChargeMoney.showChargeSheet(context, () {
            setState(() {});
          });
        },
        child: Container(
          height: 30,
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(5.5)),
          alignment: Alignment.center,
          width: 120,
          child: Text(
            I18n.of(context).recharge,
            textScaleFactor: 1.0,
            style: TextStyle(color: const Color(0xFFFF717D), fontSize: 14.8),
          ),
        ));

    var joinVipButton = InkWell(
        onTap: () {
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (context) {
                return VipPage();
              },
            ),
          );
        },
        child: Container(
          height: 30,
          decoration: BoxDecoration(
              border: Border.all(color: Colors.white),
              borderRadius: BorderRadius.circular(5.5)),
          alignment: Alignment.center,
          width: 120,
          child: Text(
            I18n.of(context).joinvip,
            textScaleFactor: 1.0,
            style: TextStyle(color: Colors.white, fontSize: 14.8),
          ),
        ));
    return Container(
        margin: EdgeInsets.only(left: 21.5, right: 21.5, top: 20),
        color: Colors.white,
        child: Stack(
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                  boxShadow: [
                    BoxShadow(
                      color: const Color(0x42C4474E),
                      offset: Offset(0, 1.5),
                      blurRadius: 9,
                    )
                  ],
                  borderRadius: BorderRadius.circular(5),
                  gradient: LinearGradient(colors: <Color>[
                    const Color(0xFFFFC689),
                    const Color(0xFFFC818C),
                  ])),
              child: Column(
                children: <Widget>[
                  SizedBox(height: 17),
                  InkWell(
                      onTap: () {
                        Navigator.of(context).push(
                          new MaterialPageRoute(
                            builder: (context) {
                              return MoneyDetailPage(type: 1);
                            },
                          ),
                        );
                      },
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Expanded(child: SizedBox()),
                          Container(
                            child: Text(
                              I18n.of(context).my_money_info,
                              textScaleFactor: 1.0,
                              style:
                                  TextStyle(color: Colors.white, fontSize: 12),
                            ),
                          ),
                          Icon(
                            IconData(0xe63c, fontFamily: 'iconfont'),
                            size: 16.0,
                            color: Colors.white,
                          ),
                          SizedBox(width: 5)
                        ],
                      )),
                  Container(
                    alignment: Alignment.center,
                    child: Text(
                      I18n.of(context).my_left_money,
                      textScaleFactor: 1.0,
                      style: TextStyle(color: Colors.white, fontSize: 15),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(bottom: 30),
                    alignment: Alignment.center,
                    child: Text(
                      '${Provider.of<MoneyChangeProvider>(context).money}' +
                          I18n.of(context).mask_coin,
                      textScaleFactor: 1.0,
                      style: TextStyle(color: Colors.white, fontSize: 31.29),
                    ),
                  ),
                  UserData().isMan()
                      ? Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: <Widget>[
                            chargeButton,
                            joinVipButton,
                          ],
                        )
                      : chargeButton,
                  Container(
                    margin: EdgeInsets.only(top: 25, bottom: 10, left: 13.5),
                    alignment: Alignment.centerLeft,
                    child: Text(
                      I18n.of(context).money_tips,
                      textScaleFactor: 1.0,
                      style: TextStyle(color: Colors.white, fontSize: 11),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ));
  }

  Widget _buildCard2() {
    return Container(
        margin: EdgeInsets.only(left: 21.5, right: 21.5, top: 60),
        color: Colors.white,
        child: Stack(
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                  boxShadow: [
                    BoxShadow(
                      color: const Color(0x42023BBE),
                      offset: Offset(0, 1.5),
                      blurRadius: 8.5,
                    )
                  ],
                  borderRadius: BorderRadius.circular(5),
                  gradient: LinearGradient(colors: <Color>[
                    const Color(0xFF5FA2FF),
                    const Color(0xFFDDA4FF),
                  ])),
              child: Column(
                children: <Widget>[
                  SizedBox(height: 17),
                  InkWell(
                      onTap: () {
                        Navigator.of(context).push(
                          new MaterialPageRoute(
                            builder: (context) {
                              return MoneyDetailPage(type: 2);
                            },
                          ),
                        );
                      },
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Expanded(child: SizedBox()),
                          Container(
                            child: Text(
                              I18n.of(context).get_money_detail,
                              textScaleFactor: 1.0,
                              style:
                                  TextStyle(color: Colors.white, fontSize: 12),
                            ),
                          ),
                          Icon(
                            IconData(0xe63c, fontFamily: 'iconfont'),
                            size: 16.0,
                            color: Colors.white,
                          ),
                          SizedBox(width: 5)
                        ],
                      )),
                  Container(
                    alignment: Alignment.center,
                    child: Text(
                      I18n.of(context).hibok_money,
                      textScaleFactor: 1.0,
                      style: TextStyle(color: Colors.white, fontSize: 15),
                    ),
                  ),
                  Container(
                      margin: EdgeInsets.only(bottom: 30),
                      alignment: Alignment.center,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text(
                            (UserData().incomeMoney + UserData().frozenMoney)
                                    .toString() +
                                'K',
                            textScaleFactor: 1.0,
                            style:
                                TextStyle(color: Colors.white, fontSize: 31.29),
                          ),
                          Text(
                            "(${I18n.of(context).can_withdraw}${UserData().incomeMoney}K)",
                            textScaleFactor: 1.0,
                            style: TextStyle(color: Colors.white, fontSize: 18),
                          ),
                        ],
                      )),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      InkWell(
                          onTap: changeMoney,
                          child: Container(
                            height: 30,
                            decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(5.5)),
                            alignment: Alignment.center,
                            width: 120,
                            child: Text(
                              I18n.of(context).exchange_cash,
                              textScaleFactor: 1.0,
                              style: TextStyle(
                                  color: const Color(0xFF4F8BFF),
                                  fontSize: 14.8),
                            ),
                          )),
                      InkWell(
                          onTap: changeHCoin,
                          child: Container(
                            height: 30,
                            decoration: BoxDecoration(
                                border: Border.all(color: Colors.white),
                                borderRadius: BorderRadius.circular(5.5)),
                            alignment: Alignment.center,
                            width: 120,
                            child: Text(
                              I18n.of(context).charge_h,
                              textScaleFactor: 1.0,
                              style: TextStyle(
                                  color: Colors.white, fontSize: 14.8),
                            ),
                          )),
                    ],
                  ),
                  InkWell(

                    onTap: () {
                      launch(
                          "http://datechatagent.chengyouhd.com/zh-CN/Home/WithdrawalRole?language=${UserData().language}");
                    },
                    child: Container(
                      margin: EdgeInsets.only(top: 25, bottom: 10, left: 13.5),
                      alignment: Alignment.centerLeft,
                      child: Text(
                        I18n.of(context).charge_tips,
                        textScaleFactor: 1.0,
                        style: TextStyle(color: Colors.white, fontSize: 11),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ],
        ));
  }

  Widget showCoin() {
    return Scaffold(
        body: SafeArea(
            child: Center(
      child: Container(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        child: _buildCoinBody(),
      ),
    )));
  }

  void initList(data) {
    list.clear();
    if (data != null) {
      list.addAll(data);
    }
    isLoadingFish = true;
    setState(() {});
  }

  getNewData(callback) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
    };
    data['sign'] = TokenMgr().getSign(data);
    data["page"] = _page;
    data['rows'] = rows;
    data['type'] = 2;
    Response res = await HttpUtil().post('message/wallet/message', data: data);
    var resData = res.data;
    print(resData);
    if (resData['code'] == 0) {
      callback(resData['data']);
    } else {
      showToast(resData['msg']);
    }
  }

  Widget _buildCoinBody() {
    return Container(
      width: Screen.width,
      height: Screen.height,
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: const Color(0x87C6C6C6),
            offset: Offset(0, 0.5),
            blurRadius: 5.5,
          )
        ],
      ),
      margin: EdgeInsets.only(top: 9.5),
      child: Column(
        children: <Widget>[
          _buildCard1(),
          _buildCard2(),
        ],
      ),
    );
  }

  static String currentGoodsId = '';
  static StreamSubscription _conectionSubscription,
      _purchaseUpdatedSubscription,
      _purchaseErrorSubscription;

  ///ios 内购初始化
  static Future initPayConf(BuildContext context) async {
    if (_purchaseErrorSubscription != null) {
      return;
    }

    // prepare
    print('initPayConf   --------   start: ');
    var result = await FlutterInappPurchase.instance.initConnection;
    print('initPayConf   --------   result: $result');
    FlutterInappPurchase.instance.clearTransactionIOS();

    _conectionSubscription =
        FlutterInappPurchase.connectionUpdated.listen((connected) {
      print('connected: $connected');
    });

    _purchaseUpdatedSubscription =
        FlutterInappPurchase.purchaseUpdated.listen((productItem) {
      print('支付成功,成功回调  ------    purchase-updated: $productItem');
//      showToast('支付成功,成功回调  ------    purchase-updated: $productItem');
      if (productItem.transactionReceipt != null &&
          productItem.transactionReceipt.isNotEmpty) {
        HttpUtil().createOrder(currentGoodsId, productItem.transactionReceipt,
            productItem.purchaseToken,
            context: context);

        showToast(I18n.of(context).payment_successful);
      }
      Navigator.of(context).pop();
    });

    _purchaseErrorSubscription =
        FlutterInappPurchase.purchaseError.listen((purchaseError) {
//      showToast('支付失败回调    --------  purchase-error: $purchaseError');
      FlutterInappPurchase.instance.clearTransactionIOS();
      Navigator.of(context).pop();
    });
  }
}
