//
//  PQBandingPhoneController.swift
//  PQSpeed
//
//  Created by SanW on 2020/8/11.
//  Copyright © 2020 BytesFlow. All rights reserved.
//

import UIKit
import BFFramework

class PQBandingPhoneController: PQPhoneLoginController {
    var isCodeSend: Bool = false // 是否已经发送过验证码
    var timer: Timer?
    var totalTime: Int = 59 // 总时长
    var codeId: String? // 验证码codeId

    lazy var sendCodeBtn: UIButton = {
        let sendCodeBtn = UIButton(type: .custom)
        sendCodeBtn.addTarget(self, action: #selector(sendMsg), for: .touchUpInside)
        sendCodeBtn.setTitleColor(UIColor.hexColor(hexadecimal: "#666666"), for: .normal)
        sendCodeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        sendCodeBtn.frame = CGRect(x: cScreenWidth - cDefaultMargin * 14, y: 253, width: cDefaultMargin * 10, height: cDefaultMargin * 4)
        sendCodeBtn.contentHorizontalAlignment = .right
        sendCodeBtn.isHidden = true
        sendCodeBtn.isUserInteractionEnabled = false
        return sendCodeBtn
    }()

    lazy var codeRightView: UIView = {
        let codeRightView = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 32))
        let codeDeleteBtn = UIButton(type: .custom)
        codeDeleteBtn.setImage(UIImage(named: "icon_x_cancel"), for: .normal)
        codeDeleteBtn.frame = CGRect(x: 0, y: 0, width: 28, height: 28)
        codeDeleteBtn.addTarget(self, action: #selector(clearCodeText), for: .touchUpInside)
        codeRightView.addSubview(codeDeleteBtn)
        return codeRightView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        titleLab.text = "绑定手机号"
        phoneTextField.textAlignment = .left
        passTextField.textAlignment = .left
        let placeholder: NSMutableAttributedString = NSMutableAttributedString(string: "请输入验证码")
        placeholder.addAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16, weight: .regular), NSAttributedString.Key.foregroundColor: UIColor.hexColor(hexadecimal: "#A3A3A3")], range: NSRange(location: 0, length: placeholder.length))
        passTextField.attributedPlaceholder = placeholder
        phoneLoginBtn.setTitle("获取验证码", for: .normal)

        phoneTextField.rightViewMode = .whileEditing
        let phoneRightView = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 32))
        let phoneDeleteBtn = UIButton(type: .custom)
        phoneDeleteBtn.setImage(UIImage(named: "icon_x_cancel"), for: .normal)
        phoneDeleteBtn.frame = CGRect(x: 0, y: 0, width: 28, height: 28)
        phoneDeleteBtn.addTarget(self, action: #selector(clearPhoneText), for: .touchUpInside)
        phoneRightView.addSubview(phoneDeleteBtn)
        phoneTextField.rightView = phoneRightView

        passTextField.rightViewMode = .whileEditing
        passTextField.keyboardType = .numberPad
        passTextField.isSecureTextEntry = false
        passTextField.rightView = codeRightView
        view.addSubview(sendCodeBtn)
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        stopTimer()
    }

    override func valueChanged(textField: UITextField) {
        if textField == phoneTextField, textField.text?.count ?? 0 > 11 {
            textField.text = String(textField.text?.prefix(11) ?? "")
        }
        if textField == passTextField, textField.text?.count ?? 0 > 4 {
            textField.text = String(textField.text?.prefix(4) ?? "")
        }
        isEnabled()
    }

    override func isEnabled() {
        let isEnabled = !isCodeSend ? phoneTextField.text?.count ?? 0 == 11 : (phoneTextField.text?.count ?? 0 == 11 && passTextField.text?.count ?? 0 == 4)
        if isEnabled {
            phoneLoginBtn.backgroundColor = UIColor.hexColor(hexadecimal: "#07C160")
        } else {
            phoneLoginBtn.backgroundColor = UIColor.hexColor(hexadecimal: "#333333")
        }
    }

    @objc func clearPhoneText() {
        phoneTextField.text = ""
    }

    @objc func clearCodeText() {
        passTextField.text = ""
    }

    /// 发送验证码
    @objc func sendMsg() {
        totalTime = 60
        if phoneTextField.text?.count ?? 0 <= 0 {
            cShowHUB(superView: nil, msg: "请输入手机号")
            return
        }
        if phoneTextField.text?.count ?? 0 != 11 {
            cShowHUB(superView: nil, msg: "请输入正确的手机号")
            return
        }
        codeId = nil
        isCodeSend = true
        phoneLoginBtn.setTitle("完成", for: .normal)
        phoneLoginBtn.backgroundColor = UIColor.hexColor(hexadecimal: "#333333")
        PQMineViewModel.sendIndetifyCode(phoneNumber: phoneTextField.text ?? "") { [weak self] isSuccess, msg, codeId in
            cShowHUB(superView: nil, msg: msg)
            if isSuccess {
                self?.codeId = codeId
                self?.startTimer()
                self?.isEnabled()
            } else {
                self?.isCodeSend = false
                self?.phoneLoginBtn.setTitle("获取验证码", for: .normal)
                self?.phoneLoginBtn.backgroundColor = UIColor.hexColor(hexadecimal: "#07C160")
            }
        }
    }

    // 定时操作
    @objc func updataSecond() {
        totalTime -= 1
        if totalTime <= 0 {
            totalTime = 60
            sendCodeBtn.setTitle("重新发送", for: .normal)
            sendCodeBtn.isUserInteractionEnabled = true
            stopTimer()
            codeRightView.frame = CGRect(x: 0, y: 0, width: cDefaultMargin * 10, height: 32)
            passTextField.rightView = codeRightView
        } else {
            let title = totalTime < 10 ? "  \(totalTime) " : "  \(totalTime)"
            sendCodeBtn.setTitle(title, for: .normal)
        }
    }

    // 开始计时
    func startTimer() {
        if timer == nil {
            codeRightView.frame = CGRect(x: 0, y: 0, width: 50, height: 32)
            passTextField.rightView = codeRightView
            sendCodeBtn.isHidden = false
            sendCodeBtn.isUserInteractionEnabled = false
            timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updataSecond), userInfo: nil, repeats: true)
            timer!.fire()
        }
    }

    // 停止计时
    func stopTimer() {
        if timer != nil {
            timer!.invalidate() // 销毁timer
            timer = nil
        }
    }

    override func loginAction() {
        if phoneTextField.text?.count ?? 0 <= 0 {
            cShowHUB(superView: nil, msg: "请输入手机号")
            return
        }
        if phoneTextField.text?.count ?? 0 != 11 {
            cShowHUB(superView: nil, msg: "请输入正确的手机号")
            return
        }
        if !isCodeSend {
            isCodeSend = true
            sendMsg()
            phoneLoginBtn.setTitle("完成", for: .normal)
            return
        }
        if passTextField.text?.count ?? 0 <= 0 {
            cShowHUB(superView: nil, msg: "请输入验证码")
            return
        }
        if passTextField.text?.count ?? 0 != 4 {
            cShowHUB(superView: nil, msg: "请输入正确的验证码")
            return
        }
        PQMineViewModel.checkIndetifyCode(phoneNumber: phoneTextField.text ?? "", codeId: codeId ?? "", indetifyCode: passTextField.text ?? "") { [weak self] isSuccess, msg in
            saveUserDefaults(key: cUpdatePhone, value: self?.phoneTextField.text ?? "")
            BFLoginUserInfo.shared.phoneNumber = self?.phoneTextField.text ?? ""
            cShowHUB(superView: nil, msg: "手机号绑定成功")
            self?.navigationController?.viewControllers = [ (self?.navigationController?.viewControllers.first)!]
            postNotification(name: cBandingPhoneSuccessKey)
//            if isSuccess {
//                PQMineViewModel.updatePhone(phoneNumber: self?.phoneTextField.text ?? "") { isSuccess, msg in
//                    if isSuccess {
//                        saveUserDefaults(key: cUpdatePhone, value: self?.phoneTextField.text ?? "")
//                        BFLoginUserInfo.shared.phoneNumber = self?.phoneTextField.text ?? ""
//                        cShowHUB(superView: nil, msg: "手机号绑定成功")
//                        self?.navigationController?.popToRootViewController(animated: true)
//                        postNotification(name: cBandingPhoneSuccessKey)
//                    } else {
//                        cShowHUB(superView: nil, msg: msg)
//                    }
//                }
//            } else {
//                cShowHUB(superView: nil, msg: msg)
//            }
        }
    }
}
