//
//  LoginVc.swift
//  VattiCSS
//
//  Created by Jan on 2023/8/22.
//

import UIKit
import TWOCNetwork

class LoginVc: UIViewController {
    
    @IBOutlet weak var userTypeA_btn: UIButton!
    @IBOutlet weak var userTypeA_line: UIImageView!
    
    @IBOutlet weak var userTypeB_btn: UIButton!
    @IBOutlet weak var userTypeB_line: UIImageView!
    
    @IBOutlet weak var userTypeC_btn: UIButton!
    @IBOutlet weak var userTypeC_line: UIImageView!
    
    @IBOutlet weak var acc_field: UITextField!
    @IBOutlet weak var com_view: UIView!
    @IBOutlet weak var com_field: UITextField!
    @IBOutlet weak var com_btn: UIButton!
    @IBOutlet weak var pas_field: UITextField!
    
    @IBOutlet weak var send_btn: UIButton!
    @IBOutlet weak var proBtn: UIButton!
    
    //标题
    @IBOutlet weak var lab_title: UILabel!
    //协议
    @IBOutlet weak var lab_readTips: UILabel!
    @IBOutlet weak var btn_agreement: UIButton!
    @IBOutlet weak var lab_and: UILabel!
    @IBOutlet weak var btn_privacy: UIButton!
    @IBOutlet weak var btn_forget: UIButton!
    //注册
    @IBOutlet weak var btn_regist: UIButton!
    
    var comId = ""
    var siteid = ""
    var comName = "" {
        didSet{
            com_field.text = comName
        }
    }
    
    // 关联企业列表
    var companyArr = [[String:Any]]()
    
