//
//  YHHomeHoldViewPageViewController.swift
//  galaxy
//
//  Created by davidhuangA on 2024/7/8.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import JXSegmentedView


//MARK: - 生命周期函数 及变量
class YHHomeHoldViewPageViewController: YHBaseViewController {
    
    let arrItemTitles = ["推荐","身份","生活","资讯"]
    
    var arrItemVCs : [YHBaseViewController] = []
        
    lazy var segmentedView : JXSegmentedView = {
       let view = JXSegmentedView(frame: CGRect(x: 0, y: k_Height_safeAreaInsetsTop(), width: KScreenWidth, height: 44))
        view.backgroundColor = .clear
        return view
    }()
    
    lazy var segmentedDataSource: JXSegmentedTitleDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.isTitleColorGradientEnabled = false
        dataSource.titles = arrItemTitles
        
        dataSource.titleNormalFont = UIFont.PFSC_M(ofSize: 16)
        dataSource.titleNormalColor = UIColor.yhGreyColor
        
        dataSource.titleSelectedFont = UIFont.PFSC_M(ofSize: 21)
        dataSource.titleSelectedColor = .mainTextColor
        
        dataSource.isItemSpacingAverageEnabled = false
        dataSource.itemWidth = JXSegmentedViewAutomaticDimension
        dataSource.itemSpacing = 28.0
        return dataSource
    }()
    
    //首页内容ViewController
    lazy var homePageVC: YHHomePageViewController = {
        let vc = YHHomePageViewController()
        return vc
    }()
    
    //分类title 所对应的VC
    lazy var listContainerView: JXSegmentedListContainerView! = {
        let view = JXSegmentedListContainerView(dataSource: self, type: .scrollView)
        view.backgroundColor = .clear
        return view
    }()
    
    var tapTimestamp : CFAbsoluteTime = -10.0
    
    var needReloadDataFlag : Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        //处于第一个item的时候，才允许屏幕边缘手势返回
        navigationController?.interactivePopGestureRecognizer?.isEnabled = (segmentedView.selectedIndex == 0)
        
        
        YHOSSManager.share.getOSSID()
        
        getTotalUnreadMsgCount()
        
        updateDefaultSearchKeyWord()
        
        requestAppNewVersion()
        
        
        if needReloadDataFlag {
            needReloadDataFlag = false
            homePageVC.requestOrder()
        }
        
//        DispatchQueue.main.async {
//            self.getAlertStatus()
//        }
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        //离开页面的时候，需要恢复屏幕边缘手势，不能影响其他页面
        navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        let offy = k_Height_safeAreaInsetsTop() + 6 + YHHomeSearchView.viewH + 6
        segmentedView.frame = CGRect(x: 0, y: offy, width: view.bounds.size.width, height: 44)
        
        let offy1 = offy + 44
        listContainerView.frame = CGRect(x: 0, y: offy1, width: view.bounds.size.width, height: view.bounds.size.height - offy1 - k_Height_TabBar)
    }
    
    lazy var searchView: YHHomeSearchView = {
        let view = YHHomeSearchView()
        let tap = UITapGestureRecognizer(target: self, action: #selector(didSearchBarClicked))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var msgUnreadView:YHMessageBellView = {
        let view = YHMessageBellView.bellView()
        return view
    }()
    
    
    lazy var msgViewModel:YHMsgViewModel = {
        let vm = YHMsgViewModel()
        return vm
    }()
    
    
    
    lazy var princleVM : YHPrincleViewModel = {
        let vm = YHPrincleViewModel()
        return vm
    }()
}

