//
//  YHLoginMethodManager.swift
//  galaxy
//
//  Created by edy on 2024/5/27.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AVFoundation

class YHOneKeyLoginManager {
    
    static let shared = YHOneKeyLoginManager()
    let viewModel = YHOneKeyLoginViewModel()
    // 防止重复点击登录
    var isLoginEnabled = true
}

extension YHOneKeyLoginManager {
    
    func oneKeyLogin() {
        if !isLoginEnabled {
            return
        }
        isLoginEnabled = false
#if targetEnvironment(simulator)
        self.enterAppNativeLoginPage(isFromOneKeyPage: false)
#else
        YHOneKeyLoginManager.shared.checkIsSupportOneKeyLogin {
            support in
            if !support {
                printLog("不支持一键登录")
                // 跳转APP自定义登录界面
                self.enterAppNativeLoginPage(isFromOneKeyPage: false)
                return
            }
            // 支持一键登录
            YHOneKeyLoginManager.shared.enterOneKeyLoginPage()
        }
#endif
    }
    
    // 进入App自己设计的主登录界面
    // @param isFromOneKeyPage:是否是从一键登录界面进入
    func enterAppNativeLoginPage(isFromOneKeyPage: Bool) {
        self.isLoginEnabled = true
        if isFromOneKeyPage {
            let vc = YHOtherLoginViewController()
            UIViewController.current?.navigationController?.pushViewController(vc, animated: true)
            return
        }
        let vc = UINavigationController(rootVC: YHOtherLoginViewController())
        vc.modalPresentationStyle = .fullScreen
        UIViewController.current?.present(vc, animated: true)
    }
    
    func getSDKVersion() -> String {
        return TXCommonHandler.sharedInstance().getVersion()
    }
    
    func configOneKeyLogin() {
        if YHNetworkStatusManager.shared.isNetWorkOK == false {
            return
        }
        
        self.viewModel.getSecretKeyInfo {
            secretKey in
            
            var targetKey = secretKey
            if secretKey.isEmpty {
                targetKey = YhConstant.Alipay.kAliLoginDefaultSecretKey
            }
            printLog("onekey login secretKey: \(targetKey)")
            TXCommonHandler.sharedInstance().setAuthSDKInfo(targetKey) {
                dict in
                printLog("设置secretKey结果：\(dict)")
                // 进行加速登录 方便点击登录时提速
                TXCommonHandler.sharedInstance().accelerateLoginPage(withTimeout: 5.0) {
                    dic in
                    printLog("加速登录结果: \(dic)")
                }
            }
        }
    }
    
    func checkIsSupportOneKeyLogin(_ support: ((Bool) -> Void)?) {
        // 检测当前环境是否支持一键登录
        TXCommonHandler.sharedInstance().checkEnvAvailable(with: .loginToken) {
            dict in
            
            printLog("checkEnvAvailable: \(String(describing: dict))")

            if let resultCode = dict?["resultCode"] as? String, resultCode == PNSCodeSuccess {
                support?(true)
            } else {
                support?(false)
            }
        }
    }
    
    func requestOneKeyLogin(token: String) {
        YHHUD.show(.progress(message: "登录中..."))
        let deviceId = YHLoginManager.shared.deviceTokenModel.registerId
        printLog("oneKey Login deviceId: \(deviceId)")
        printLog("oneKey Login token: \(token)")
        
        self.viewModel.oneKeyLogin(authToken: token) {
            success, error in
            DispatchQueue.main.async {
                YHHUD.hide()
                if success {
                    YHLoginManager.shared.loginSuccessActionBlock?()
                    if YHLoginManager.shared.userModel?.is_first_login == 1 {
                        let vc = YHUserInfoSettingViewController()
                        vc.modalPresentationStyle = .fullScreen
                        UIViewController.current?.navigationController?.pushViewController(vc)
                    } else {
                        TXCommonHandler.sharedInstance().cancelLoginVC(animated: true)
                    }
                    return
                }
                if let err = error {
                    var msg = err.errorMsg
                    if msg.isEmpty {
                        msg = "登录失败"
                    }
                    YHHUD.flash(message: msg)
                }
            }
        }
    }
    
