//
//  QSQuickLogonHandle.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2025/7/18.
//

import Foundation
import NTESQuickPass
import UIKit

class QSQuickLogonHandle: NSObject {
    
    //单例
    static let share = QSQuickLogonHandle()
    
    static var isGetPhoneNumSuccess = false
    
    var currentVC: UIViewController?
    
    // 易盾 token
    var token: String?
    
    // 运营商授权码
    var accessToken: String?
    
    var loginSuccess: (() -> ())?
    
    func starOneQuickLogin(loginSuccess: @escaping () -> ()) {
        self.loginSuccess = loginSuccess
        
        QSLLoading.show()
        NTESQuickLoginManager.sharedInstance().register(withBusinessID:QSLConfig.quick_logon_key_id)
        NTESQuickLoginManager.sharedInstance().getPhoneNumberCompletion { [weak self] resultDic in
            guard let self = self else { return }
            if let isSuccess = resultDic["success"] as? Bool {
                QSQuickLogonHandle.isGetPhoneNumSuccess = isSuccess
                if isSuccess && NTESQuickLoginManager.sharedInstance().shouldQuickLogin() {
                    if let token = resultDic["token"] as? String {
                        QSQuickLogonHandle.share.token = token
                    }
                    NTESQuickLoginManager.sharedInstance().delegate = self
                    self.layoutQuickLoginUI()
                    self.obtionAuthorizeLogin()
                } else {
                    DispatchQueue.main.async {
                        QSLLoading.hide()
                        ///去登录
                        if !QSLBaseManager.shared.isLogin() {
                            gravityInstance?.track(QSLGravityConst.mine_login)
                            QSLJumpManager.shared.pushToLogin(type: .mine)
                        }
                    }
                }
            }
        }
    }
    