    var userType:UserRole = .None {
        didSet{
            if oldValue != userType {
                refreshUi()
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        configUi()
        userType = .Engineer
        loadLoaclData()
        
        requestCheckVersionInfo()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    //检查更新
    func requestCheckVersionInfo(){
        CheckVersionMgr.shareInstance.checkVersionWithSystemAlert()
    }
    
    // 加载本地数据
    func loadLoaclData() {
        let curState = UserDefaults.standard.bool(forKey: StringMacro.protocolStateKey)
        proBtn.isSelected = curState
        
        let cUserTypeInt = UserDefaults.standard.integer(forKey: StringMacro.userTypeKey)
        guard let cUserType = UserRole(rawValue: cUserTypeInt) else { return }
        userType = cUserType
        
        if let phoneStr = UserDefaults.standard.string(forKey: StringMacro.usernameKey) {
            acc_field.text = phoneStr
            if !phoneStr.isEmpty {
                requetCompany(userStr: phoneStr, needShowPicker: false)
            }
        }
        if let passStr = UserDefaults.standard.string(forKey: StringMacro.passwordKey) {
            pas_field.text = passStr
        }
    }
    
    func configUi() {
        acc_field.makeLayerRadius(value: 8)
        com_view.makeLayerRadius(value: 8)
        pas_field.makeLayerRadius(value: 8)
        send_btn.makeLayerRadius(value: 8)
        
        addLeftViewToField(tField: acc_field)
        addLeftViewToField(tField: com_field)
        addLeftViewToField(tField: pas_field)
        
        userTypeA_btn.setTitleColor(UIColor(hexString: "#666666"), for: .normal)
        userTypeA_btn.setTitleColor(UIColor(hexString: "#333333"), for: .selected)
        userTypeB_btn.setTitleColor(UIColor(hexString: "#666666"), for: .normal)
        userTypeB_btn.setTitleColor(UIColor(hexString: "#333333"), for: .selected)
        userTypeC_btn.setTitleColor(UIColor(hexString: "#666666"), for: .normal)
        userTypeC_btn.setTitleColor(UIColor(hexString: "#333333"), for: .selected)
        
        acc_field.addTarget(self, action: #selector(self.accEditEnd), for: .editingDidEnd)
        com_field.isUserInteractionEnabled = false
        pas_field.isSecureTextEntry = true
        
        //lang_localizable
        userTypeA_btn.setTitle("工程师".languageString(), for: .normal)
        userTypeB_btn.setTitle("服务商".languageString(), for: .normal)
        
        lab_title.text = "欢迎来到周到快服".languageString()
        acc_field.placeholder = "账号".languageString()
        com_field.placeholder = "企业".languageString()
        pas_field.placeholder = "密码".languageString()
        
        lab_readTips.text = "登录代表阅读并遵守".languageString()
        lab_and.text = "和".languageString()
        btn_forget.titleLabel?.text = "忘记密码".languageString()
        btn_regist.setTitle("注册".languageString(), for: .normal)
        
        btn_agreement.setTitle("使用协议".languageString(), for: .normal)
        btn_privacy.setTitle("隐私协议".languageString(), for: .normal)
        send_btn.setTitle("立即登录".languageString(), for: .normal)
    }
    
    func refreshUi() {
        userTypeA_line.isHidden = true
        userTypeA_btn.isSelected = false
        userTypeA_btn.titleLabel?.font = UIFont.PingFangRegular(size: 16)
        
        userTypeB_line.isHidden = true
        userTypeB_btn.isSelected = false
        userTypeB_btn.titleLabel?.font = UIFont.PingFangRegular(size: 16)
        
        userTypeC_line.isHidden = true
        userTypeC_btn.isSelected = false
        userTypeC_btn.titleLabel?.font = UIFont.PingFangRegular(size: 16)
        
        switch userType {
        case .Engineer:
            userTypeA_line.isHidden = false
            userTypeA_btn.isSelected = true
            userTypeA_btn.titleLabel?.font = UIFont.PingFangMedium(size: 16)
        case .Site:
            userTypeB_line.isHidden = false
            userTypeB_btn.isSelected = true
            userTypeB_btn.titleLabel?.font = UIFont.PingFangMedium(size: 16)
        case .Admin:
            userTypeC_line.isHidden = false
            userTypeC_btn.isSelected = true
            userTypeC_btn.titleLabel?.font = UIFont.PingFangMedium(size: 16)
        case .None:
            break
        }
    }
    
    // 添加左边间隔
    func addLeftViewToField(tField: UITextField) {
        let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 12, height: 12))
        leftView.backgroundColor = UIColor.clear
        tField.leftView = leftView
        tField.leftViewMode = .always
    }
    
    @IBAction func userTypeBtnAction(_ sender: UIButton) {
        let oldType = userType
        userType = UserRole(rawValue: sender.tag) ?? .None
        
//        if oldType != userType{
//            acc_field.text = ""
//            com_field.text = ""
//            pas_field.text = ""
//        }
    }
    
    @IBAction func companyBtnAction(_ sender: UIButton) {
        view.endEditing(true)
        guard let userStr = acc_field.text, userStr.count > 0 else {
            hud_error("请先输入账号".languageString())
            return
        }
        requetCompany(userStr: userStr,needShowPicker: true)
    }
    
    @IBAction func forgetBtnAction(_ sender: UIButton) {
        
    }
    
    @IBAction func sendAction(_ sender: UIButton) {
        view.endEditing(true)
        let curState = UserDefaults.standard.bool(forKey: StringMacro.protocolStateKey)
        if curState == false {
            hud_info("请阅读并同意协议".languageString())
            return
        }
        guard let accStr = acc_field.text, accStr.count > 0 else {
            hud_info("请输入账号".languageString())
            return
        }
        guard comId.count > 0 else {
            hud_info("请选择企业".languageString())
            return
        }
        guard let pasStr = pas_field.text, pasStr.count > 0 else {
            hud_info("请输入密码".languageString())
            return
        }
        beginLogin(ac: accStr, co: comId, pa: pasStr)
    }
    
    @IBAction func protocolBtnAction(_ sender: UIButton) {
        view.endEditing(true)
        var curState = UserDefaults.standard.bool(forKey: StringMacro.protocolStateKey)
        curState.toggle()
        proBtn.isSelected = curState
        UserDefaults.standard.set(curState, forKey: StringMacro.protocolStateKey)
        UserDefaults.standard.synchronize()
    }
    
    @IBAction func userProAction(_ sender: UIButton) {
        let webUrl = "https://css-new-uat.vatti.com.cn/h5/userAgreement.html"
        R_Web.push(.http(webUrl), title: "用户协议".languageString())
    }
    
    @IBAction func privacyProAction(_ sender: UIButton) {
        let webUrl = "https://css-new-uat.vatti.com.cn/h5/userPrivacyAgreement.html"
        R_Web.push(.http(webUrl), title: "隐私协议".languageString())
    }
    
    
    @IBAction func registerAction(_ sender: UIButton) {
        R_Register.router()
    }
    
    @objc func accEditEnd() {
        guard let userStr = acc_field.text, userStr.count > 0 else { return  }
        requetCompany(userStr: userStr,needShowPicker: false)
    }
    
    func requetCompany(userStr: String, needShowPicker: Bool) {
        let cNet = TWOCNetwork(url: "/v2/login/getCompanyList.jhtml",andParam: ["account":userStr,"userRole":userType.rawValue,"appName":"云服务APP"])
        cNet.successCall = { [weak self] (result) in
            guard let weakSelf = self else { return }
            let companylist = result.arrayValue(forKey: "companylist")
            if companylist.count == 1 {
                weakSelf.setDefaultCom(comArr: companylist)
            }else{
                if needShowPicker {
                    weakSelf.showCompanyPicker(comArr: companylist)
                }else{
                    weakSelf.setDefaultCom(comArr: companylist)
                }
               
            }
            
        }
        cNet.failCall = { (errorTag,errorStr) in
            hud_error(errorStr)
        }
        cNet.sendConfigRequest()
    }
    
    func setDefaultCom(comArr:[[String:Any]]) {
        var selCompany = comArr.filter {
            $0.intValue(forKey: "isdefault") == 1
        }.first
        if selCompany == nil {
            selCompany = comArr.first
        }
        guard let curComp = selCompany else { return }
        self.comId = curComp.stringValue(forKey: "companyid")
        self.comName = curComp.stringValue(forKey: "companyname")
        
        let siteId = curComp.stringValue(forKey: "siteid")
        MyInfo.shareInstance().siteId = siteId
        self.siteid = siteId
        
        let bUrl = curComp.stringValue(forKey: "requesturl")
     
        let serverUrl = bUrl
        if serverUrl.last == "/"{
            ///文件服务器去掉/
            let newUrl = serverUrl.prefix(serverUrl.count-1)
            TWOCNetwork.shareNetManager().filePath = String(newUrl) + "/admin/sys-file/upload"
            TWOCNetwork.shareNetManager().baseURL = bUrl
        }else{
            TWOCNetwork.shareNetManager().filePath = bUrl + "/admin/sys-file/upload"
            TWOCNetwork.shareNetManager().baseURL = bUrl+"/"
        }
    }
    
    func showCompanyPicker(comArr:[[String:Any]])  {
        let pickerDataArr = comArr.compactMap {
            ($0.stringValue(forKey: "companyname"),"")
        }
        TWSheetPicker.showActionSheet(titleStr: "请选择企业".languageString(), singleType: true, dataArr: pickerDataArr) {  [weak self] (indexArr) in
            guard let weakSelf = self else { return }
            guard let index = indexArr.first else { return }
            let curComp = comArr[index]
            weakSelf.comId = curComp.stringValue(forKey: "companyid")
            weakSelf.comName = curComp.stringValue(forKey: "companyname")
            
            let siteId = curComp.stringValue(forKey: "siteid")
            MyInfo.shareInstance().siteId = siteId
            self?.siteid = siteId

            let bUrl = curComp.stringValue(forKey: "requesturl")
          
            let serverUrl = bUrl
            if serverUrl.last == "/"{
                ///去掉/
                let newUrl = serverUrl.prefix(serverUrl.count-1)
                TWOCNetwork.shareNetManager().filePath = String(newUrl) + "/admin/sys-file/upload"
                TWOCNetwork.shareNetManager().baseURL = bUrl
            }else{
                TWOCNetwork.shareNetManager().filePath = bUrl + "/admin/sys-file/upload"
                TWOCNetwork.shareNetManager().baseURL = bUrl+"/"
            }
          
        }.show(self)
    }
    
    func beginLogin(ac: String, co: String, pa: String) {
        var sendParam = [String:Any]()
        sendParam["companyId"] = co
        sendParam["account"] = ac
        sendParam["password"] = pa
        sendParam["userRole"] = userType.rawValue
        sendParam["mobiletoken"] = MyInfo.shareInstance().pushToken
        sendParam["siteId"] = self.siteid
        
        SVProgressHUD.show()
        let cNet = TWOCNetwork(url: "/app/v2/login/login",andParam: sendParam)
        cNet.successCall = { [weak self] (result) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            
            if let objx = result["data"] as? [String:Any] {
                MyInfo.shareInstance().userRole = weakSelf.userType
                MyInfo.shareInstance().configData(cData: objx)
                weakSelf.saveDataToLocal(ac: ac, co: co, pa: pa)
                weakSelf.loadTab()
            }else{
                hud_error("用户信息无效".languageString())
            }
        }
        cNet.failCall = { (errorTag,errorStr) in
            SVProgressHUD.dismiss()
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    // 保存账号信息到本地
    func saveDataToLocal(ac: String, co: String, pa: String) {
        UserDefaults.standard.set(userType.rawValue, forKey: StringMacro.userTypeKey)
        UserDefaults.standard.set(ac, forKey: StringMacro.usernameKey)
        UserDefaults.standard.set(pa, forKey: StringMacro.passwordKey)
        UserDefaults.standard.synchronize()
    }
    // 加载Tabbar
    func loadTab()  {
        UIApplication.shared.keyWindow?.rootViewController = TWTabBarVc();
    }
    
}
