//
//  QSLMineController.swift
//  QuickSearchLocation
//
//  Created by mac on 2024/4/10.
//

import UIKit

class QSLMineController: QSLBaseController {
    
    var viewModel:QSLMineViewModel = QSLMineViewModel()
    
    lazy var mineBgImageView: UIImageView = {
        
        let imageView = UIImageView()
        imageView.image = UIImage(named: "mine_bg")
        return imageView
    }()
    
    lazy var mineInfoView: QSLMineInfoView = {
       
        let view = QSLMineInfoView()
        view.isUserInteractionEnabled = true
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(jumpToLogin))
        view.addGestureRecognizer(tap)
        
        return view
    }()
    
    lazy var mineVipView: QSLMineVipView = {
       
        let view = QSLMineVipView()
        view.delegate = self
        return view
    }()
    
    lazy var mineFuncView: QSLMineFuncView = {
       
        let view = QSLMineFuncView()
        view.delegate = self
        view.viewModel = viewModel
        return view
    }()
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        setUpUI()
        
        updateUI()
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateUI), name: QSLNotification.QSLLogin, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateUI), name: QSLNotification.QSLLogout, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(requestVip), name: QSLNotification.QSLRefreshMember, object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.requestVip()
    }
}

extension QSLMineController {
    
    // 请求vip信息
    @objc func requestVip() {
        
        QSLNetwork().request(.userMember(dict: [:])) { response in
            
            let memberModel = response.mapObject(QSLMemberModel.self, modelKey: "data")
            QSLBaseManager.shared.userModel.memberModel = memberModel
            
            if memberModel.expired {
                QSLBaseManager.shared.saveVipExpiredTime(time: 0)
            } else {
                QSLBaseManager.shared.saveVipExpiredTime(time: memberModel.endTimestamp)
            }
            
            QSLBaseManager.shared.saveUserId(id: memberModel.userId)
            
            self.mineVipView.updateUI()
//            NotificationCenter.default.post(name: QSLNotification.QSLRefreshMember, object: nil)
            
        } fail: { code, error in
            
        }
    }
    
    // 清除用户数据
    func requestClearUser() {
        
        QSLNetwork().request(.userClear(dict: [:])) { response in
            
            self.view.toast(text: "注销成功")
            QSLBaseManager.shared.logOut()
        } fail: { code, error in
            
        }
    }
}

extension QSLMineController {
    
    // 跳转到登录页面
    @objc func jumpToLogin() {
        
        if !QSLBaseManager.shared.isLogin() {
            QSQuickLogonHandle.share.currentVC = self
            QSQuickLogonHandle.share.starOneQuickLogin(loginSuccess: {
                
            })
        }
        
        /*if !QSLBaseManager.shared.isLogin() {
            
            gravityInstance?.track(QSLGravityConst.mine_login)
            QSLJumpManager.shared.pushToLogin(type: .mine)
        }*/
    }
}

extension QSLMineController: QSLMineVipViewDelegate {
    
    // 跳转到vip页面
    func unlockBtnAction() {
        
        gravityInstance?.track(QSLGravityConst.mine_vip)
        QSLJumpManager.shared.pushToVip(type: .mine)
    }
}

extension QSLMineController: QSLMineFuncViewDelegate {
    
    func didSelectRowAt(indexPath: IndexPath) {
        switch indexPath.row {
        case 0:
            self.jumpToContact()
            break
        case 1:
            // 权限跳转
            self.authAction()
            break
        case 2:
            // 关于我们
            self.jumpToInfo()
            break
        case 3:
            // 注销
            self.logOffAction()
            break
        case 4:
            // 退出登录
            self.logoutAction()
            break
        case 5: break
        case 6: break
        case 7:
            
            break
        default: break
        }
    }
    
    func jumpToContact() {
        
        gravityInstance?.track(QSLGravityConst.mine_contact)
        QSLJumpManager.shared.pushToContact(type: .mine)
//        let vc = QSLContactController()
//        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func jumpToInfo() {
        
        gravityInstance?.track(QSLGravityConst.mine_about)
        let vc = QSLAppInfoController()
        vc.title = "关于我们"
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    // MARK: - 权限
    func authAction() {
        
        gravityInstance?.track(QSLGravityConst.mine_auth)
        if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
            
            UIApplication.shared.open(url)
        }
    }
    
    // MARK: - 注销账号
    func logOffAction() {
        
        if let view = self.tabBarController?.view {
            QSLAlertView.alert(view: view, title: "温馨提示", content: "确认注销账号吗？", secondBtnClosure:  {
                self.view.toast(text: "注销成功")
                self.requestClearUser()
            })
        }
    }
    
    // MARK: - 退出登录
    func logoutAction() {
        
        gravityInstance?.track(QSLGravityConst.mine_logout)
        if let view = self.tabBarController?.view {
            QSLAlertView.alert(view: view, title: "温馨提示", content: "确认退出登录吗？", firstBtnClosure: {
                gravityInstance?.track(QSLGravityConst.mine_logout_cancel)
            }, secondBtnClosure:  {
                gravityInstance?.track(QSLGravityConst.mine_logout_confirm)
                self.view.toast(text: "退出登录成功")
                QSLBaseManager.shared.logOut()
            })
        }
    }
}

extension QSLMineController {
    
    @objc func updateUI() {
        
        self.viewModel.initFuncData()
        
        mineFuncView.snp.updateConstraints { make in
            make.height.equalTo(viewModel.funcViewHeight)
        }
        
        self.mineFuncView.funcTableView.reloadData()
        
        if QSLBaseManager.shared.isLogin() {
            
            let name = "用户\(QSLBaseManager.shared.userModel.phone.suffix(4))"
            self.mineInfoView.config(name: name, content: "您好，尊敬的用户")
        } else {
            self.mineInfoView.config(name: "立即登录", content: "解锁更多精彩内容")
        }
        
        mineVipView.updateUI()
    }
    
    func setUpUI() {
        
        view.addSubview(mineBgImageView)
        mineBgImageView.snp.makeConstraints { make in
            make.left.top.right.equalTo(0)
        }
        
        view.addSubview(mineInfoView)
        mineInfoView.snp.makeConstraints { make in
            make.left.top.right.equalTo(0)
            make.height.equalTo(122 + QSLConst.qsl_kStatusBarFrameH)
        }
        
        view.addSubview(mineVipView)
        mineVipView.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.top.equalTo(mineInfoView.snp.bottom).offset(10)
            make.height.equalTo(90)
        }
        
        view.addSubview(mineFuncView)
        mineFuncView.snp.makeConstraints { make in
            make.top.equalTo(mineVipView.snp.bottom).offset(12)
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.height.equalTo(viewModel.funcViewHeight)
        }
    }
}
