import 'dart:async';

import 'package:electronic_assistant/sdk/pay/wxpay/wechat_pay_info.dart';
import 'package:flutter/widgets.dart';
import 'package:wechat_kit/wechat_kit.dart';

import '../assist/agile_pay_state_info.dart';
import '../code/agile_pay_code.dart';
import '../listener/i_agile_pay.dart';

class WechatPay extends AgilePayStateInfo implements IAgilePay {
  late final StreamSubscription<WechatResp> _respSubs;

  final WechatPayInfo _payInfo;

  WechatPay(this._payInfo) {
    _respSubs = WechatKitPlatform.instance.respStream().listen(_listenResp);
  }

  void _listenResp(WechatResp resp) {
    try {
      if (resp is WechatPayResp) {
        final String content = 'pay: ${resp.errorCode} ${resp.errorMsg}';
        debugPrint('agilePay-wechat---> $content');
        if (resp.errorCode == WechatResp.kErrorCodeSuccess) {
          sendPaySuccess(resp.returnKey);
        } else if (resp.errorCode == WechatResp.kErrorCodeUserCancel) {
          sendError(AgilePayCode.payCodeCancelError,
              AgilePayCode.getMessageByCode(AgilePayCode.payCodeCancelError));
        } else {
          sendError(resp.errorCode, resp.errorMsg);
        }
      }
    } catch (e) {
      sendError(AgilePayCode.payCodeOtherError,
          AgilePayCode.getMessageByCode(AgilePayCode.payCodeOtherError));
    } finally {
      dispose();
    }
  }

  Future<bool> isInstalled() {
    return WechatKitPlatform.instance.isInstalled();
  }

  @override
  void pay() async {
    sendPayBefore();
    try {
      await WechatKitPlatform.instance.registerApp(
          appId: _payInfo.appId, universalLink: _payInfo.universalLink);
      if (await check()) {
        if (await isInstalled()) {
          try {
            WechatKitPlatform.instance.pay(
                appId: _payInfo.appId,
                partnerId: _payInfo.partnerId,
                prepayId: _payInfo.prepayId,
                package: _payInfo.package,
                nonceStr: _payInfo.noncestr,
                timeStamp: _payInfo.timestamp,
                sign: _payInfo.sign);
          } catch (e) {
            sendError(AgilePayCode.payCodePayError,
                AgilePayCode.getMessageByCode(AgilePayCode.payCodePayError));
          }
        } else {
          sendError(AgilePayCode.payCodeWxEnvError,
              AgilePayCode.getMessageByCode(AgilePayCode.payCodeWxEnvError));
        }
      } else {
        sendError(AgilePayCode.payCodeWxEnvError,
            AgilePayCode.getMessageByCode(AgilePayCode.payCodeWxEnvError));
      }
    } catch (e) {
      sendError(AgilePayCode.payCodeOtherError,
          AgilePayCode.getMessageByCode(AgilePayCode.payCodeOtherError));
    }
  }

  Future<bool> check() async {
    return WechatKitPlatform.instance.isSupportApi();
  }

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