//
//  LoginController.swift
//  OrderScheduling
//
//  Created by 中道 on 2023/8/4.
//

import Foundation
import SnapKit
import RxRelay
import RxCocoa
import RxSwift
import DDTimerKit_Private
import DDProgressHUDKit_Private
import DDAutoUIKit_Private
import DDControlsKit_Private

class LoginController : DDViewController {
    private let disposeBag = DisposeBag()
    private let loginView = LoginView.init()
    private let agreeSub = ReplaySubject<Bool>.create(bufferSize: 1)

    override func viewDidLoad() {
        super.viewDidLoad()
        dd_navigationBarBackgroundColor = .clear
        navigationItem.leftBarButtonItems = nil
        addSubviews()
        addActions()
    }
}
extension LoginController {
    func addSubviews() {
        view.addSubview(loginView)
        loginView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        loginView.backgroundImageView.image = UIImage(named: "login_backgroundImage")
        loginView.inputContentView.backgroundColor = UIColor.white
        loginView.serviceProviderView.titleLabel.text = "服务商编号"
        loginView.serviceProviderView.textfield.attributedPlaceholder = NSAttributedString(string: "请输入服务商编号",attributes: [.foregroundColor: UIColor.hex("203152").alpha(0.2),.font:UIFont.regularFont(auto(14))])
        loginView.phoneView.titleLabel.text = "用户手机号"
        loginView.phoneView.textfield.attributedPlaceholder = NSAttributedString(string: "请输入手机号",attributes: [.foregroundColor: UIColor.hex("203152").alpha(0.2),.font:UIFont.regularFont(auto(14))])
        loginView.codeView.titleLabel.text = "验证码"
        loginView.codeView.textfield.attributedPlaceholder = NSAttributedString(string: "请输入验证码",attributes: [.foregroundColor: UIColor.hex("203152").alpha(0.2),.font:UIFont.regularFont(auto(14))])
        loginView.codeView.codeButton.layer.borderColor = UIColor.hex("3364B7").alpha(0.8).cgColor
        loginView.codeView.codeButton.layer.borderWidth = 1
        loginView.codeView.codeButton.setTitle("获取验证码", for: .normal)
        loginView.codeView.codeButton.setTitleColor(.hex("3364B7").alpha(0.8), for: .normal)
        loginView.codeView.codeButton.titleLabel?.font = .regularFont(auto(13))
        loginView.agreeButton.setImage(UIImage(named: "login_agree_unselected"), for: .normal)
        loginView.agreeButton.setImage(UIImage(named: "login_agree_selected"), for: .selected)
        let privacyText = NSAttributedString.init(string: "已阅读并同意",attributes: [.foregroundColor:UIColor.hex("203152"),.font:UIFont.regularFont(auto(14))]).dd_mutable()
        let privacyText_appendUser = NSAttributedString.init(string: "《用户协议》",attributes: [.foregroundColor:UIColor.hex("354D93"),.font:UIFont.regularFont(auto(14))]).dd_mutable()
        privacyText_appendUser.addAttribute(.link, value: login_attach_userAgreement_key, range: NSRange(location: 0, length: privacyText_appendUser.length))
        let privacyText_appendPrivacy = NSAttributedString.init(string: "《隐私协议》",attributes: [.foregroundColor:UIColor.hex("354D93"),.font:UIFont.regularFont(auto(14))]).dd_mutable()
        privacyText_appendPrivacy.addAttribute(.link, value: login_attach_privacy_key, range: NSRange(location: 0, length: privacyText_appendPrivacy.length))
        loginView.agreeTextView.attributedText = privacyText.dd_append(privacyText_appendUser).dd_append(privacyText_appendPrivacy)
        loginView.agreeTextView.textContainerInset = .zero
        loginView.agreeTextView.isEditable = false
        loginView.agreeTextView.delegate = self
        
        loginView.loginButton.backgroundColor = .hex("1C6CCE").alpha(0.4)
        loginView.loginButton.setTitle("登录", for: .normal)
    }
}
extension LoginController {
    func addActions() {
       loginView.codeView.codeButton.rx.tap
            .observe(on: MainScheduler.instance)
            .filter({[weak self] _ in
                if self?.loginView.phoneView.textfield.text?.isEmpty == true {
                    self?.view.dd_makeToast(loginInputPhone)
                }
                return self?.loginView.phoneView.textfield.text?.isEmpty == false
            })
            .observe(on: MainScheduler.instance)
            .do(onNext: {[weak self] _ in
                self?.codeButtonBinder.onNext(false)
                self?.view.dd_showHUD()
            })
            .flatMapLatest({[weak self] _ in
                return RQ.loginCode(parameters: LoginCodeParameters(phone: self?.loginView.phoneView.textfield.text ?? ""))
            })
            .observe(on: MainScheduler.instance)
            .do(onNext: {[weak self] _ in
                self?.view.dd_hideHUD()
            })
            .flatMapLatest {[weak self] _ in
                return self?.codeButtonTimer() ?? Observable.just(0)
            }
            .observe(on: MainScheduler.instance)
            .do(onNext: {[weak self] duration in
                if duration == 0 {
                    self?.codeButtonBinder.onNext(true)
                }
            })
            .observe(on: MainScheduler.instance)
            .flatMapLatest {[weak self] duration in
                return self?.codeButtonStateChange(duration: duration) ?? Observable.just(nil)
            }
            .subscribe(onNext: { _ in
            })
            .disposed(by: disposeBag)
        
        loginView.agreeButton.rx.tap
            .asDriver()
            .drive(onNext: {[weak self] _ in
                if let isSelected = self?.loginView.agreeButton.isSelected {
                    self?.agreeButtonBinder.onNext(!isSelected)
                    self?.agreeSub.onNext(!isSelected)
                }
            })
            .disposed(by: disposeBag)
        
        Observable.combineLatest(loginView.serviceProviderView.textfield.rx.text, loginView.phoneView.textfield.rx.text, loginView.codeView.textfield.rx.text,agreeSub)
            .asDriver(onErrorJustReturn: ("","","",false))
            .drive(onNext: {[weak self] (serviceProvider,phone,code,isAgree) in
                if serviceProvider?.isEmpty == false && phone?.isEmpty == false && code?.isEmpty == false && isAgree == true {
                    self?.loginView.loginButton.isEnabled = true
                    self?.loginView.loginButton.backgroundColor = .hex("1C6CCE").alpha(1)
                }else{
                    self?.loginView.loginButton.isEnabled = false
                    self?.loginView.loginButton.backgroundColor = .hex("1C6CCE").alpha(0.4)
                }
            })
            .disposed(by: disposeBag)
        
        loginView.loginButton.rx.tap
            .observe(on: MainScheduler.instance)
            .do(onNext: {[weak self] _ in
                self?.view.dd_showHUD()
            })
            .map({[weak self] _ in
                let phone = self?.loginView.phoneView.textfield.text ?? ""
                let code = self?.loginView.codeView.textfield.text ?? ""
                let clientType = "rescueApp"
                let supplierLoginCode = self?.loginView.serviceProviderView.textfield.text ?? ""

                let str = "{\"phone\":\"\(phone)\",\"code\":\"\(code)\",\"clientType\":\"\(clientType)\",\"supplierLoginCode\":\"\(supplierLoginCode)\"}"
                return str
            })
            .flatMapLatest({ app_login_json in
                return RQ.login(parameters: LoginParameters(app_login_json: app_login_json, client_id: true))
            })
            .observe(on: MainScheduler.instance)
            .do(onNext: {[weak self] _ in
                self?.view.dd_hideHUD()
            })
            .subscribe(onNext: { responseModel in
                if responseModel?.success == true {
                    if let token = responseModel?.data?.accessToken.tokenValue {
                        USER.setToken(token: token)
                    }
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: Notification_loginSuccessToRescueController), object: nil)
                }else{
                }
            })
            .disposed(by: disposeBag)
    }
}