//MARK: - 内部函数
extension YHHomeHoldViewPageViewController {
    //获取原则批、正式批的弹窗状态
    func getAlertStatus() {
        
        if !YHLoginManager.shared.isLogin() {
            return
        }
        
        
        princleVM.getPrincleStatus { success, error in
            if success {
                guard let model = self.princleVM.alertStatusModel else {
                    return
                }
                
                
                if let vc = UIApplication.shared.keyWindow?.rootViewController as? YHTabBarViewController {
                    if vc.selectedIndex != 0 {
                        return
                    }
                }
                
                if model.type == 1 {
                    //正式弹窗
                    self.princleVM.postAlertStatus(15) { success, error in
                    }
                    
                    
                    let view = YHOffivialApprovalSuccessCheckView.sheetView()
                    view.days = model.date
                    view.show()
                    
                    view.block = { tag in
                        if tag == 0 {
                            //跳转 正式批结果页面
                            //正式批已获批~
                            let vc = YHOfficialApprovalResultVC()
                            vc.isFromHomeAlertViewFlag = true
                            self.navigationController?.pushViewController(vc)
                        }
                    }
                } else if model.type == 2 {
                    
                    self.princleVM.postAlertStatus(14) { success, error in
                    }
                    
                    //原则批弹窗
                    let view = YHPrincipleApprovedAlertView.alertView()
                    view.lookBlock = {
                        if let orderID = UserDefaults.standard.value(forKey: "orderIdForPreview") as? Int {
                            let vc = YHPrincipleApprovedWaitSubmitVC()
                            vc.orderId = orderID
                            self.navigationController?.pushViewController(vc)
                            
                        } else {
                            YHHUD.flash(message: "订单号为空")
                        }
                    }
                    view.show()
                }
            }
        }
    }
    
    
    func getUatRules() {
        DispatchQueue.global().async {
            //灰度规则配置
            YHUatHelper.shared.loadUatData()
        }
    }
    
    @objc func clickMsgitem() {
        needReloadDataFlag = true
    }
    
    @objc func didRefreshMessageCount() {
        getTotalUnreadMsgCount()
    }
    
    func requestAppNewVersion() {
        if YHConfigManager.shared.loadNewDataFlag == false {
            YHConfigManager.shared.loadConfigData {
                [weak self] in
                guard let self = self else { return }
                self.showNewVersionAlertView()
            }
        } else {
            showNewVersionAlertView()
        }
    }
    
    func showNewVersionAlertView() {
        let isNeedShowAlert =  YHAppVersionManager.shared.needShowAlertViewOfSuggestVersionUpdate()
        if isNeedShowAlert {
            if let configModel = YHConfigManager.shared.reqVM.configModel {
                let alertView = YHFindAppNewVersionView.alertView(version: configModel.max_version)
                let arr = configModel.suggest_updating_msg.components(separatedBy: "$")
                alertView.updateContentArray(arr)
                alertView.show()
                alertView.cancleBlock = {
                    self.getAlertStatus()
                }
            }
        } else {
            self.getAlertStatus()
        }
    }
    
