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

import UIKit

public struct R_MineUpdate {
    static func router(_ style:String,mobile:String="") {
        let vc = MineUpdateVc.cd_storyboard("Mine", from: "MineUpdateVc") as! MineUpdateVc
        vc.hidesBottomBarWhenPushed = true
        vc.style = style
        vc.vm.style = style
        vc.vm.mobile = mobile
        CD.push(vc)
    }
}

class MineUpdateVc: UIViewController {
    lazy var topBar: CD_TopBar = {
        return CD_TopBar()
    }()
    lazy var tableView: UITableView = {
        let tab = UITableView()
        return tab
    }()
    var vm = MineUpdateVm()
    var style = "修改手机号"
    
    deinit {
        MineGetCodeTool.defaultTool().timerNumber = 0
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        self.cd.navigationBar(hidden: true)
        self.view.cd
            .add(topBar)
        topBar.delegate = self
        topBar.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
        }
        
        self.configTableView()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        MineGetCodeTool.defaultTool().timerNumber = 0
    }
    
    func configTableView() {
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(self.topBar.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        
        self.tableView.backgroundColor = UIColor(hexString: "f8f8f8")
        self.view.backgroundColor = UIColor(hexString: "f8f8f8")
        
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
       
        vm.callback = {
            self.tableView.reloadData()
        }
        
        vm.getCodeCallback = { str in
            self.requestGetCode()
        }
        
        vm.submitCallback = {
            if self.style == "修改手机号"{
                self.checkMobile()
            }else{
                self.checkPassword()
            }
        }
        
        vm.makeForms()
    }
    
    func checkMobile() {
        guard vm.newMobile != "" else {
            CD.visibleVC?.promptInformation("请输入新手机号".languageString())
            return
        }
        guard vm.code != "" else {
            CD.visibleVC?.promptInformation("请输入验证码".languageString())
            return
        }
        
        var param = [String:Any]()
        param["newMobile"] = vm.newMobile
        param["verificationCode"] = vm.code
        requstSaveData(param)
    }
    
    func checkPassword() {
        guard vm.old != "" else {
            CD.visibleVC?.promptInformation("请输入原密码".languageString())
            return
        }
        guard vm.password1 != "" else {
            CD.visibleVC?.promptInformation("请输入新密码".languageString())
            return
        }
        guard vm.password1.count >= 6 else {
            CD.visibleVC?.promptInformation("密码不能小于6位！".languageString())
            return
        }
        guard vm.password2 != "" else {
            CD.visibleVC?.promptInformation("请再次输入新密码".languageString())
            return
        }
        guard vm.password1 == vm.password2 else {
            CD.visibleVC?.promptInformation("前后新密码不一致，请重新输入".languageString())
            return
        }
        var param = [String:Any]()
        param["oldPassword"] = vm.old
        param["newPassword"] = vm.password1
        requstSaveData(param)
    }
}

//请求
extension MineUpdateVc{
    func requstSaveData(_ param:[String:Any]){
        var requestPath = self.style == "修改手机号" ? "app/v2/personal/updateMobile" : "app/v2/personal/updatePassword"
        
        let cNet = TWOCNetwork(url: requestPath,andParam: param)
        cNet.successCall = { [weak self] (result) in
            guard let weakSelf = self else { return }
            if let data = result["data"] as? [String:Any] {
                DispatchQueue.main.async(execute: {
                    hud_info("操作成功~".languageString())
                    weakSelf.navigationController?.popViewController(animated: true)
                })
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
    func requestGetCode(){
       self.view.endEditing(true)
        if vm.newMobile == ""{
            self.promptInformation("请输入新手机号~".languageString())
            return
        }
        var paramDict = [String:Any]()
        paramDict["mobile"] = vm.newMobile
        MineGetCodeTool.defaultTool().starRequestVerificationCode(theParam: paramDict,timerCount: 60)
   }
    
}


extension MineUpdateVc: CD_TopBarProtocol {
    func topBarCustom() {
        topBar.cd.background(.white)
        topBar._title = self.style
        topBar._colorTitle = Config.color.hex("3")
        topBar.bar_navigation.line.cd.isHidden(true)
        
        topBar._style = "10"
    }
    
    func update(withTopBar item: CD_TopNavigationBar.Item) -> [CD_TopNavigationBarItem.Item.Style]? {
        switch item {
        case .leftItem1:
            let color:UIColor = Config.color.hex("6")
            let icon = CD_IconFont.tback_light(22)
            return [.title([(icon.text, icon.font, color, .normal), (icon.text, icon.font, Config.color.hex("6"), .highlighted), (icon.text, icon.font, Config.color.hex("6"), .selected)])]
        default:
            return nil
        }
    }
    
    func didSelect(withTopBar item: CD_TopNavigationBar.Item) {
        super_topBarClick(item)
        switch item {
        case .leftItem1:
            break
        default:
            break
        }
    }
}


// MARK: - Table view data source
extension MineUpdateVc: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return vm.forms.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellVM = vm.forms[indexPath.row]
        let cellIdentifier = cellVM.cellId.isEmpty ? String(describing: cellVM.cellClass) : cellVM.cellId
        var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
        if cell == nil {
            let bundle = Bundle.main.path(forResource:cellIdentifier, ofType: "nib")
            if bundle == nil{
                tableView.register(cellVM.cellClass, forCellReuseIdentifier: cellIdentifier)
            }else{
                let cellNib = UINib(nibName:cellIdentifier, bundle: nil)
                tableView.register(cellNib, forCellReuseIdentifier: cellIdentifier)
            }
            cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
        }
        
        guard let endCell = cell else {
            fatalError("没有找到标识为：\(cellIdentifier)的Cell")
        }
        cellVM.bind(endCell)
        return endCell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor.init(hexString: "f8f8f8")
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellVM = vm.forms[indexPath.row]
        return cellVM.frameH
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cellVM = vm.forms[indexPath.row]
        cellVM.tapBlock?()
    }
}
