//
//  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 getCodeLabel: UILabel!
    var getCodeButton: UIButton!
    var smscodeView: YHSmsCodeInputView!
    var phoneNumber: String?
    var viewModel: YHLoginViewModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = YHLoginViewModel()
        gk_navBackgroundColor = .clear
        gk_navShadowColor = .clear
        gk_navigationBar.isHidden = true
        setView()
        // Do any additional setup after loading the view.
        startTime()
    }
    
    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: "login_back"), 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: 28)
            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(203)
            make.height.equalTo(25)
        }
        
        loginSubTitleLabel = {
            let label = UILabel()
            label.text = "已发送至 \(phoneNumber ?? "")"
            label.font = UIFont.PFSC_R(ofSize: 13)
            label.textColor =  UIColor.placeHolderColor
            return label
        }()
        view.addSubview(loginSubTitleLabel)
        loginSubTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.top.equalTo(233)
            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 {
                    self.viewModel?.login(phone : phone, code: code, callBackBlock: {[weak self] success,error in
                        guard let self = self else { return }
                        if success == false {
                            YHHUD.flash(message: error?.errorMsg ?? "")
                        } else {
                            YHHUD.flash(message: "登录成功")
                            self.dismiss(animated: true)
                        }
                    })
                } 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)
        }
        
        getCodeLabel = {
            let button = UILabel()
            button.font = UIFont.PFSC_M(ofSize: 12)
            button.text = "重新发送（58s）"
            button.textColor = UIColor.placeHolderColor
            button.textAlignment = .center
            button.isHidden = false
            button.layer.cornerRadius = 4
            button.layer.borderWidth = 1
            button.layer.borderColor = UIColor(hex: 0xebeef4).cgColor
            return button
        }()
        view.addSubview(getCodeLabel)
        getCodeLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(382)
            make.height.equalTo(28)
            make.width.equalTo(120)
        }
        
        getCodeButton = {
            let button = UIButton(type: .custom)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 12)
            button.contentHorizontalAlignment = .center
            button.setTitle("获取验证码", for: .normal)
            button.setTitleColor( UIColor.mainTextColor, for: .normal)
            button.addTarget(self, action: #selector(startClicked), for: .touchUpInside)
            button.isHidden = true
            button.layer.cornerRadius = 4
            button.layer.borderWidth = 1
            button.layer.borderColor = UIColor(hex: 0xebeef4).cgColor
            return button
        }()
        view.addSubview(getCodeButton)
        getCodeButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(382)
            make.height.equalTo(28)
            make.width.equalTo(91)
        }
        
        //测试
        
    }
    
    func startTime() {
        getCodeLabel.isHidden = false
        getCodeButton.isHidden = true
        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.getCodeLabel?.text = String.localizedStringWithFormat("重新获取（%ds）",self.time)
                }
            } else if self.time <= 0 {
                sourceTimer.cancel()
                DispatchQueue.main.async {
//                    self.getCodeLabel?.text = "获取验证码"
                    self.time = 60
                    self.getCodeLabel.isHidden = true
                    self.getCodeButton.isHidden = false
                }
            }
        }
        // 启动定时器
        sourceTimer.resume()
    }
    
    
    @objc func startClicked() {
        viewModel?.getLoginCode(phoneNumber ?? "", callBackBlock: {[weak self] success,error in
            guard let self = self else { return }
            
            if success == true {
//                YHHUD.flash(message: "验证码已下发,请注意查收")
                self.startTime()
            } else {
                YHHUD.flash(message: error?.errorMsg ?? "")
            }
        })
    }
    
    @objc func close() {
        self.navigationController?.popViewController()
    }
}
