
import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.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;
  double integral;
  String orderId;
  String orderKey;

  PaymentInfo.id(this.orderId);
  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 = "";
  Alipay _alipay = Alipay();
  Wechat _wechat = Wechat();
  StreamSubscription<AlipayResp> _alipayResp;
  StreamSubscription<WechatPayResp> _wechatResp;

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

  @override
  void dispose() {
    _alipayResp?.cancel();
    _alipayResp = null;
    _wechatResp?.cancel();
    _wechatResp = null;
    super.dispose();
  }

  @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>();
    for(var conf in PayConfig.payTypes) {
      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(
                width: 68.px,
                child: Text(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 {
    OrderInfo info;
    if (widget.info.orderKey == null) {
      info = await Network.inst.payOrder(payType: conf.key,
          orderId: widget.info.orderId);
    } else {
      info = await Network.inst.createOrder(payType: conf.key,
          address: widget.info.addressId,
          orderKey: widget.info.orderKey,
          integral: widget.info.addressId);
    }
    if (info == null) return;

    Log.d(info.toJson());
    _orderId = info.result.orderId;
    switch(conf.type) {
      case PayType.alipay:
        aliPay(info);
        break;
      case PayType.wechat:
        wechatPay(info);
        break;
      case PayType.yue:
        yuePay(info);
        break;
      default:
        Log.e("Unknown pay type: ${conf.key}");
        break;
    }
  }

  void aliPay(OrderInfo info) {
    var payConf = info.result.jsConfig;
    _alipay.payResp().listen(_listenAliPay);
    _alipay.isInstalled().then((install) {
      if (install) {
        Log.d("begin alipay ...");
        _alipay.payOrderSign(orderInfo: payConf);
      } else {
        Log.e("alipay is not install");
        Navigator.pop(context);
        BotToast.showText(text: "没有安装支付宝");
      }
    });
  }

  void wechatPay(OrderInfo info) {
    var payConf = info.result.jsConfig;
    _wechat.registerApp(appId: payConf["appid"], universalLink: PayConfig.universalLink);
    _wechat.payResp().listen(_listenWechatPay);
    _wechat.isInstalled().then((install) {
      if (install) {
        Log.d("begin wechat pay ...");
        _wechat.pay(appId: payConf["appid"], partnerId: payConf["partnerid"],
            prepayId: payConf["prepayid"], package: payConf["package"],
            nonceStr: payConf["noncestr"], timeStamp: payConf["timestamp"].toString(),
            sign: payConf["sign"]);
      } else {
        Log.e("wechat is not install");
        Navigator.pop(context);
        BotToast.showText(text: "没有安装微信");
      }
    });
  }

  void yuePay(OrderInfo info) {

  }

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

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

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