    // 请求未读消息总数
    @objc func getTotalUnreadMsgCount() {
        if !YHLoginManager.shared.isLogin() {
            return
        }
        
        self.msgViewModel.requestTotalUnreadMsgCount {
            [weak self] success, error in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.msgUnreadView.unreadCount = self.msgViewModel.unreadTotalCount
            }
        }
    }
    
    @objc func clearUnreadBadge() {
        DispatchQueue.main.async {
            self.msgUnreadView.unreadCount = 0
        }
    }
    
    @objc func loginSuccess() {
        homePageVC.getData()
    }
    
    @objc func logoutSuccess() {
        self.msgUnreadView.unreadCount = 0
        homePageVC.getData()
    }
    
    @objc func revMsg() {
        homePageVC.requestOrder()
    }
    
    func updateDefaultSearchKeyWord() {
        var placeHolder = "香港身份"
        if isHaveLocalSearchRecords() {
            let latestValidSearchWord = getLatestValidSearchWord()
            if !latestValidSearchWord.isEmpty {
                placeHolder = latestValidSearchWord
            }
        }
        searchView.placeHolder = placeHolder
    }
    
    @objc func didSearchBarClicked() {
        let vc = YHSearchInfomationVC()
        vc.searchPlaceHolder = searchView.placeHolder
        printLog("placeHolder: \(searchView.placeHolder)")
        self.navigationController?.pushViewController(vc)
    }
    
    func setupUI() {
        
        gk_navigationBar.isHidden = false
        gk_navigationBar.isHidden = true
        view.backgroundColor = .white
        
        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(revMsg), name: YhConstant.YhNotification.didRevMsgNotifiction, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(clearUnreadBadge), name: YhConstant.YhNotification.didMarkAllMessagesReadedNotifiction, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(didRefreshMessageCount), name: YhConstant.YhNotification.didRequestUnreadMsgTotalCountNotification, object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(clickMsgitem), name: YhConstant.YhNotification.clickHomeMsgNotifiction, object: nil)
        
        
        for i in 0..<arrItemTitles.count {
            if i == 0 {
                //首页
                let vc = homePageVC
                arrItemVCs.append(vc)
            } else if i == 1 {
                //身份
                let vc = YHHomeIdentityViewController()
                arrItemVCs.append(vc)
            } else if i == 2 {
                //生活
                let vc = YHLifeViewController()
                arrItemVCs.append(vc)
            } else if i == 3 {
                //资讯
                let vc = YHHomeInformationViewController()
                arrItemVCs.append(vc)

            }
        }
        
        view.addSubview(searchView)
        searchView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_safeAreaInsetsTop() + 6)
            make.left.equalTo(20)
            make.height.equalTo(YHHomeSearchView.viewH)
        }
        
        view.addSubview(msgUnreadView)
        msgUnreadView.snp.makeConstraints { make in
            make.width.equalTo(YHMessageBellView.width)
            make.height.equalTo(YHMessageBellView.height)
            make.left.equalTo(searchView.snp.right)
            make.right.equalToSuperview()
            make.centerY.equalTo(searchView)
        }
        
        //segmentedViewDataSource一定要通过属性强持有！！！！！！！！！
        segmentedView.dataSource = segmentedDataSource
        segmentedView.delegate = self
        view.addSubview(segmentedView)

        segmentedView.listContainer = listContainerView
        view.addSubview(listContainerView)
        
    }
    

    
    func jumpToItemIndex(itemIndex : Int) {
        self.segmentedView.selectItemAt(index: itemIndex)
    }
}

//MARK: - JXSegmentedViewDelegate
extension YHHomeHoldViewPageViewController: JXSegmentedViewDelegate {
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        navigationController?.interactivePopGestureRecognizer?.isEnabled = (segmentedView.selectedIndex == 0)
        self.segmentedView.reloadDataWithoutListContainer()
    }
}

//MARK: - JXSegmentedListContainerViewDataSource
extension YHHomeHoldViewPageViewController: JXSegmentedListContainerViewDataSource {
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        if let titleDataSource = segmentedView.dataSource as? JXSegmentedBaseDataSource {
            return titleDataSource.dataSource.count
        }
        return 0
    }

    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        return arrItemVCs[index] as! JXSegmentedListContainerViewListDelegate
    }
}

//MARK: - UITabBarControllerDelegate
extension YHHomeHoldViewPageViewController : UITabBarControllerDelegate {
    
    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        let doubleTapInterval : CGFloat = 0.3
        
        if tabBarController.selectedIndex == 0 {
            let timestamp = CFAbsoluteTimeGetCurrent()
            printLog(timestamp - self.tapTimestamp)
            if timestamp - self.tapTimestamp < doubleTapInterval {
                homePageVC.goTop()
            }
            self.tapTimestamp = timestamp
        }
    }
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        guard let index = tabBarController.viewControllers?.firstIndex(of: viewController) else {
            return false
        }
        if index == 1 {
            if YHLoginManager.shared.isLogin() {
                return true
            } else {
                YHOneKeyLoginManager.shared.oneKeyLogin()
                YHLoginManager.shared.loginSuccessActionBlock = {[weak self] in
                    guard self != nil else { return }
                    tabBarController.selectedIndex = index
                    YHLoginManager.shared.loginSuccessActionBlock = nil
                }
                return false
            }
        }
        return true
    }
}