    func layoutQuickLoginUI() {
        let model = NTESQuickLoginModel()
//        print("curredfdjf---\(String(describing: currentVC))");
        model.currentVC = currentVC
        
        model.presentDirectionType = .push
        model.authWindowPop = .fullScreen
        model.backgroundColor =  .hexStringColor(hexString: "#E2E2E2")

        // 导航栏
        model.navBarHidden = false
        model.navBgColor = .hexStringColor(hexString: "#E2E2E2")
        model.navText = ""
        model.navTextFont = UIFont.systemFont(ofSize: 14)
        model.navTextColor = .hexStringColor(hexString: "#E2E2E2")
        model.navTextHidden = false
        if let image = UIImage(named: "public_back_btn") {
            model.navReturnImg = image
        }
        model.navReturnImgLeftMargin = 15
        model.navReturnImgBottomMargin = 0
        model.navReturnImgWidth = 44
        model.navReturnImgHeight = 44
        
        // logo
        if let image = UIImage(named: "mine_about_logo") {
            model.logoImg = image
        }
        model.logoWidth = 80
        model.logoHeight = 80
        model.logoOffsetTopY = 50
        model.logoOffsetX = 0
        model.logoHidden = false

        // 手机号
        model.numberColor = QSLColor.Color_202020
        model.numberFont = UIFont.systemFont(ofSize: 18)
        model.numberOffsetTopY = 160
        model.numberOffsetX = 0
        model.numberHeight = 27

        // 品牌标语
        model.brandColor = .hexStringColor(hexString: "#8F8F8F")
        model.brandFont = UIFont.systemFont(ofSize: 12)
        model.brandWidth = 200
        model.brandHeight = 16
        model.brandOffsetX = 0
        model.brandOffsetTopY = 200
        model.brandHidden = false

        // 登录按钮
        model.logBtnText = "本机号码一键登录"
        model.logBtnTextFont = UIFont.systemFont(ofSize: 18)
        model.logBtnTextColor = UIColor.white
        model.logBtnOffsetTopY = 260
        model.logBtnRadius = 8
        model.logBtnUsableBGColor = QSLColor.themeMainColor
        model.logBtnOriginLeft = 24
        model.logBtnOriginRight = 24
        model.logBtnHeight = 56

        // 协议
        if let image = UIImage(named: "login_agree_n") {
            model.uncheckedImg = image
        }
        if let image = UIImage(named: "login_agree_s") {
            model.checkedImg = image
        }

        model.uncheckedImg = UIImage(named: "public_select_btn_false")?.withRenderingMode(.alwaysOriginal) ?? UIImage(named: "")!
        model.checkedImg = UIImage(named: "public_select_btn_true")?.withRenderingMode(.alwaysOriginal) ?? UIImage(named: "")!
        model.checkboxWH = 22
        model.privacyState = false
        model.checkBoxAlignment = .center
        model.checkedSelected = false
        model.checkBoxMargin = 5
//        model.appPrivacyOriginLeftMargin = 32
//        model.appPrivacyOriginRightMargin = 12
        model.appPrivacyOriginBottomMargin = 40
        if let image = UIImage(named: "public_back_btn") {
            model.privacyNavReturnImg = image
        }
//        model.privacyNavReturnImg = UIImage(named: "navigation_back") ?? UIImage(named: "")
        model.appPrivacyText = "已阅读并同意《隐私权政策》、《用户协议》"
        model.appFPrivacyText = "《隐私权政策》"
        model.appFPrivacyURL = QSLConfig.AppPrivacyAgreementLink
        model.appSPrivacyText = "《用户协议》"
        model.appSPrivacyURL =  QSLConfig.AppServiceAgreementLink
        model.shouldHiddenPrivacyMarks = false
        model.privacyColor = .hexStringColor(hexString: "#404040")//.hexStringColor(hexString: "#2F79FF")
        model.privacyFont = UIFont.systemFont(ofSize: 12)
        model.protocolColor = .hexStringColor(hexString: "#2F79FF")
        model.appPrivacyLineSpacing = 1
        model.appPrivacyWordSpacing = 0
        model.progressColor = .hexStringColor(hexString: "#D9D9D9")
        
        model.toastBackgroundColor = .white//.hexStringColor(hexString: "#171717")
        model.toastTitleText = "隐私政策及权限说明"
//        model.toastTitleFontSize = 14
        model.toastTitleTextColor = QSLColor.Color_202020//.white

        //同意按钮
        model.toastConfirmText = "同意并继续"
        model.toastConfirmBorderColor = .clear
        model.toastConfirmTextColor = .white
        model.toastConfirmBackgroundColor = .hexStringColor(hexString: "#15CBA1")
        model.toastConfirmCornerRadius = 18
        
        //不同意按钮
        model.toastCancelText = "不同意"
        model.toastCancelBorderColor = .clear
        model.toastCancelBackgroundColor = .hexStringColor(hexString: "#F8F8F8")
        model.toastCancelTextColor = .hexStringColor(hexString: "#A7A7A7")
        model.toastEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        
        model.toastContentTextColor = .hexStringColor(hexString: "#404040")
        model.toastContentFontWeight = .regular
        model.toastContentPrefixText = "需同意"
        model.toastContentSuffixText = "才能继续享受我们的服务，您的信任对我们非常重要!如您仍不同意本隐私政策与服务条例，很遗憾我们难以为您继续服务~"
        model.toastProtocolTextColor = .hexStringColor(hexString: "#6B9CF2")

        // 添加自定义按钮 “验证码登录”
        model.customViewBlock = { customView in
            let codeLoginBtn = UIButton(type: .system)
            codeLoginBtn.setTitle("验证码登录", for: .normal)
            codeLoginBtn.setTitleColor(QSLColor.Color_202020, for: .normal)
            codeLoginBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            codeLoginBtn.backgroundColor = .clear
            codeLoginBtn.layer.cornerRadius = 20
            codeLoginBtn.addTarget(self, action: #selector(self.codeLoginAction), for: .touchUpInside)
            
            customView?.addSubview(codeLoginBtn)
            codeLoginBtn.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                codeLoginBtn.topAnchor.constraint(equalTo: customView!.topAnchor, constant: 340),
                codeLoginBtn.leadingAnchor.constraint(equalTo: customView!.leadingAnchor, constant: 80),
                codeLoginBtn.trailingAnchor.constraint(equalTo: customView!.trailingAnchor, constant: -80),
                codeLoginBtn.heightAnchor.constraint(equalToConstant: 30)
            ])
        }
        
