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

import UIKit
import SnapKit
import NEConversationUIKit
import SafariServices

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:.grouped)
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.estimatedSectionHeaderHeight = 1.0
        tableView.showsVerticalScrollIndicator = false
        tableView.tableHeaderView = headerView
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.bounces = false
        tableView.register(YHPersonalCenterCell.self, forCellReuseIdentifier: YHPersonalCenterCell.cellReuseIdentifier)
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    lazy var items: [PersonalModuleItem] = {
        
        let version = "app版本号：" + UIDevice.appVersion() + "_" + UIDevice.appBuild()
        
        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),
                PersonalModuleItem(icon: "mine_item_appoint", title: version, 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
    }()
        
    override func viewDidLoad() {
        super.viewDidLoad()
        initView()
        return
    }
    
    @objc func clickBtn() {
        
    }
    
    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(tableView)
        
        updateUserUI()
        
        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 true {
            
//            YHCertificateUploadFailTipsView.tipsView().show()

            
//            let vc = YHUploadContentVC()
//            self.navigationController?.pushViewController(vc)
            
            
           let vc = YHMaterialListViewController()
           self.navigationController?.pushViewController(vc)
           return
        }
        
        
        
        if !checkLogin() {
            let vc = UINavigationController(rootVC: YHPhoneLoginViewController())
            vc.modalPresentationStyle = .custom
            self.navigationController?.present(vc, animated: true)
        } else {
            YHHUD.flash(message: "已登录: 功能完善中...")
        }
        
        return
        
        
//        let url = URL(string: "https://docs.qq.com/openapi/drive/v2/files/embed/temporary?timestamp=1710298232&id=6bcaa379b0e5488abbaff85d51ee2fab&clientID=2aebc2da4f0b4883bf33ef20836f2e2d")!
//        
//        let tmpVC = SFSafariViewController(url: url)
//        navigationController?.pushViewController(tmpVC)
//    
//        
//        return
        
//        if indexPath.row == 0 {
//
//            
//            let vc = YHWebViewViewController()
//            navigationController?.pushViewController(vc, animated: true)
//        } else {
//            let vc = YHWebViewViewController()
//            navigationController?.pushViewController(vc, animated: true)
//        }
//        
//        return
        
        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 =  "登录/注册"
        }
    }
}
