//
//  YHRealNameHelper.swift
//  galaxy
//
//  Created by edy on 2024/9/20.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

enum YHRealnameResult: Int {
    case cancel = 0
    case failed = 1
    case success = 2
}

enum YHURLHandleResult: Int {
    case null = 0
    case cancel = 1
    case allow = 2
}


protocol YHRealNameDelegate: AnyObject {
    func realnameJumptoAlipay()
    func realnameResult(_ result: YHRealnameResult)
    func signResult(_ status: Bool)
}

class YHRealNameHelper {
    
    // 实名回调地址
    static let callbackScheme = "esign://demo"
    // 实名的回调跟 生成实名H5链接的入参redirectUrl相关
    static let realnameCallback = "esign://demo/realBack"
    // 签署的appScheme 入参
    static let signCallback = "esign://demo/signBack"
    
    static let jumpToAlipay = "alipays://platformapi/startapp?appId=20000067&url="
    // 签署H5回调的结果 会根据redirectUrl入参变化，需要同步
    static let signResultWebCloseJSFunction = "jsbridge://signCallback"
    // // 实名H5回调的结果 会根据redirectUrl入参变化，需要同步
    static let realResultWebCloseJSFunction = "esign://demo/realBack"
    
    @discardableResult
    class func handleRealnameURL(_ url: URL, delegate: YHRealNameDelegate?) -> YHURLHandleResult {
        // 获取完整url并进行UTF-8转码
        let requestUrl = url.absoluteString.removingPercentEncoding ?? ""
        
        if url.host == "zmcustprod.zmxy.com.cn" { // 跳转芝麻认证
            delegate?.realnameJumptoAlipay()
            let requestEncodeUrl = YHURLEncodeHelper.urlEncodedString(requestUrl) ?? ""
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(URL(string: "\(jumpToAlipay)\(requestEncodeUrl)")!, options: [:], completionHandler: nil)
            } else {
                UIApplication.shared.open(URL(string: "\(jumpToAlipay)\(requestEncodeUrl)")!)
            }
            return .cancel
            
        } else if url.scheme == "alipays", url.host == "platformapi" { // 跳转到支付宝
            if requestUrl.range(of: "?") == nil {
                delegate?.realnameResult(.cancel)
            } else {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        } else if requestUrl.hasPrefix(signResultWebCloseJSFunction) || requestUrl.hasPrefix(signCallback) { // H5 签署返回结果处理
            let params = extractParameters(from: requestUrl)
            if params.isEmpty {
                delegate?.realnameResult(.cancel)
            } else {
                var status = (params["signResult"]?.boolValue() ?? false)
                if !status, let tsignCode = params["tsignCode"] {
                    status = (tsignCode.intValue() == 0)
                }
                delegate?.signResult(status)
            }
            return .cancel
        } else if requestUrl.hasPrefix(callbackScheme) || requestUrl.hasPrefix("js://tsignRealBack") || requestUrl.hasPrefix("js://signCallBack") { // H5 实名返回结果处理
            if requestUrl.contains(realResultWebCloseJSFunction) {
                let params = extractParameters(from: requestUrl)
                let status = params["passed"]?.boolValue() ?? false
                delegate?.realnameResult(status ? .success : .failed)
            }
            return .cancel
        }
        
        return .allow
    }
    
    private class func extractParameters(from url: String) -> [String: String] {
        var params = [String: String]()
        if let range = url.range(of: "?") {
            let strParam = String(url[range.upperBound...])
            let pairs = strParam.split(separator: "&")
            for pair in pairs {
                let items = pair.split(separator: "=")
                if items.count == 2 {
                    params[String(items[0])] = String(items[1])
                }
            }
        }
        return params
    }
}

extension String {
    func boolValue() -> Bool {
        return (self as NSString).boolValue
    }
    
    func intValue() -> Int {
        return (self as NSString).integerValue
    }
}
