//
//  YHPhoneLoginViewController.swift
//  galaxy
//
//  Created by EDY on 2024/2/5.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift

enum YHLoginType: Int {
    // 默认手机号一键登录
    case normal = 0
    // 常规手机号验证码登录
    case phone
    // 微信第三方登录
    case wechat
    // 苹果第三方登录
    case apple
}

class YHOtherLoginViewController: YHBaseViewController {
    
    var bgImageView: UIImageView!
    var closeButton: UIButton!
    var logImageView: UIImageView!
    var loginTitleLabel: UILabel!
    var loginSubTitleLabel: UILabel!
    var phoneMessageView: YHPhoneMessageView!
    var countryMessageView: YHCountryMessageView!
    var getCodeButton: UIButton!
    var wechatButton: UIButton!
    var appleButton: UIButton!
    var privacyView: YHLoginPrivacyView!
    var viewModel: YHLoginViewModel!
    let appleLoginViewModel = YHAppleLoginViewModel()
    var type: YHLoginType = .phone
    var token: String = ""
    var appleLoginParams: [String: Any] = [:]
    var country: Country = Country(name: "中国大陆", code: "86", index: "")
    
    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = YHLoginViewModel()
        setView()
        updateData(type)
    }
    
    func setView() {
        view.backgroundColor = .white
        bgImageView = {
            let imageView = UIImageView()
            imageView.image = UIImage(named: "login_phone_bg_image")
            imageView.isUserInteractionEnabled = true
            return imageView
        }()
        view.addSubview(bgImageView)
        bgImageView.snp.makeConstraints { make in
            make.left.right.top.equalTo(view)
            make.height.equalTo(300)
        }
        
        closeButton = {
            let button = UIButton(type: .custom)
            button.setImage(UIImage(named: "phone_login_close"), for: .normal)
            button.addTarget(self, action: #selector(close), for: .touchUpInside)
            return button
        }()
        view.addSubview(closeButton)
        closeButton.snp.makeConstraints { make in
            make.left.equalTo(13)
            make.top.equalTo(51)
            make.width.height.equalTo(30)
        }
        
        loginTitleLabel = {
            let label = UILabel()
            label.text = "欢迎来到银河港生活"
            label.font = UIFont.PFSC_M(ofSize: 30)
            label.textColor = UIColor.mainTextColor
            return label
        }()
        view.addSubview(loginTitleLabel)
        loginTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.top.equalTo(144)
            make.height.equalTo(42)
        }
        
        loginSubTitleLabel = {
            let label = UILabel()
            label.text = "手机号首次登录自动注册"
            label.font = UIFont.PFSC_R(ofSize: 15)
            label.textColor =  UIColor.mainTextColor50
            return label
        }()
        view.addSubview(loginSubTitleLabel)
        loginSubTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.top.equalTo(190)
            make.height.equalTo(20)
        }
        
        phoneMessageView = {
            let view = YHPhoneMessageView()
            view.phoneBlock = {[weak self] count in
                guard let self = self else { return }
                if count == 0 {
                    self.getCodeButton.backgroundColor =  UIColor.brandMainColor.withAlphaComponent(0.4)
                    self.getCodeButton.isEnabled = false
                } else {
                    self.getCodeButton.backgroundColor =  UIColor.brandMainColor
                    self.getCodeButton.isEnabled = true
                }
            }
            return view
        }()
        view.addSubview(phoneMessageView)
        phoneMessageView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.top.equalTo(356)
            make.height.equalTo(56)
        }
        
        countryMessageView = {
            let view = YHCountryMessageView()
            view.block = {[weak self] in
                guard let self = self else { return }
                let vc = YHSelectPhoneCountryViewController()
                vc.backLocationStringController = { (country) in
                    self.country = country
                    self.countryMessageView.messageButton.setTitle(country.name, for: .normal)
                    self.phoneMessageView.messageButton.text = "+\(country.code)"
                }
                UIViewController.current?.navigationController?.pushViewController(vc)
            }
            return view
        }()
        view.addSubview(countryMessageView)
        countryMessageView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.top.equalTo(300)
            make.height.equalTo(56)
        }
        
        getCodeButton = {
            let button = UIButton(type: .custom)
            button.backgroundColor =  UIColor.brandMainColor.withAlphaComponent(0.4)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
            button.contentHorizontalAlignment = .center
            button.setTitle("获取验证码", for: .normal)
            button.setTitleColor( UIColor(hex: 0xffffff), for: .normal)
            button.layer.cornerRadius = kCornerRadius3
            button.addTarget(self, action: #selector(getCode), for: .touchUpInside)
            button.isEnabled = false
            return button
        }()
        view.addSubview(getCodeButton)
        getCodeButton.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.top.equalTo(431)
            make.height.equalTo(48)
        }
        
        privacyView = {
            let view = YHLoginPrivacyView()
            return view
        }()
        view.addSubview(privacyView)
        privacyView.snp.makeConstraints { make in
            make.top.equalTo(503)
            make.left.equalTo(25)
            make.height.equalTo(20)
            make.width.equalTo(260)
        }
        
        if WXApi.isWXAppInstalled() {
            wechatButton = {
                let button = UIButton(type: .custom)
                button.setImage(UIImage(named: "login_wechat"), for: .normal)
                button.addTarget(self, action: #selector(wechatLogin), for: .touchUpInside)
                return button
            }()
            view.addSubview(wechatButton)
            wechatButton.snp.makeConstraints { make in
                make.right.equalTo(view.snp.centerX).offset(-22)
                make.bottom.equalTo(-58)
                make.height.width.equalTo(44)
            }
            
            appleButton = {
                let button = UIButton(type: .custom)
                button.setImage(UIImage(named: "login_apple"), for: .normal)
                button.addTarget(self, action: #selector(appleLogin), for: .touchUpInside)
                return button
            }()
            view.addSubview(appleButton)
            appleButton.snp.makeConstraints { make in
                make.left.equalTo(view.snp.centerX).offset(22)
                make.bottom.equalTo(-58)
                make.height.width.equalTo(44)
            }
        } else {
//            appleButton = {
//                let button = UIButton(type: .custom)
//                button.setImage(UIImage(named: "login_apple"), for: .normal)
//                button.addTarget(self, action: #selector(appleLogin), for: .touchUpInside)
//                return button
//            }()
//            view.addSubview(appleButton)
//            appleButton.snp.makeConstraints { make in
//                make.centerX.equalToSuperview()
//                make.bottom.equalTo(-58)
//                make.height.width.equalTo(44)
//            }
        }
    }
    
    @objc func close() {
        YHLoginManager.shared.loginSuccessActionBlock = nil
        IQKeyboardManager.shared.isEnabled = true
        dismiss(animated: true)
    }
    
    func updateData(_ type: YHLoginType) {
        switch type {
        case .normal: break
        case .phone: break
        case .wechat:
            loginTitleLabel.text = "手机号绑定"
            loginSubTitleLabel.text = "微信号首次登录需绑定手机号"
            appleButton.isHidden = true
            wechatButton.isHidden = true
            privacyView.isHidden = true
        case .apple:
            loginTitleLabel.text = "手机号绑定"
            loginSubTitleLabel.text = "Apple ID首次登录需绑定手机号"
            appleButton.isHidden = true
            wechatButton.isHidden = true
            privacyView.isHidden = true
        }
        
        if self.navigationController?.viewControllers.count == 1 {
            closeButton.isHidden = false
            gk_navigationBar.isHidden = true
        } else {
            closeButton.isHidden = true
            gk_navigationBar.isHidden = false
        }
    }
    
    @objc func getCode() {
        
        IQKeyboardManager.shared.resignFirstResponder()
        if type == .phone {
            let phoneNumer = phoneMessageView.phoneTextField.text ?? ""
            if self.country.code == "86" {
                guard phoneNumer.isMobile() == true else {
                    YHHUD.flash(message: "请输入正确的手机号")
                    return
                }
            }

            if privacyView.isAgree {
                YHHUD.show(.progress(message: ""))
                viewModel?.getLoginCode(phoneNumer, code: self.country.code, callBackBlock: {[weak self] success, error in
                    YHHUD.hide()
                    
                    guard let self = self else { return }
                    
                    if success == true {
                        let vc = YHCodeSueecssViewController()
                        vc.phoneNumber = self.phoneMessageView.phoneTextField.text
                        vc.country = self.country
                        vc.type = self.type
                        vc.token = self.token
                        self.navigationController?.pushViewController(vc)
                    } else {
                        var msg = error?.errorMsg ?? ""
                        if msg.isEmpty {
                            msg = String(error?.errorCode ?? 404)
                        }
                        YHHUD.flash(message: msg)
                    }
                })
            } else {
                let view = YHPrivacyAlertView(frame: view.bounds)
                view.urlBlock = { [weak self] (type, url) in
                    guard let self = self else { return }
                    let vc = YHWebViewViewController()
                    vc.url = url
                    if type == 0 {
                        vc.navTitle = "银河港生活隐私政策"
                    } else if type == 1 {
                        vc.navTitle = "银河港生活用户条款"
                    }
                    
                    self.navigationController?.pushViewController(vc)
                }
                view.agreeBlock = { [weak self] in
                    guard let self = self else { return }
                    self.privacyView.isAgree = true
                    self.getCode()
                }
                self.view.addSubview(view)
            }
        }
        if type == .wechat {
            let phoneNumer = phoneMessageView.phoneTextField.text ?? ""
            if self.country.code == "86" {
                guard phoneNumer.isMobile() == true else {
                    YHHUD.flash(message: "请输入正确的手机号")
                    return
                }
            }
            YHHUD.show(.progress(message: ""))
            viewModel?.getLoginCode(phoneNumer, code: self.country.code, callBackBlock: {[weak self] success, error in
                YHHUD.hide()
                
                guard let self = self else { return }
                
                if success == true {
                    let vc = YHCodeSueecssViewController()
                    vc.phoneNumber = self.phoneMessageView.phoneTextField.text
                    vc.country = self.country
                    vc.type = self.type
                    vc.token = self.token
                    self.navigationController?.pushViewController(vc)
                } else {
                    var msg = error?.errorMsg ?? ""
                    if msg.isEmpty {
                        msg = String(error?.errorCode ?? 404)
                    }
                    YHHUD.flash(message: msg)
                }
            })
        }
        if type == .apple {
            let phoneNumer = phoneMessageView.phoneTextField.text ?? ""
            if self.country.code == "86" {
                guard phoneNumer.isMobile() == true else {
                    YHHUD.flash(message: "请输入正确的手机号")
                    return
                }
            }
            YHHUD.show(.progress(message: ""))
            viewModel?.getLoginCode(phoneNumer, code: self.country.code, callBackBlock: {[weak self] success, error in
                YHHUD.hide()
                
                guard let self = self else { return }
                
                if success == true {
                    let vc = YHCodeSueecssViewController()
                    vc.phoneNumber = self.phoneMessageView.phoneTextField.text
                    vc.country = self.country
                    vc.type = self.type
                    vc.token = self.token
                    vc.appleLoginParams = self.appleLoginParams
                    self.navigationController?.pushViewController(vc)
                } else {
                    var msg = error?.errorMsg ?? ""
                    if msg.isEmpty {
                        msg = String(error?.errorCode ?? 404)
                    }
                    YHHUD.flash(message: msg)
                }
            })
        }
    }
    
    @objc func wechatLogin() {
        if privacyView.isAgree {
            let login = YHShareManager.shared
            login.sendLogin()
            login.success = { [weak self] unionId in
                guard let self = self else { return }
                self.viewModel.wxlogin(unionId: unionId, phone: "", code: "", countryCode: self.country.code) {[weak self] success, error in
                    guard let self = self else { return }
                    if success {
                        YHLoginManager.shared.loginSuccessActionBlock?()
                        YHHUD.flash(message: "登录成功")
                        self.dismiss(animated: true)
                        TXCommonHandler.sharedInstance().cancelLoginVC(animated: true)
                        self.navigationController?.popToRootViewController(animated: true)
                    } else {
                        if error?.errorCode == 30001 {
                            // 第一次微信登录跳转逻辑
                            let vc = YHOtherLoginViewController()
                            vc.type = .wechat
                            vc.token = unionId
                            navigationController?.pushViewController(vc)
                        } else {
                            YHHUD.flash(message: error?.errorMsg ?? "")
                        }
                    }
                }
            }
        } else {
            let view = YHPrivacyAlertView(frame: view.bounds)
            view.urlBlock = { [weak self] (type, url) in
                guard let self = self else { return }
                let vc = YHWebViewViewController()
                vc.url = url
                if type == 0 {
                    vc.navTitle = "银河港生活隐私政策"
                } else if type == 1 {
                    vc.navTitle = "银河港生活用户条款"
                }
                
                self.navigationController?.pushViewController(vc)
            }
            view.agreeBlock = { [weak self] in
                guard let self = self else { return }
                self.privacyView.isAgree = true
                self.wechatLogin()
            }
            self.view.addSubview(view)
        }
    }
    
    @objc func appleLogin() {
        if privacyView.isAgree {
            YHAppleLoginManager.shared.success = {
                dict in
                
                YHHUD.flash(message: "登录中...")
                self.appleLoginViewModel.appleLogin(params: dict) {
                    success, error in
                    
                    YHHUD.hide()
                    if success {
                        YHLoginManager.shared.loginSuccessActionBlock?()
                        YHHUD.flash(message: "登录成功")
                        self.dismiss(animated: true)
                        TXCommonHandler.sharedInstance().cancelLoginVC(animated: true)
                        self.navigationController?.popToRootViewController(animated: true)
                        return
                    }
                    
                    if let err = error {
                        var msg = err.errorMsg
                        if msg.isEmpty {
                            msg = "登录失败"
                        }
                        YHHUD.flash(message: msg)
                        
                        if err.errorCode == 30001 {
                           // 首次登录，没有传电话号码和验证码返回错误码：30001
                           // 进入手机绑定页面
                           let bindVC = YHOtherLoginViewController()
                           bindVC.type = .apple
                           bindVC.appleLoginParams = dict
                           UIViewController.current?.navigationController?.pushViewController(bindVC)
                           return
                        }
                    }
                }
            }
            YHAppleLoginManager.shared.appleLogin()
        } else {
            let view = YHPrivacyAlertView(frame: view.bounds)
            view.urlBlock = { [weak self] (type, url) in
                guard let self = self else { return }
                let vc = YHWebViewViewController()
                vc.url = url
                if type == 0 {
                    vc.navTitle = "银河港生活隐私政策"
                } else if type == 1 {
                    vc.navTitle = "银河港生活用户条款"
                }
                
                self.navigationController?.pushViewController(vc)
            }
            view.agreeBlock = { [weak self] in
                guard let self = self else { return }
                self.privacyView.isAgree = true
                self.appleLogin()
            }
            self.view.addSubview(view)
        }

    }
}
