//
//  RealnameHelper.swift
//  account_center
//
//  Created by MrQi on 2025/3/12.
//

import Foundation
import WebKit

public class RealnameHelper {
    
    public class func clx_handleRealname(complent: () -> RealnameConfig) {
        let config = complent()
        
        guard let url = config.url else {
            config.decisionHandler(.allow)
            return
        }
        guard url.absoluteString.removingPercentEncoding != nil else {
            config.decisionHandler(.allow)
            return
        }
        if url.host?.isZmxy == true {
            /// 芝麻认证
            config.decisionHandler(.cancel)
            openAlipay(url: url, target: config.target)
        } else if (url.scheme?.isAlipays == true) {
            config.decisionHandler(.cancel)
            openAlipay(url: url, target: config.target)
        } else if (url.absoluteString.isSign) {
            config.decisionHandler(.cancel)
            config.target?.dismiss(animated: true)
            config.signComplent?(url.absoluteString.isSignSucc ? 1 : 0)
        } else if (url.absoluteString.isRealname) {
            config.decisionHandler(.cancel)
            config.target?.dismiss(animated: true)
            config.realNameComplent?(url.absoluteString.isRealnameSucc ? 1 : 0)
        } else if (url.absoluteString.isLoadPDF) {
            config.decisionHandler(.cancel)
            CLXFileManagePlugin.downloadFile(filePath: url.absoluteString) { res in
                
            }
        } else {
            config.decisionHandler(.allow)
        }
    }
    
    /// 打开支付宝
    private class func openAlipay(url: URL?, target: UIViewController?) {
        guard let openUrl = url else { return }
        if UIApplication.shared.canOpenURL(openUrl) {
            UIApplication.shared.open(openUrl)
        } else {
            let alert = UIAlertController(
                title: "",
                message: "无法打开支付宝，请切换验证方式",
                preferredStyle: .alert
            )
            let cancelAction = UIAlertAction(title: "确定", style: .cancel)
            alert.addAction(cancelAction)
            alert.modalPresentationStyle = .fullScreen
            target?.present(alert, animated: true)
        }
    }
}