        model.backActionBlock = { backType in
            if backType == 2 {
                self.currentVC?.navigationController?.popViewController(animated: true)
            }
        }

        model.loginActionBlock = { isCheck in
            if isCheck {
                QSLLoading.show()
            }
        }
        
        NTESQuickLoginManager.sharedInstance().setupModel(model)
    }
    
    func obtionAuthorizeLogin() {
        NTESQuickLoginManager.sharedInstance().cucmctAuthorizeLoginCompletion({ resultDic in
            if let isSuccess = resultDic["success"] as? Bool {
                if isSuccess {
                    if let accessToken = resultDic["accessToken"] as? String {
                        self.accessToken = accessToken
                    }
                    Task {
                        await self.requestOneClickLogin()
                    }
                } else {
                    QSLLoading.hide()
                    Task { @MainActor in
                        self.showMyToast(showText: "一键登录失败，请使用验证码登录")
                    }
                }
            }
        })
    }
     
    func requestOneClickLogin() async {
        guard let token = self.token else {
            return
        }
        guard let accessToken = self.accessToken else {
            return
        }
        QSLLoading.show()
        QSLNetwork().request(.loginOneclick(dict:["token": token, "accessToken": accessToken]), success: { response in
            QSLLoading.hide()
            let authToken = response.toJSON(modelKey: "data>authToken").stringValue
            let phone = response.toJSON(modelKey: "data>phone").stringValue
            QSLBaseManager.shared.loginUpdateUser(authToken: authToken, phone: phone)
            // 使用时必须异步调用
            Task { @MainActor in
                self.showMyToast(showText:  "登录成功")
            }
            gravityInstance?.track(QSLGravityConst.login_success)
            // 发送通知
            NotificationCenter.default.post(name: QSLNotification.QSLLogin, object: nil)
            // 发送通知
            NotificationCenter.default.post(name: QSLNotification.QSLRefreshMember, object: nil)
            
            // 返回
            Task { @MainActor in
                self.popCurrentViewController()
            }
            
        }, fail: { code, error in
            if code == 1005 {
                gravityInstance?.track(QSLGravityConst.login_fail, properties: ["id": 1002])
            } else {
                gravityInstance?.track(QSLGravityConst.login_fail, properties: ["id": 1003])
            }
            QSLLoading.hide()
            //self.currentVC?.view.toast(text: error)
            Task { @MainActor in
                self.showMyToast(showText: error)
            }
        })
    }
    
    @objc @MainActor func popCurrentViewController() {
        self.currentVC?.navigationController?.popViewController(animated: true)
    }
    
    @objc @MainActor func showMyToast(showText: String) {
        UIApplication.keyWindow?.toast(text: showText)
    }
    
    
    // MARK: - 你需要实现的按钮点击方法
    @objc func codeLoginAction() {
        // 实现你的验证码登录逻辑
        print("验证码登录按钮点击")
        ///去登录
        if !QSLBaseManager.shared.isLogin() {
            gravityInstance?.track(QSLGravityConst.mine_login)
            
            let longinvc = QSLLoginViewController()
            longinvc.type = .onQucikLogin
            self.currentVC?.pushVC(vc: longinvc)

        }
    }
}

extension QSQuickLogonHandle: NTESQuickLoginManagerDelegate {
    
    func authViewDidAppear() {
       
    }
    
    func authViewDealloc() {
        
    }
    
    func authViewDidLoad() {
        
    }
    
    func authViewWillAppear() {
        QSLLoading.hide()
    }
    
    func authViewDidDisappear() {
        
    }
    
    func authViewWillDisappear() {
        
    }
}
