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

import UIKit
import SnapKit
import SafariServices



enum YHPersonalModuleItemType: Int {
    case none = 0
    
    case myMessage
    case myProgress
    case scoreCenter
    case recommend
    case myPoster
    case myTestCode
    case appointGalaxyBay
    
    case notifySettings
    case permissionSettings
    case playSettings
    case infoCollectList
    case infoShareList
    case aboutUs
    case deviceInfo
    case version
    case userItems//用户条款
    case privaceAgreement//隐私协议
}

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

class YHMyViewController: YHBaseViewController, ConstraintRelatableTarget {
    
    let likeViewModel: YHMyLikeViewModel = YHMyLikeViewModel()
    let msgViewModel: YHMsgViewModel = YHMsgViewModel()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style:.grouped)
        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 bgImgView:UIImageView = {
        let imgView = UIImageView(image: UIImage(named: "mine_header_bg"))
        return imgView
    }()
    
    lazy var items: [PersonalModuleItem] = {
        var arrData = [
            PersonalModuleItem(icon: "mine_item_msg", title: "我的消息".local, type:.myMessage),
            PersonalModuleItem(icon: "mine_item_scoreCenter", title: "积分中心".local, type:.scoreCenter),
            PersonalModuleItem(icon: "mine_item_code", title: "我的测评码".local, type:.myTestCode),
            PersonalModuleItem(icon: "mine_item_appoint", title: "预约银河湾".local, type:.appointGalaxyBay)
        ]
        return arrData
    }()
    
    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 }
        }
        view.likeClick = {
            [weak self] in
            guard let self = self else { return }
            if !checkLogin() { return }
            let vc = YHMyLikeViewController()
            vc.id = 1
            self.navigationController?.pushViewController(vc)
            print("点赞")
        }
        view.collectClick = {
            [weak self] in
            guard let self = self else { return }
            if !checkLogin() { return }
            let vc = YHMyLikeViewController()
            vc.id = 2
            self.navigationController?.pushViewController(vc)
            print("收藏")
        }
        view.recentScanClick = {
            [weak self] in
            guard let self = self else { return }
            if !checkLogin() { return }
            let vc = YHMyLikeViewController()
            vc.id = 3
            self.navigationController?.pushViewController(vc)
            print("最近浏览")
        }
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initView()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requestLikeCollectionCount()
        getTotalUnreadMsgCount()
        checkSettingRedPoint()
        self.headerView.updateAvatar()
    }
    
    @objc func clickBtn() {
        
    }
    
    func checkLogin()->Bool {
        if YHLoginManager.shared.isLogin() == false {
            YHOneKeyLoginManager.shared.oneKeyLogin()
            return false
        }
        return true
    }
    
    func checkSettingRedPoint() {
        if YHConfigManager.shared.loadNewDataFlag == false {
            YHConfigManager.shared.loadConfigData {
                [weak self] in
                guard let self = self else { return }
                self.headerView.isShowSettingRedPoint = YHAppVersionManager.shared.needShowRedPointOfSuggestVersionUpdate()
            }
        } else {
            self.headerView.isShowSettingRedPoint = YHAppVersionManager.shared.needShowRedPointOfSuggestVersionUpdate()
        }
    }
    
    func initView() {
        
        gk_navigationBar.isHidden = true
        // 背景色必须放底部
        view.addSubview(bgImgView)
        view.addSubview(tableView)
        self.view.backgroundColor = .white
        
        updateUserUI()
        
        bgImgView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            let topMargin = (k_Height_StatusBar > 20.0 ? 0 : -24)
            make.top.equalToSuperview().offset(topMargin)
            make.height.equalTo(312.0)
        }
        
        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)
        NotificationCenter.default.addObserver(self, selector: #selector(clearUnreadBadge), name: YhConstant.YhNotification.didMarkAllMessagesReadedNotifiction, object: nil)
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    func requestLikeCollectionCount() {
        self.likeViewModel.getLikeCollectionRecentScanCountInfo {
            [weak self] success, error in
            guard let self = self else { return }
            self.headerView.updateLikeCollectCount(self.likeViewModel.likeCollectCountInfo)
        }
    }
    
    // 请求未读消息总数
    func getTotalUnreadMsgCount() {
        if YHLoginManager.shared.isLogin() {
            self.msgViewModel.requestTotalUnreadMsgCount {
                [weak self] success, error in
                guard let self = self else { return }
                DispatchQueue.main.async {
                    let count = self.msgViewModel.unreadTotalCount
                    for item in self.items {
                        if item.type == .myMessage {
                            item.isShowRedPoint = count > 0
                            break
                        }
                    }
                    self.tableView .reloadData()
                }
            }
        }
    }
    
    @objc func clearUnreadBadge() {
        DispatchQueue.main.async {
            for item in self.items {
                if item.type == .myMessage {
                    item.isShowRedPoint = false
                    break
                }
            }
            self.tableView .reloadData()
        }
    }
}

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 53.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if (indexPath.row >= items.count) { return }
        
//#if DEBUG
//        let vc = YHCodeSueecssWithVideoBkgViewController()
//        vc.phoneNumber = "15818743775"
//        self.navigationController?.pushViewController(vc)
//        return
//#endif
        
        if !checkLogin() {
            return
        }
        
        
        let item: PersonalModuleItem = items[indexPath.row]
        switch item.type {
        case .myMessage://我的消息
            printLog("我的消息")
            goTabBarBy(tabType: .message)
        case .scoreCenter:////积分中心
            printLog("积分中心")
            if let param = YHLoginManager.shared.userModel?.token,param.count>5 {
                printLog(param)
                var token : String = param
                
                var url = YHBaseUrlManager.shared.curH5URL() + "superApp/integral"
                let addtionString = randomAlphanumericString(6)//随机6个字母或者数字
                let indexToInsert = token.index(token.startIndex, offsetBy: 6) //插入位置，这里以第六个字符后面为例
                token.insert(contentsOf: addtionString, at: indexToInsert)
                url = url + "?param=" + token
                
                let vc = YHHomeWebViewController()
                vc.vcTitle = "积分中心"
                vc.url = url
                self.navigationController?.pushViewController(vc)
            }
        case .myTestCode://我的测评码
            printLog("我的测评码")
            let vc = YHHomeWebViewController()
            vc.vcTitle = "香港身份测评码"
            vc.showSavePicBottomFlag = true
            vc.url = "https://cdn-public.galaxy-immi.com/app/cepingma.png"
            self.navigationController?.pushViewController(vc)
        case .appointGalaxyBay://预约银河湾
            printLog("预约银河湾")
            let vc = YHHomeWebViewController()
            vc.vcTitle = "预约银河湾"
            vc.url = "https://upload.cdn.galaxy-immi.com/sell/product/images/page-1686138671996.png"
            self.navigationController?.pushViewController(vc)
        default:
            printLog("不需要响应")
        }
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 1.0
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 1.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        return UIView()
    }
}

extension YHMyViewController {
    
    func randomAlphanumericString(_ length: Int) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        let randomString = (0..<length).map{ _ in String(letters.randomElement()!) }.reduce("", +)
        return randomString
    }
    
    @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 =  "登录/注册"
        }
        headerView.updateAvatar()
        requestLikeCollectionCount()
        getTotalUnreadMsgCount()
        checkSettingRedPoint()
    }
}
