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

import UIKit

class YHCodeSueecssViewController: YHBaseViewController {

    var time = 60
    
    var bgImageView: UIImageView!
    var closeButton: UIButton!
    var loginTitleLabel: UILabel!
    var loginSubTitleLabel: UILabel!
    var getCodeButton: UIButton!
    var smscodeView: YHSmsCodeInputView!
    var phoneNumber: String?
    var type: YHLoginType = .phone
    var viewModel: YHLoginViewModel?
    let appleLoginViewModel = YHAppleLoginViewModel()
    var token: String = ""
    var country: Country = Country(name: "中国大陆", code: "86", index: "")
    var appleLoginParams: [String: Any] = [:]
    
    private var isRequestFlag: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = YHLoginViewModel()
        setView()
        // Do any additional setup after loading the view.
        startTime()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        isRequestFlag = false
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        smscodeView.textField.becomeFirstResponder()
    }
    
    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)
        }
        
        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)
        }
        smscodeView = {
            let view = YHSmsCodeInputView(config: YHSmsCodeViewConfig())
            view.complete = { [weak self] code in
                guard let self = self else { return }
                
                if let phone = self.phoneNumber {
                    
                    // 登录接口需要加一个deviceToken参数
                    YHHUD.show(.progress(message: "登录中..."))
                    if phone.contains("15818743775") {
                        // 审核账号
                        YHHUD.hide()
                        self.requestLogin(phone: phone, code: code)
                        return
                    }
                    
                    if YHLoginManager.shared.deviceTokenModel.registerId.isEmpty {
                        JPUSHService.registrationIDCompletionHandler {
                            _, registrationID in
                            YHHUD.hide()
                            YHLoginManager.shared.deviceTokenModel.registerId = registrationID ?? ""
                            self.requestLogin(phone: phone, code: code)
                        }
                    } else {
                        YHHUD.hide()
                        self.requestLogin(phone: phone, code: code)
                    }
                    
                } else {
                    printLog("errror :  电话号码为空")
                }
            }
            return view
        }()
        view.addSubview(smscodeView)
        smscodeView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(288)
            make.height.equalTo(55)
        }
        
        getCodeButton = {
            let button = UIButton(type: .custom)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
            button.contentHorizontalAlignment = .center
            button.setTitle("重新获取验证码", for: .normal)
            button.setTitleColor( UIColor(hex: 0xffffff), for: .normal)
            button.backgroundColor = UIColor.brandMainColor16
            button.addTarget(self, action: #selector(startClicked), for: .touchUpInside)
            button.layer.cornerRadius = 3
            button.isEnabled = false
            return button
        }()
        view.addSubview(getCodeButton)
        getCodeButton.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.top.equalTo(373)
            make.height.equalTo(48)
            make.right.equalTo(-20)
        }
        // 测试
        
    }
    
    func requestLogin(phone: String, code: String) {
        
        if isRequestFlag {
#if DEBUG
            YHHUD.flash(message: "请求已发送")
#endif
            return
        }
        isRequestFlag = true
        
        if type == .phone {
            YHHUD.show(.progress(message: "登录中..."))
            self.viewModel?.login(phone: phone, code: code, countryCode: self.country.code, callBackBlock: {[weak self] success, error in
                YHHUD.hide()
                self?.isRequestFlag = false
                guard let self = self else { return }
                if success == false {
                    YHHUD.flash(message: error?.errorMsg ?? "")
                } else {
                    YHLoginManager.shared.loginSuccessActionBlock?()
                    YHHUD.flash(message: "登录成功")
                    
                    // 20240927版本 登录时 不需要 特殊处理注册用户 by Cecilia曾欢宝
//                    if YHLoginManager.shared.userModel?.is_first_login == 1 {
//                        let vc = YHUserInfoSettingViewController()
//                        vc.modalPresentationStyle = .fullScreen
//                        self.navigationController?.pushViewController(vc)
//                    } else {
//                        TXCommonHandler.sharedInstance().cancelLoginVC(animated: true)
//                        self.dismiss(animated: true)
//                    }
                    
                    TXCommonHandler.sharedInstance().cancelLoginVC(animated: true)
                    self.dismiss(animated: true)
                }
            })
        }
        
        if type == .wechat {
            self.viewModel?.wxlogin(unionId: self.token, phone: phone, code: code, countryCode: self.country.code, callBackBlock: {[weak self] success, error in
                self?.isRequestFlag = false
                guard let self = self else { return }
                if success == false {
                    YHHUD.flash(message: error?.errorMsg ?? "")
                } else {
                    YHLoginManager.shared.loginSuccessActionBlock?()
                    YHHUD.flash(message: "登录成功")
                    TXCommonHandler.sharedInstance().cancelLoginVC(animated: true)
                    self.dismiss(animated: true)
                }
            })
        }
        
        if type == .apple {
            // 苹果登录逻辑
            var params = self.appleLoginParams
            params["sms_code"] = code
            params["mobile"] = XXTEA.encryptString(toBase64String: phone, stringKey: "galaxyapps") ?? phone
            params["mobile_area_code"] = "+" + self.country.code
            printLog("Apple login parmas: \(params)")
            YHHUD.show(.progress(message: ""))
            self.appleLoginViewModel.appleLogin(params: params) {[weak self]  success, error in
                YHHUD.hide()
                self?.isRequestFlag = false
                if success == false {
                    YHHUD.flash(message: error?.errorMsg ?? "")
                } else {
                    YHLoginManager.shared.loginSuccessActionBlock?()
                    YHHUD.flash(message: "登录成功")
                    
                    TXCommonHandler.sharedInstance().cancelLoginVC(animated: true)
                    self?.dismiss(animated: true)
                }
            }
        }
    }
    
    func startTime() {
        let sourceTimer = DispatchSource.makeTimerSource()
        sourceTimer.schedule(deadline: DispatchTime.now(), repeating: DispatchTimeInterval.milliseconds(1000), leeway: DispatchTimeInterval.milliseconds(0))
        sourceTimer.setEventHandler {
            if self.time != 0 {
                self.time -= 1
                DispatchQueue.main.async {
                    self.getCodeButton.setTitle(String.localizedStringWithFormat("重新获取（%ds）", self.time), for: .normal)
                    self.getCodeButton.isEnabled = false
                    self.getCodeButton.backgroundColor = UIColor.brandMainColor16
                }
            } else if self.time <= 0 {
                sourceTimer.cancel()
                DispatchQueue.main.async {
                    self.time = 60
                    self.getCodeButton.setTitle("重新获取", for: .normal)
                    self.getCodeButton.isEnabled = true
                    self.getCodeButton.backgroundColor = UIColor.brandMainColor
                }
            }
        }
        // 启动定时器
        sourceTimer.resume()
    }
    
    @objc func startClicked() {
        YHHUD.show(.progress(message: ""))
        viewModel?.getLoginCode(phoneNumber ?? "", code: self.country.code, callBackBlock: {[weak self] success, error in
            YHHUD.hide()
            
            guard let self = self else { return }
            
            if success == true {
//                YHHUD.flash(message: "验证码已下发,请注意查收")
                self.startTime()
            } else {
                YHHUD.flash(message: error?.errorMsg ?? "")
            }
        })
    }
    
}
