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

import UIKit
import SnapKit
import SafariServices



enum YHPersonalModuleItemType: Int {
    case none = 0
    case myCard
    case myMessage
    case myProgress
    case myActivity
    case scoreCenter
    case inviteFriends
    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//隐私协议
    case myOrder //我的订单 双十一订单入口
    case mycart //我的订单 双十一订单入口
    case serviceStep
    //case liveEntryTest //直播入口
}

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

class YHMyViewController: YHBaseViewController, ConstraintRelatableTarget {
    
    let likeViewModel: YHMyLikeViewModel = YHMyLikeViewModel()
    let msgViewModel: YHMsgViewModel = YHMsgViewModel()
    let loginViewModel = YHLoginViewModel()
    let userViewModel = YHMatchUserViewModel()
    
    private lazy var princleVM : YHPrincleViewModel = {
        let vm = YHPrincleViewModel()
        return vm
    }()

    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
    }()
    
//    var items: [PersonalModuleItem] = {
//        var arrData = [
//            PersonalModuleItem(icon: "mine_item_card", title: "我的名片".local, type:.myCard),
//            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),
//            PersonalModuleItem(icon: "mine_item_activity", title: "我的活动".local, type:.myActivity),
//            PersonalModuleItem(icon: "mine_item_about_us", title: "关于我们".local, type:. aboutUs)
//        ]
//        return arrData
//    }()
    
    var items: [PersonalModuleItem] = []
    
    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 = YHMyLikeActivityViewController()
            vc.myDefaultNavItemIndex = 0
            self.navigationController?.pushViewController(vc)
        }
        view.collectClick = {
            [weak self] in
            guard let self = self else { return }
            if !checkLogin() { return }
            let vc = YHMyLikeActivityViewController()
            vc.myDefaultNavItemIndex = 1
            self.navigationController?.pushViewController(vc)
            print("收藏")
        }
        view.recentScanClick = {
            [weak self] in
            guard let self = self else { return }
            if !checkLogin() { return }
            let vc = YHMyLikeActivityViewController()
            vc.myDefaultNavItemIndex = 2
            self.navigationController?.pushViewController(vc)
            print("最近浏览")
        }
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initView()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        loadItems()
        
        requestLikeCollectionCount()
        getTotalUnreadMsgCount()
        checkSettingRedPoint()
        headerView.updateAvatar()
        requstUserBasicInfo()
        showAlert()
    }
    
