import 'dart:async';

import 'package:flutter/widgets.dart';

import '../assist/agile_pay_state_info.dart';
import '../code/agile_pay_code.dart';
import '../listener/i_agile_pay.dart';
import 'ali_pay_info.dart';
import 'package:alipay_kit/alipay_kit.dart';

class Alipay extends AgilePayStateInfo implements IAgilePay {
  final AliPayInfo _aliPayInfo;

  late final StreamSubscription<AlipayResp> _paySubs;

  Alipay(this._aliPayInfo) {
    _paySubs = AlipayKitPlatform.instance.payResp().listen(_listenPay);
  }

  void _listenPay(AlipayResp resp) {
    final String content = 'pay: ${resp.resultStatus} - ${resp.result}';
    debugPrint('agilePay-alipay---> $content');
    try {
      int code = AgilePayCode.payCodeOtherError;
      if (resp.resultStatus == AgilePayCode.payCodeAlipaySuccess) {
        sendPaySuccess(resp.result);
      } else {
        if (resp.resultStatus != null &&
            AgilePayCode.resultStatus.containsKey(resp.resultStatus)) {
          code = resp.resultStatus!;
        }
        sendPayError(code, AgilePayCode.getMessageByCode(code));
      }
    } catch (e) {
      sendError(AgilePayCode.payCodeOtherError,
          AgilePayCode.getMessageByCode(AgilePayCode.payCodeOtherError));
    } finally {
      dispose();
    }
  }

  @override
  void pay() {
    sendPayBefore();
    try {
      AlipayKitPlatform.instance.pay(
        orderInfo: _aliPayInfo.payInfo,
      );
    } catch (e) {
      sendError(AgilePayCode.payCodePayError,
          AgilePayCode.getMessageByCode(AgilePayCode.payCodePayError));
    }
  }

  void dispose() {
    _paySubs.cancel();
  }
}