extension LoginController {
    var codeButtonBinder : Binder<Bool> {
        return Binder(loginView.codeView.codeButton) { codeButton, isEnable in
            codeButton.isEnabled = isEnable
        }
    }
    var agreeButtonBinder : Binder<Bool> {
        return Binder(loginView.agreeButton) { agreeButton, isSelected in
            agreeButton.isSelected = isSelected
        }
    }
    
    func codeButtonIsEnable(isEnable:Bool) -> Observable<Bool> {
        return Observable.create {[weak self] ob in
            self?.loginView.codeView.codeButton.isEnabled = isEnable
            ob.onNext(isEnable)
            ob.onCompleted()
            return Disposables.create()
        }
    }
    func codeButtonStateChange(duration:Int) -> Observable<Any?>{
        return Observable.create {[weak self] ob in
            if duration == 0 {
                self?.loginView.codeView.codeButton.layer.borderColor = UIColor.hex("3364B7").alpha(0.8).cgColor
                self?.loginView.codeView.codeButton.setTitle("获取验证码", for: .normal)
                self?.loginView.codeView.codeButton.setTitleColor(.hex("3364B7").alpha(0.8), for: .normal)
            }else{
                self?.loginView.codeView.codeButton.setTitle("\(duration)s重新获取", for: .normal)
                self?.loginView.codeView.codeButton.setTitleColor(.hex("939BAB").alpha(0.8), for: .normal)
                self?.loginView.codeView.codeButton.layer.borderColor = UIColor.hex("939BAB").alpha(0.8).cgColor
            }
            ob.onNext(nil)
            ob.onCompleted()
            return Disposables.create()
        }
    }
    
