
import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:twong/utils/pay.dart';
// import 'package:wechat_kit/wechat_kit.dart';
import 'package:alipay_kit/alipay_kit.dart';

import 'package:twong/api/index.dart';
import 'package:twong/utils/index.dart';
import 'package:twong/router/index.dart';
import 'package:twong/models/index.dart';
import 'package:twong/config/pay_config.dart';

class PaymentInfo {
  int addressId;
  num integral;
  String orderId;
  String orderKey;
  String price;
  num rechargeId;


  PaymentInfo.id(this.orderId);
  PaymentInfo.recharge(this.rechargeId, this.price);
  PaymentInfo(this.orderKey, this.addressId, this.integral);
}

class Payment extends StatefulWidget {
  final PaymentInfo info;
  Payment(this.info);

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

class _PaymentState extends State<Payment> {
  String _orderId = "";

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

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Container(
        height: 260.px,
        child: Column(
          children: [
            Stack(
              children: [
                Container(
                    width: double.infinity,
                    margin: EdgeInsets.only(top: 6.px, bottom: 6.px),
                    child: Text("选择付款方式", style: TextStyle(fontSize: 16.px), textAlign: TextAlign.center)
                ),
                Positioned(
                    top: 8.px,
                    right: 12.px,
                    child: InkWell(
                      onTap: () => Navigator.pop(context),
                      child: Icon(Icons.close, color: Colors.grey, size: 18.px),
                    ))
              ],
            ),
            _buildPaymentButtons()
          ],
        ),
      ),
    );
  }

  Widget _buildPaymentButtons() {
    List<Widget> widgets = List<Widget>();
    var configs = PayConfig.payTypes;
    if(widget.info.rechargeId != null) {
      configs.removeWhere((element) => element.key == "yue");
    }

    for(var conf in configs) {
      widgets.add(Divider());
      widgets.add(InkWell(
        onTap: () => _onPay(conf),
        child: Container(
          height: 40.px,
          margin: EdgeInsets.only(left: 12.px, right: 12.px),
          child: Row(
            children: [
              Container(
                margin: EdgeInsets.only(right: 16.px, left: 6.px),
                child: conf.icon,
              ),
              Expanded(child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("${conf.name}支付", style: TextStyle(fontSize: 14.px)),
                  conf.type == PayType.yue ? RichText(text: TextSpan(
                    text: conf.desc,
                    style: TextStyle(color: Colors.grey),
                    children: [TextSpan(
                      text: Utils.formatRMB(Cache.user.now_money, show: true),
                      style: TextStyle(color: Colors.redAccent, fontSize: 12.px)
                    )]
                  )) : Text(conf.desc, style: TextStyle(color: Colors.grey, fontSize: 12.px))
                ],
              )),
              Icon(Icons.chevron_right, color: Colors.grey)
            ],
          ),
        ),
      ));
    }
    widgets.add(Divider());
    return Container(
      child: Column(children: widgets),
    );
  }

  void _onPay(PayInfo conf) async {
    Utils.loading();
    OrderInfo info;
    try {
      if (widget.info.orderId != null) {
        info = await Network.inst.payOrder(payType: conf.key,
            orderId: widget.info.orderId);

        _orderId = widget.info.orderId;
      } else if(widget.info.orderKey != null) {
        info = await Network.inst.createOrder(payType: conf.key,
            address: widget.info.addressId,
            orderKey: widget.info.orderKey,
            integral: widget.info.addressId);

        _orderId = info.result["orderId"];
      } else if(widget.info.price != null) {
        info = await Network.inst.recharge(type: conf.key,
            price: widget.info.price,
            id: widget.info.rechargeId);
      }
      Log.d(info.toJson());
    } catch (err, stack) {
      // Log.d(err);
      // Log.e(stack);
      Utils.closeLoading();
      Navigator.pop(context);
      return;
    }

    switch(conf.type) {
      case PayType.alipay:
        aliPay(info);
        break;
      case PayType.wechat:
        wechatPay(info);
        break;
      case PayType.yue:
        _payOver();
        break;
      default:
        Log.e("Unknown pay type: ${conf.key}");
        break;
    }
  }

  void aliPay(OrderInfo info) {
    var payConf = info.result["jsConfig"];
    Pay.aliPay(payConf, callback: (success) {
      _payOver();
    });
  }

  void wechatPay(OrderInfo info) {
    var payConf = info.result["jsConfig"];
    Pay.wechatPay(payConf, callback: (success) {
      _payOver();
    });
  }

  void _listenAliPay(AlipayResp resp) {
    Log.d('Alipay : ${resp.resultStatus} - ${resp.result} ${resp.memo}');
    Utils.closeLoading();
  }

  // void _listenWechatPay(WechatPayResp resp) {
  //   Log.d('WechatPay : ${resp.returnKey} - ${resp.errorCode}: ${resp.errorMsg}');
  //   Utils.closeLoading();
  // }

  void _payOver() {
    Utils.closeLoading();
    Navigator.pushNamedAndRemoveUntil(context, RouteNames.orderDetails,
        ModalRoute.withName('/'), arguments: _orderId);
  }
}