    func enterOneKeyLoginPage() {
        
        // 3. 开始一键登录流程
            // 3.2 调用获取登录Token接口，可以立马弹起授权页，model的创建需要放在主线程
            let model = self.createLoginUIModel()
            YHHUD.show(.progress(message: "加载中..."))
                       
            TXCommonHandler.sharedInstance().getLoginToken(withTimeout: 5.0, controller: UIViewController.current!, model: model) {
                dict in
                
                self.isLoginEnabled = true
                DispatchQueue.main.async {
                    YHHUD.hide()
                }
                
                guard let code = dict["resultCode"] as? String else {
                    printLog(dict)
                    return
                }
                
                if code == PNSCodeSuccess {
                    // 点击登录按钮获取登录Token成功回调
                    guard let token = dict["token"] as? String, !token.isEmpty else {
                        YHHUD.flash(message: "获取token失败")
                        return
                    }
                    printLog("oneKeyLogin token: \(token)")
                    // 下面用Token去服务器登录
                    if YHLoginManager.shared.deviceTokenModel.registerId.isEmpty {
                        YHHUD.show(.progress(message: "登录中..."))
                        JPUSHService.registrationIDCompletionHandler {
                            _, registrationID in
                            YHHUD.hide()
                            YHLoginManager.shared.deviceTokenModel.registerId = registrationID ?? ""
                            self.requestOneKeyLogin(token: token)
                        }
                    } else {
                        self.requestOneKeyLogin(token: token)
                    }
                    return
                }
                
                // 以下是处理一键登录异常
                
                if code == PNSCodeLoginControllerPresentFailed {
                    printLog("弹起授权页失败")
                    // 此时一键登录界面未显示
                    self.enterAppNativeLoginPage(isFromOneKeyPage: false)
                    
                } else if code == PNSCodeLoginControllerPresentSuccess {
                    printLog("弹起授权页成功")
                    
                } else if code == PNSCodeCallPreLoginInAuthPage {
                    printLog("授权页已加载时不允许调用加速或预取号接口")
                    
                } else if code == PNSCodeLoginControllerClickCancel {
                    printLog("点击了授权页的返回")
                    
                } else if code == PNSCodeLoginControllerClickChangeBtn {
                    printLog("点击切换其他登录方式按钮")
                    
                } else if code == PNSCodeLoginControllerClickLoginBtn {
                    
                    if let isChecked = dict["isChecked"] as? Bool, isChecked == true {
                        printLog("点击了登录按钮，check box选中，SDK内部接着会去获取登录Token")
                    } else {
                        printLog("点击了登录按钮，check box未选中，SDK内部不会去获取登录Token")
                    }
                    
                } else if code == PNSCodeLoginControllerClickCheckBoxBtn {
                    printLog("点击了check box")
                    
                } else if code == PNSCodeLoginControllerClickProtocol {
                    printLog("点击了协议富文本")
    
                } else if code == PNSCodeLoginClickPrivacyAlertView {
                    printLog("点击一键登录拉起授权页二次弹窗")
                    
                } else if code == PNSCodeLoginPrivacyAlertViewClose {
                    printLog("点击隐私协议二次弹窗关闭")
                    
                } else if code == PNSCodeLoginPrivacyAlertViewClickContinue {
                    printLog("隐私协议二次弹窗点击确认并继续")
                    
                } else if code == PNSCodeLoginPrivacyAlertViewPrivacyContentClick {
                    printLog("点击隐私协议二次弹窗上的协议富文本文字")
                    
                } else if code == PNSCodeLoginControllerSuspendDisMissVC {
                    printLog("中断页面消失的时候，也就是suspendDisMissVC设置为YES的时候")
                    
                } else {
                    printLog("其他错误：\(dict)")
                    self.enterAppNativeLoginPage(isFromOneKeyPage: false)
                }
            }
    }
    