    func codeButtonTimer() -> Observable<Int> {
        return Observable.create { ob in
            var duration = 60
            
            DDTimerManager.dd_share().dd_addTimer(withName: login_code_timer_key, timeInterval: 1, repeatCount: 0, delay: 0) { (manager,obj,_) in
                duration-=1
                ob.onNext(duration)
                if duration == 0 {
                    ob.onCompleted()
                }
            }
            
            return Disposables.create {
                DDTimerManager.dd_share().dd_removeTimerNamed(login_code_timer_key)
            }
        }
    }
}

extension LoginController : UITextViewDelegate {
    public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if URL.absoluteString == login_attach_userAgreement_key {
            let vc = WebViewController.init(title: "用户协议",url: "https://backend.hichefu.com/agreement")
            navigationController?.pushViewController(vc, animated: true)
        }
        if URL.absoluteString == login_attach_privacy_key {
            let vc = WebViewController.init(title: "隐私协议",url: "https://backend.hichefu.com/agreement")
            navigationController?.pushViewController(vc, animated: true)
        }
        return false
    }
}

class LoginView : DDView {
    public let backgroundImageView : DDImageView
    public let inputContentView : DDView
    public let serviceProviderView : LoginInputView
    public let phoneView : LoginInputView
    public let codeView : LoginInputView
    public let agreeButton : DDButton
    public let agreeTextView : DDTextView
    public let loginButton : DDButton
    override init(frame: CGRect) {
        backgroundImageView = DDImageView.init()
        inputContentView = DDView.init()
        serviceProviderView = LoginInputView.init()
        phoneView = LoginInputView.init()
        codeView = LoginInputView.init()
        agreeButton = DDButton.init()
        agreeTextView = DDTextView.init()
        loginButton = DDButton.dd_initCustom()
        super.init(frame: frame)
        
        addSubview(backgroundImageView)
        inputContentView.layer.shadowColor = UIColor.black.alpha(0.3).cgColor
        inputContentView.layer.shadowRadius = 5
        inputContentView.layer.shadowOffset = CGSize(width: 0, height: 0)
        inputContentView.layer.shadowOpacity = 1
        addSubview(inputContentView)
        inputContentView.addSubview(serviceProviderView)
        phoneView.textfield.keyboardType = .numberPad
        inputContentView.addSubview(phoneView)
        codeView.textfield.keyboardType = .numberPad
        inputContentView.addSubview(codeView)
        inputContentView.addSubview(agreeButton)
        inputContentView.addSubview(agreeTextView)
        addSubview(loginButton)
        
        backgroundImageView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(auto(423))
        }
        
        inputContentView.layer.cornerRadius = auto(10)
        inputContentView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(auto(30))
            make.height.equalTo(auto(280))
            make.width.equalTo(auto(340))
        }
        
        serviceProviderView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(auto(75))
        }
        
        phoneView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(serviceProviderView.snp.bottom)
            make.height.equalTo(serviceProviderView)
        }
        
        codeView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(phoneView.snp.bottom)
            make.height.equalTo(serviceProviderView)
        }
        
        agreeButton.snp.makeConstraints { make in
            make.top.equalTo(codeView.snp.bottom).offset(auto(20))
            make.left.equalTo(auto(20))
        }
        
        agreeTextView.snp.makeConstraints { make in
            make.centerY.equalTo(agreeButton)
            make.left.equalTo(agreeButton.snp.right).offset(auto(10))
            make.right.equalToSuperview()
            make.height.equalTo(17)
        }
        
        loginButton.layer.cornerRadius = auto(25)
        loginButton.snp.makeConstraints { make in
            make.top.equalTo(inputContentView.snp.bottom).offset(auto(30))
            make.width.equalTo(auto(300))
            make.height.equalTo(auto(50))
            make.centerX.equalToSuperview()
        }
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

class LoginInputView : DDView {
    public let titleLabel : DDLabel
    public let textfield : DDTextField
    public let line : DDView
    public let codeButton : DDButton
    override init(frame: CGRect) {
        titleLabel = DDLabel.dd_init(withText: "", font: .regularFont(auto(15)), textColor: .hex("203152"))
        textfield = DDTextField.init()
        line = DDView.init()
        line.backgroundColor = .hex("F1F2F5")
        codeButton = DDButton.dd_initCustom()
        super.init(frame: frame)
        
        addSubview(titleLabel)
        addSubview(textfield)
        addSubview(line)
        addSubview(codeButton)
        
        line.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.left.equalTo(auto(20))
            make.right.equalTo(-auto(20))
            make.height.equalTo(1)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(line)
            make.top.equalTo(auto(25))
        }
        
        textfield.snp.makeConstraints { make in
            make.left.equalTo(titleLabel)
            make.bottom.equalTo(line.snp.top).offset(-auto(5))
            make.left.equalTo(line)
            make.right.equalTo(codeButton.snp.left)
        }
        
        codeButton.layer.cornerRadius = auto(12.5)
        codeButton.snp.makeConstraints { make in
            make.centerY.equalTo(textfield)
            make.right.equalTo(line)
            make.height.equalTo(auto(25))
            make.width.equalTo(auto(90))
        }
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
