//
//  MineGetCodeTool.swift
//  VattiCSS
//
//  Created by Jan on 2023/10/17.
//

import UIKit

class MineGetCodeTool: NSObject {
    // 单例
    static let curDefaultTool: MineGetCodeTool = MineGetCodeTool()
    class func defaultTool()-> MineGetCodeTool{
        return curDefaultTool
    }
    
    //  验证码倒计时 回调
    var codeBtnCall:((Int)->Void)?
    // 倒计时次数
    var timerNumber = 0
    var codeTimer:Timer?
    
    //外面需要多少秒读数
    public var count = 0
    
     //  验证码功能
     func setupCodeBtnCall(theCall:@escaping ((Int)->Void)) {
         self.codeBtnCall = theCall
     }
     
     func timerbegin() {
         if timerNumber > 0 { return }
         timerNumber = self.count
         codeTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.codeTimerAction), userInfo: nil, repeats: true)
     }
     
    @objc func codeTimerAction() {
         self.timerNumber -= 1
         self.codeBtnCall?(self.timerNumber)
         if self.timerNumber <= 0 {
             if let theT = codeTimer {
                 theT.invalidate()
             }
         }
     }
    
    // 获取验证码
    func starRequestVerificationCode(theParam: [String:Any],timerCount:Int=60,path:String="app/v2/AppUtil/getVerificationCode") {
        
        self.count = timerCount
        
        SVProgressHUD.show()
        let cNet = TWOCNetwork(url: path,andParam: theParam)
        cNet.successCall = { [weak self] (result) in
            SVProgressHUD.dismiss()
            guard let weakSelf = self else { return }
            weakSelf.timerbegin()
        }
        cNet.failCall = {(errorTag,errorStr) in
            SVProgressHUD.dismiss()
            hud_error(errorStr)
        }
        cNet.postRequest()
        
        
    }
    
}