    func isRunningOnSimulator() -> Bool {
        return ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] != nil
    }
    
    func createLoginUIModel() -> TXCustomModel {
        
        let model = TXCustomModel()
        model.navIsHidden = true
        model.sloganIsHidden = true
        model.logoIsHidden = true
        model.changeBtnIsHidden = true
        // 配置二次弹窗
        model.privacyAlertIsNeedShow = true
        
        // 协议勾选框UI自定义
        let uncheckedImg = UIImage(named: "login_privacy_disagree_white")!
        let checkedImg = UIImage(named: "login_privacy_agree_white")!
        model.checkBoxImages = [uncheckedImg, checkedImg]
        model.checkBoxWH = 18.0
        model.checkBoxImageEdgeInsets = UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3)
        
        model.privacyFont = .PFSC_R(ofSize: 12)
        model.privacyOperatorPreText = "《"
        model.privacyOperatorSufText = "》"
        model.privacyOne = ["《隐私协议》", YHBaseUrlManager.shared.curPrivacyAgreementUrl()]
        model.privacyTwo = ["《用户条款》", YHBaseUrlManager.shared.curUserItemsUrl()]
        
        let privacyUnclickColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.7)
        let privacyClickColor = UIColor.white
        model.privacyColors = [privacyUnclickColor, privacyClickColor]
        model.privacyFrameBlock = {
            _, superViewSize, _ in
            return CGRect(x: 24, y: KScreenHeight-40-40, width: superViewSize.width-48, height: 40)
        }
        
        model.loginBtnFrameBlock = {
            _, superViewSize, _ in
            return CGRect(x: 24, y: KScreenHeight-40-40-30-48, width: superViewSize.width-48, height: 48)
        }
        
        // 手机号码UI自定义
        model.numberColor = .white
        model.numberFont = UIFont(name: "DINAlternate-Bold", size: 30)!
        model.numberFrameBlock = {
            _, _, frame in
            return CGRect(x: frame.minX, y: KScreenHeight-40-40-30-20-48-35, width: frame.width, height: 35)
        }
        
        // 登录按钮自定义UI
        model.loginBtnText = NSAttributedString(string: "本机号码一键登录/注册", attributes: [NSAttributedString.Key.foregroundColor: UIColor.mainTextColor, NSAttributedString.Key.font: UIFont.PFSC_M(ofSize: 16)])
        
        let enableLoginBgImg = TXCommonUtils.image(with: .white, size: CGSize(width: KScreenWidth-20*2, height: 48), isRoundedCorner: true, radius: kCornerRadius3)!
        let disableLoginBgImg = TXCommonUtils.image(with: .white, size: CGSize(width: KScreenWidth-20*2, height: 48), isRoundedCorner: true, radius: kCornerRadius3)!
        let imgArr: [UIImage] = [enableLoginBgImg, disableLoginBgImg, enableLoginBgImg]
        model.loginBtnBgImgs = imgArr
        
        // 创建视频底图View
        let videoBgView = YHOneKeyLoginView(frame: UIScreen.main.bounds)
        videoBgView.closeBlock = {
            TXCommonHandler.sharedInstance().cancelLoginVC(animated: true)
        }
        // 改变登录方式
        videoBgView.changeLoginBlock = {
            [weak self] in
            guard let self = self else { return }
            self.enterAppNativeLoginPage(isFromOneKeyPage: true)
        }
        
        model.customViewBlock = {
            superCustomView in
                superCustomView.insertSubview(videoBgView, at: 0)
        }
        model.customViewLayoutBlock = {
            _, _, _, _, _, _, _, _, _, _ in
               
                videoBgView.frame = UIScreen.main.bounds
        }
        
        if model.privacyAlertIsNeedShow == false {
            return model
        }
        
        // 配置二次弹窗
        model.privacyAlertIsNeedShow = true
        model.privacyAlertMaskAlpha = 0.5
        model.privacyAlertMaskColor = .black
        model.privacyAlertCornerRadiusArray = [6, 6, 6, 6]
        model.privacyAlertBackgroundColor = .white
        model.privacyAlertAlpha = 1.0
        model.privacyAlertTitleBackgroundColor = .white
        model.privacyAlertContentBackgroundColor = .white
        model.privacyAlertTitleFont = .PFSC_M(ofSize: 17)
        model.privacyAlertContentFont = .PFSC_R(ofSize: 16)
        model.privacyAlertTitleColor = UIColor.black
        model.privacyAlertContentAlignment = .left
        model.privacyAlertContentColors = [.black, .brandMainColor]
        let activeImage = TXCommonUtils.image(with: .brandMainColor, size: CGSize(width: UIScreen.main.bounds.size.width - 2 * 18, height: 45), isRoundedCorner: true, radius: 3)!
        let hightLightImage = TXCommonUtils.image(with: .brandMainColor, size: CGSize(width: UIScreen.main.bounds.size.width - 2 * 18, height: 45), isRoundedCorner: true, radius: 3)!
        model.privacyAlertBtnBackgroundImages = [activeImage, hightLightImage]
        
        model.privacyAlertButtonTextColors = [UIColor.white, UIColor.white]
        model.privacyAlertButtonFont = .PFSC_M(ofSize: 14)
        model.privacyAlertCloseButtonIsNeedShow = true
        model.privacyAlertMaskIsNeedShow = true
        model.privacyAlertIsNeedAutoLogin = true
        model.tapPrivacyAlertMaskCloseAlert = false
        model.expandAuthPageCheckedScope = true
        model.privacyAlertCloseButtonIsNeedShow = true
        
        let alertGap = 38.0
        let alertWidth = KScreenWidth-alertGap*2
        let alertContentWidth = alertWidth-21.0*2
        let titleHeight = 24.0
        let alertBtnWith = alertWidth-16.0*2
        let alertBtnHeight = 45.0
        
        var currentTop: CGFloat = 0.0
        model.privacyAlertTitleFrameBlock = {
            _, _, frame in
            return CGRect(x: 0, y: 15, width: frame.size.width, height: titleHeight)
        }
        currentTop += 15.0+titleHeight
        let text = "我已阅读并同意《中国移动认证服务条款》和《用户隐私协议》、《用户条款》"
        let attributes = [NSAttributedString.Key.font: UIFont.PFSC_R(ofSize: 16)] as [NSAttributedString.Key: Any]
        let boundingSize = (text as NSString).boundingRect(
            with: CGSize(width: alertContentWidth, height: .greatestFiniteMagnitude),
            options: .usesLineFragmentOrigin,
            attributes: attributes,
            context: nil
        ).size

