//
//  YHMainViewController.swift
//  galaxy
//
//  Created by EDY on 2023/12/20.
//

import UIKit
import SnapKit
import NEConversationUIKit

enum YHPersonalModuleItemType: Int {
    case none = 0
    
    case myMessage
    case myProgress
    case scoreCenter
    case recommend
    case myPoster
    case myTestCode
    case appointGalaxyBay
    
    case changeSettings
    case darkMode
    case infoCollectList
    case infoShareList
    case aboutUs
}

struct PersonalModuleItem {
    var icon: String?
    var title: String
    var type:YHPersonalModuleItemType = .none
    init(icon: String? = nil, title: String, type:YHPersonalModuleItemType) {
        self.icon = icon
        self.title = title
        self.type = type
    }
}

class YHMyViewController: YHBaseViewController, ConstraintRelatableTarget {
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style:.plain)
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.showsVerticalScrollIndicator = false
        tableView.tableHeaderView = headerView
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.register(YHPersonalCenterCell.self, forCellReuseIdentifier: YHPersonalCenterCell.cellReuseIdentifier)
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    lazy var items: [PersonalModuleItem] = {
        return [PersonalModuleItem(icon: "mine_item_msg", title: "我的消息".local, type:.myMessage),
                PersonalModuleItem(icon: "mine_item_progress", title: "我的进度".local, type:.myProgress),
                PersonalModuleItem(icon: "mine_item_scoreCenter", title: "积分中心".local, type:.scoreCenter),
                PersonalModuleItem(icon: "mine_item_recommend", title: "推荐有礼".local, type:.recommend),
                PersonalModuleItem(icon: "mine_item_poster", title: "我的海报".local, type:.myPoster),
                PersonalModuleItem(icon: "mine_item_code", title: "我的测评码".local, type:.myTestCode),
                PersonalModuleItem(icon: "mine_item_appoint", title: "预约银河湾".local, type:.appointGalaxyBay),
               ]
    }()
    
    lazy var headerView: YHUserInfoHeaderView = {
        let view = YHUserInfoHeaderView.createView()
        view.settingBlock = {
            [weak self] in
            guard let self = self else { return }
            if !checkLogin() { return }
            let vc = YHMySettingViewController()
            self.navigationController?.pushViewController(vc)
        }
        view.evaluateBlock = {
            [weak self] in
            guard let self = self else { return }
            if !checkLogin() { return }
        }
        view.avatarClickBlock = {
            [weak self] in
            guard let self = self else { return }
            if !checkLogin() { return }
        }
        view.nickNameClickBlock = {
            [weak self] in
            guard let self = self else { return }
            if !checkLogin() { return }
        }
        return view
    }()
    
    private lazy var bgImgView:UIImageView = {
        let img = UIImageView(image: UIImage(named: "mine_header_bg"))
        return img
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initView()
    }
    
    func checkLogin()->Bool {
        if YHLoginManager.shared.isLogin() == false {
            let vc = UINavigationController(rootVC: YHPhoneLoginViewController())
            vc.modalPresentationStyle = .custom
            self.navigationController?.present(vc, animated: true)
            return false
        }
        return true
    }
    
    func initView() {
        
        gk_navigationBar.isHidden = true
        view.addSubview(bgImgView)
        view.addSubview(tableView)
        
        updateUserUI()
        
        bgImgView.snp.makeConstraints { make in
            make.left.right.top.equalTo(view)
            make.height.equalTo(bgImgView.snp.width).multipliedBy(YHUserInfoHeaderView.bgRatio)
        }
        tableView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalToSuperview().offset(-k_Height_TabBar)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: YhConstant.YhNotification.didLoginSuccessNotifiction, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(logoutSuccess), name: YhConstant.YhNotification.didLogoutSuccessNotifiction, object: nil)
        
    }
}

extension YHMyViewController : UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: YHPersonalCenterCell.cellReuseIdentifier, for: indexPath) as! YHPersonalCenterCell
        let item : PersonalModuleItem = items[indexPath.row];
        cell.updateItem(item: item)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 52
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if (indexPath.row >= items.count) { return }
        
        if !checkLogin() {
            let vc = UINavigationController(rootVC: YHPhoneLoginViewController())
            vc.modalPresentationStyle = .custom
            self.navigationController?.present(vc, animated: true)
        } else {
            YHHUD.flash(message: "已登录: 功能完善中...")
        }
        return //for test hjl
        
        let item: PersonalModuleItem = items[indexPath.row];
        
        if item.title == "关于我们" {
            let vc = YHAboutUsViewController()
            self.navigationController?.pushViewController(vc)
            
        } else if item.title == "我的设置" {
            
            let account = "duyu"
            let token = "123456"
            let vc = ConversationController()
            self.navigationController?.pushViewController(vc)
            
            IMKitClient.instance.loginIM(account, token) { error in
                if let err = error {
                    print("login error in app : ", err.localizedDescription)
                }else {
                    let _ = NEAtMessageManager.instance
                   
                }
            }
            
            
            
        } else {
//            let vc = YHLoginViewController()
//            self.navigationController?.pushViewController(vc)
        }

    }
}

extension YHMyViewController {
    @objc func loginSuccess() {
        printLog("登录成功，进行相应的 UI刷新操作")
        updateUserUI()
    }
    
    @objc func logoutSuccess() {
        updateUserUI()
    }
    
    func updateUserUI() {
        if YHLoginManager.shared.isLogin() {
            headerView.nickName =  YHLoginManager.shared.userModel?.nickname ?? "Hi, 银河用户".local
        } else {
            headerView.nickName =  "登录/注册"
        }
    }
}