//    override func viewDidAppear(_ animated: Bool) {
//        super.viewDidAppear(animated)
//        showYHManagerGuideView(self.navigationController)
//    }
    
    private func showAlert() {
        guard YHLoginManager.shared.isLogin() else {
            return
        }
        princleVM.getPrincleStatus { [weak self] success, error in
            if success {
                guard let self = self else {
                    return
                }
                guard let model = self.princleVM.alertStatusModel else {
                    return
                }
                
                if model.type == 20 {
                    self.showYHManagerGuideView(self.navigationController)
                }
            }
        }
    }
    
    @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)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(didRevUatParam), name: YhConstant.YhNotification.didRevUatParam, 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 {
                    var unreadCount = self.msgViewModel.unreadTotalCount
                    if YHButlerServiceManager.shared.isUatAllowed() {
                        unreadCount = self.msgViewModel.unreadTotalCount + YHButlerServiceManager.shared.unreadCount
                    }
                    for item in self.items {
                        if item.type == .myMessage {
                            item.isShowRedPoint = unreadCount > 0
                            break
                        }
                    }
                    self.tableView .reloadData()
                }
            }
        }
    }
    
    
    @objc func didRevUatParam() {
        loadItems()
    }
    
    @objc func clearUnreadBadge() {
        DispatchQueue.main.async {
            for item in self.items {
                if item.type == .myMessage {
                    item.isShowRedPoint = false
                    break
                }
            }
            self.tableView .reloadData()
        }
    }
    
    //uat 添加items
    func loadItems() {
        
        items.removeAll()
        
        if YHUatHelper.shared.getUatModuleStatusBy(module: .Mine_MyCard) == 1 {
            let item = PersonalModuleItem(icon: "mine_item_card", title: "我的名片".local, type:.myCard)
            items.append(item)
        }
        
        if let configModel = YHConfigManager.shared.reqVM.configModel,configModel.is_integral_open {
            let item = PersonalModuleItem(icon: "mine_item_myOrder", title: "我的订单".local, type:.myOrder)
            items.append(item)
        }
        
        if let configModel = YHConfigManager.shared.reqVM.configModel,configModel.is_integral_open {
            let item = PersonalModuleItem(icon: "mine_item_service_center", title: "服务进度".local, type:.serviceStep)
            items.append(item)
        }
        
        if let configModel = YHConfigManager.shared.reqVM.configModel,configModel.is_integral_open {
            let item = PersonalModuleItem(icon: "mine_item_cart", title: "购物车".local, type:.mycart)
            items.append(item)
        }
        
        do {
            let item = PersonalModuleItem(icon: "mine_item_msg", title: "我的消息".local, type:.myMessage)
            items.append(item)
        }
        
        if let configModel = YHConfigManager.shared.reqVM.configModel,configModel.is_integral_open {
            if YHUatHelper.shared.getUatModuleStatusBy(module: .Mine_IntegralCenter) == 1 {
                let item = PersonalModuleItem(icon: "mine_item_scoreCenter", title: "积分中心".local, type:.scoreCenter)
                items.append(item)
            }
        }
        
        if YHUatHelper.shared.getUatModuleStatusBy(module: .Mine_EvaluationCode) == 1 {
            let item = PersonalModuleItem(icon: "mine_item_code", title: "我的测评码".local, type:.myTestCode)
            items.append(item)
        }
        
        
        if YHUatHelper.shared.getUatModuleStatusBy(module: .Mine_AboutYinHeHarbour) == 1 {
            let item = PersonalModuleItem(icon: "mine_item_appoint", title: "关于银河湾".local, type:.appointGalaxyBay)
            items.append(item)
        }
        
        if YHUatHelper.shared.getUatModuleStatusBy(module: .Mine_MyActivity) == 1 {
            let item = PersonalModuleItem(icon: "mine_item_activity", title: "我的活动".local, type:.myActivity)
            items.append(item)
        }
        
        if YHUatHelper.shared.getUatModuleStatusBy(module: .Mine_AboutUS) == 1 {
            let item = PersonalModuleItem(icon: "mine_item_about_us", title: "关于我们".local, type: .aboutUs)
            items.append(item)
        }
        
        
//        let item = PersonalModuleItem(icon: "mine_item_about_us", title: "直播测试入口".local, type: .liveEntryTest)
//        items.append(item)
        
        
        
        
        
        
        
        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 !checkLogin() {
            return
        }
        
        let item: PersonalModuleItem = items[indexPath.row]
        switch item.type {
        case .myCard://我的名片
            if let userId = YHLoginManager.shared.userModel?.id, !userId.isEmpty {
                let vc = YHNameCardViewController()
                vc.userId = userId
                self.navigationController?.pushViewController(vc)
            } else {
                YHHUD.show(.progress(message: "加载中..."))
                self.loginViewModel.getUserId {
                    [weak self] uid in
                    YHHUD.hide()
                    guard let self = self else { return }
                    if !uid.isEmpty {
                        YHLoginManager.shared.userModel?.id = uid
                        let vc = YHNameCardViewController()
                        vc.userId = uid
                        self.navigationController?.pushViewController(vc)
                    }
                }
            }
        case .myMessage://我的消息
            printLog("我的消息")
            goToMessagePage()
            
        case .scoreCenter:////积分中心
            printLog("积分中心")
            if let param = YHLoginManager.shared.userModel?.token,param.count>5 {
                printLog(param)
                var url = YHBaseUrlManager.shared.curH5URL() + "superApp/integral"
                url = url + "?param=" + YHLoginManager.shared.h5Token
                
                let vc = YHH5WebViewVC()
                vc.title = "积分中心"
                vc.navTitle = "积分中心"
                vc.url = url
                vc.isFullScreenFlag = false
                vc.isSupportWebviewInterBackFlag = true
                self.navigationController?.pushViewController(vc)
            }
        case .myTestCode://我的测评码
            printLog("我的测评码")
            let vc = YHHomeWebViewController()
            vc.title = "香港身份测评码"
            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 = YHListViewController()
            self.navigationController?.pushViewController(vc)
        case .myActivity:
            printLog("我的活动")
            let vc = YHActivityListViewController()
            vc.type = 1
            self.navigationController?.pushViewController(vc)
        case .aboutUs:
            let vc = YHAboutGalaxyViewController()
            self.navigationController?.pushViewController(vc)
        case .myOrder:
//            我的订单
            if let token = YHLoginManager.shared.userModel?.token,token.count > 5 {
                var url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/order/my"
                url = url + "?param=" + YHLoginManager.shared.h5Token
                printLog("URL: \(url)")
                let vc = YHH5WebViewVC()
                vc.url = url
                vc.isFullScreenFlag = false
                vc.navTitle = "我的订单"
                vc.isSupportWebviewInterBackFlag = true
                UIViewController.current?.navigationController?.pushViewController(vc)
            }
        case .mycart:
//            我的订单
            if let token = YHLoginManager.shared.userModel?.token,token.count > 5 {
                var url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/goods/cart"
                url = url + "?param=" + YHLoginManager.shared.h5Token
                printLog("URL: \(url)")
                var tUrl = url
                if !url.contains("navigationH=") {
                    tUrl = url + "?navigationH=\(k_Height_NavigationtBarAndStatuBar)"
                    if url.contains("?") {
                        tUrl = url + "&navigationH=\(k_Height_NavigationtBarAndStatuBar)"
                    }
                }
                let vc = YHH5WebViewVC()
                vc.url = tUrl
                vc.isFullScreenFlag = false
                vc.navTitle = "购物车"
                vc.isSupportWebviewInterBackFlag = true
                UIViewController.current?.navigationController?.pushViewController(vc)
            }
        case .serviceStep:
            UIViewController.current?.tabBarController?.selectedIndex = 1
        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 {
    
    @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()
        requstUserBasicInfo()
    }
    
    func requstUserBasicInfo() {
        if YHLoginManager.shared.isLogin() {
            if isEmptyString(YHLoginManager.shared.userModel?.id) {
                self.loginViewModel.getUserId {
                    [weak self] uid in
                    guard let self = self else { return }
                    requestUserAvatar()
                }
            } else {
                requestUserAvatar()
            }

        } else {
            headerView.updateAvatar()
        }
    }
    
    func requestUserAvatar() {
        if let uid = YHLoginManager.shared.userModel?.id, !uid.isEmpty {
            self.userViewModel.getUserNameCardInfo(uid: uid) {
                [weak self] success, error in
                guard let self = self else { return }
                let url = URL(string: self.userViewModel.nameCardInfo.avatar)
                self.headerView.avarImgView.kf.setImage(with: url, placeholder: UIImage(named: "people_head_default"))
            }
        }
    }
    
}

extension YHMyViewController {
    //MARK: - 跳银河管家
    
    private func showYHManagerGuideView(_ navigationController: UINavigationController?) {
        if YHUatHelper.shared.getUatModuleStatusBy(module: .QiYu_Service) != 1 {
            printLog("非目标用户")
            return
        }
        if let key = YHButlerServiceManager.shared.guideWindowShowedKey, YHButlerServiceManager.shared.didShowWindowDict[key] == true {
            return
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
            if let key = YHButlerServiceManager.shared.guideWindowShowedKey {
                YHButlerServiceManager.shared.didShowWindowDict[key] = true
            }
            let view = YHConversationGuideView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight))
            view.checkButtonEvent = { [weak self] in
                guard let self = self else {
                    return
                }
                self.princleVM.postAlertStatus(20) { success, error in
                }
                self.gotoYinHeManager(navigationController)
            }
            view.show()
        }
    }
    
    private func gotoYinHeManager(_ navigationController: UINavigationController?) {
        guard let userId = YHLoginManager.shared.userModel?.id, userId.count > 0 else {
            return
        }
        //YHAnalytics.track("APP_HomeTab_IntelligentAssistant")
        YHButlerServiceManager.shared.gotoButlerServiceSessionVC(navigationController: navigationController, completion: { _ in
        })
    }
}