#if targetEnvironment(simulator)
// 这段代码只会在模拟器上编译
        let textHeight = ceill(Float80(boundingSize.height))

        model.privacyAlertPrivacyContentFrameBlock = {
            _, _, _ in
            return CGRect(x: 21.0, y: 15.0+24.0+33.0, width: alertContentWidth, height: CGFloat(textHeight))
        }
        currentTop = currentTop + 33.0 + Double(textHeight)
#else
// 这段代码只会在真机上编译
        let textHeight = ceill(boundingSize.height)

        model.privacyAlertPrivacyContentFrameBlock = {
            _, _, _ in
            return CGRect(x: 21.0, y: 15.0+24.0+33.0, width: alertContentWidth, height: CGFloat(textHeight))
        }
        currentTop = currentTop + 33.0 + Double(textHeight)
        
        model.privacyAlertButtonFrameBlock = {
            _, _, _ in
            return CGRect(x: 16, y: 15+24+33+textHeight+36.0, width: alertBtnWith, height: alertBtnHeight)
        }
#endif
        
        currentTop += 36.0+alertBtnHeight
        let totalHeight =  currentTop + 16.0
        model.privacyAlertFrameBlock = {
            _, superViewSize, _ in
            return CGRect(x: alertGap, y: (superViewSize.height-totalHeight)/2.0, width: alertWidth, height: totalHeight)
        }
        if let closeImg = UIImage(named: "person_info_close_btn") {
            model.privacyAlertCloseButtonImage = closeImg
        }
        model.privacyAlertCloseFrameBlock = {
            _, _, _ in
            return CGRect(x: alertWidth-16.0-24.0, y: 15, width: 24, height: 24)
        }
        return model
    }
}
