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

import UIKit
import JXSegmentedView
import dsBridge
@preconcurrency import WebKit

//MARK: - 生命周期函数 及变量
class YHHomeHoldViewPageViewController: YHBaseViewController, WKUIDelegate, WKNavigationDelegate {
    private var needShowManagerTipsView = false
    private var didFirstLoadYhManager = false
    var viewModel = YHHomePageViewModel()
    var webview = DWKWebView()
    var arrItemTitles: [String] = []
    
    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
    
    let loginViewModel = YHLoginViewModel()
    
    var needDelete: Bool = false
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
//        getConfigData()
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    }
    
    // MARK: - WKUIDelegate
    
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        // 实现非安全链接的跳转。如果目标主视图不为空,则允许导航
        if !(navigationAction.targetFrame?.isMainFrame != nil) {
            webview.load(navigationAction.request)
        }
        return nil
    }
    
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
    }
    
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        printLog("\(error.localizedDescription)")
    }

    
    func getConfigData() {
        viewModel.getHomeInfo {[weak self] success, error in
            guard let self = self else { return }
            if success {
                arrItemVCs.removeAll()
                var tempTitle: [String] = []
                let dataSource = self.viewModel.homeInfoModel?.tab_list ?? []
                for item in dataSource {
                    tempTitle.append(item.name)
                    if item.id == 1 {
                        //推荐
                        let vc = homePageVC
                        vc.configModel = self.viewModel.homeInfoModel
                        arrItemVCs.append(vc)
                    }
                    if item.id == 2 {
                        //
                        let vc = YHHomeIdentityViewController()
                        arrItemVCs.append(vc)
                    }
                    if item.id == 3 {
                        let vc = YHLifeViewController()
                        vc.hideFlag = false
                        arrItemVCs.append(vc)
                    }
                    if item.id == 4 {
                        //相关资讯
                        let vc = YHHomeInformationViewController()
                        arrItemVCs.append(vc)
                    }
                    if item.id == 5 {
                        //银河甄选
                        let vc = YHSelectViewController()
                        vc.hideFlag = true
                        arrItemVCs.append(vc)
                    }
                    if item.id == 6 {
                        //直播
                        let vc = YHLifeViewController()
                        vc.hideFlag = true
                        arrItemVCs.append(vc)
                    }
                }
                if tempTitle == arrItemTitles {
                    return
                }
                arrItemTitles = tempTitle
                //segmentedViewDataSource一定要通过属性强持有！！！！！！！！！
                segmentedView.removeFromSuperview()
                segmentedDataSource.titles = self.arrItemTitles
                segmentedView.dataSource = segmentedDataSource
                segmentedView.delegate = self
                view.addSubview(segmentedView)
                listContainerView.removeFromSuperview()
                segmentedView.listContainer = listContainerView
                view.addSubview(listContainerView)
                segmentedView.reloadData()
            } else {
                arrItemVCs.removeAll()
                let tempTitle: [String] = ["推荐", "身份", "生活", "咨询攻略"]
                let dataSource = self.viewModel.homeInfoModel?.tab_list ?? []
                for item in 0..<4 {
                    if item == 0{
                        let vc = homePageVC
                        vc.configModel = self.viewModel.homeInfoModel
                        arrItemVCs.append(vc)
                    }
                    if item == 1 {
                        let vc = YHHomeIdentityViewController()
                        arrItemVCs.append(vc)
                    }
                    if item == 2 {
                        let vc = YHLifeViewController()
                        vc.hideFlag = false
                        arrItemVCs.append(vc)
                    }
                    if item == 3 {
                        let vc = YHHomeInformationViewController()
                        arrItemVCs.append(vc)
                    }
                }
                if tempTitle == arrItemTitles {
                    return
                }
                arrItemTitles = tempTitle
                //segmentedViewDataSource一定要通过属性强持有！！！！！！！！！
                segmentedView.removeFromSuperview()
                segmentedDataSource.titles = self.arrItemTitles
                segmentedView.dataSource = segmentedDataSource
                segmentedView.delegate = self
                view.addSubview(segmentedView)
                listContainerView.removeFromSuperview()
                segmentedView.listContainer = listContainerView
                view.addSubview(listContainerView)
                segmentedView.reloadData()
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        //处于第一个item的时候，才允许屏幕边缘手势返回
        navigationController?.interactivePopGestureRecognizer?.isEnabled = (segmentedView.selectedIndex == 0)
        
        YHOSSManager.share.getOSSID()
        
        getTotalUnreadMsgCount()
        
        updateDefaultSearchKeyWord()
        
        if needReloadDataFlag {
            needReloadDataFlag = false
            homePageVC.requestOrder()
        }
        
        checkHomeAlertView()
        getCurrentUserInfo()
        getConfigData()
        NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(_:)), name: YhConstant.YhNotification.backToHomeNotification, object: nil)
    }
    
    @objc func handleNotification(_ notification: Notification) {
        if let userInfo = notification.userInfo, let value = userInfo["value"] as? Int {
            segmentedView.selectItemAt(index: value)
        }
    }
    
    deinit {
            // 移除观察者
            NotificationCenter.default.removeObserver(self)
        }
    
    private func isViewVisibleOnScreen(view: UIView) -> Bool {
        let viewFrame = view.convert(view.bounds, to: UIScreen.main.coordinateSpace)
        let screenFrame = UIScreen.main.bounds
        return viewFrame.intersects(screenFrame) && viewFrame.maxY <= screenFrame.maxY
    }

    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 showFlowAlertView(callback:@escaping ((_ showFlag: Bool)->())) {
        if !YHLoginManager.shared.isLogin() {
            callback(false)
            return
        }
        
        princleVM.getPrincleStatus { success, error in
            if success {
                guard let model = self.princleVM.alertStatusModel else {
                    callback(false)
                    return
                }
                if let vc = UIApplication.shared.keyWindow?.rootViewController as? YHTabBarViewController {
                    if vc.selectedIndex != 0 {
                        callback(false)
                        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()
                } else if model.type == 20 {
                    //签约用户新人指引
                    if self.didFirstLoadYhManager {
                        self.showYHManagerTipsView()
                    } else {
                        self.needShowManagerTipsView = true
                    }
                } else {
                    callback(false)
                    return
                }
                callback(true)
            }
        }
    }
    
    
    func getUatRules() {
        DispatchQueue.global().async {
            //灰度规则配置
            YHUatHelper.shared.loadUatData()
        }
    }
    
    @objc func clickMsgitem() {
        needReloadDataFlag = true
    }
    
    @objc func didRefreshMessageCount() {
        getTotalUnreadMsgCount()
    }
    
    // 请求未读消息总数
    @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 {
                var unreadCount = self.msgViewModel.unreadTotalCount
                if YHButlerServiceManager.shared.isUatAllowed() {
                    unreadCount = self.msgViewModel.unreadTotalCount + YHButlerServiceManager.shared.unreadCount
                }
                self.msgUnreadView.unreadCount = unreadCount

            }
        }
    }
    
    @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)
        
        NotificationCenter.default.addObserver(self, selector: #selector(didRefreshMessageCount), name: YhConstant.YhNotification.didQiYuUnReadMsgCountChangeNotification, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(didJumpToIdentityTab), name: YhConstant.YhNotification.didJumpToHomePageIdentityTabNotification, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(didJumpToNewsTab), name: YhConstant.YhNotification.didJumpToHomePageNewsTabNotification, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(didJumpToLifeTab), name: YhConstant.YhNotification.didJumpToHomePageLifeTabNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(didLoadYhManager), name: YhConstant.YhNotification.didLoadYhManagerNotification, object: nil)
        
        view.addSubview(searchView)
        searchView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_safeAreaInsetsTop() + 6)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(YHHomeSearchView.viewH)
        }
        // 隐藏消息铃铛UI
//        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一定要通过属性强持有！！！！！！！！！
        webview = DWKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 0))
        webview.navigationDelegate = self
        let current = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/preload/preload"

        if let url = URL(string: current) {
            let request = URLRequest(url: url)
            webview.load(request)
        }
        // 添加wkwebview
        self.view.addSubview(webview)
    }
    // 跳转到资讯tab
    @objc func didJumpToNewsTab() {
        jumpToItemIndex(itemIndex: 3)
    }
    
    @objc func didJumpToLifeTab() {
        jumpToItemIndex(itemIndex: 2)
    }
    
    @objc func didJumpToIdentityTab() {
        jumpToItemIndex(itemIndex: 1)
    }
    
    @objc func didLoadYhManager() {
        if needShowManagerTipsView {
            needShowManagerTipsView = false
            showYHManagerTipsView()
        }
        didFirstLoadYhManager = true
    }
    
    
    func jumpToItemIndex(itemIndex : Int) {
        self.segmentedView.selectItemAt(index: itemIndex)
        self.listContainerView.didClickSelectedItem(at: itemIndex)
    }
    
    func getCurrentUserInfo() {
        if !YHLoginManager.shared.isLogin() {
            return
        }
        if let mobile = YHLoginManager.shared.userModel?.mobile, !mobile.isEmpty {
            return
        }
        self.loginViewModel.getUserInfo { success, error in
            
        }
    }
}

//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 || index == 3 { // 点击服务tab或社区tab
            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
            }
        }
        
        if index == 2 { // AI港小宝
            if !YHLoginManager.shared.isLogin() {
                YHOneKeyLoginManager.shared.oneKeyLogin()
                return false
            }
            let vc = YHAITabViewController()
            UIViewController.current?.navigationController?.pushViewController(vc)
            return false
        }
        return true
    }
}

//MARK: 弹窗相关的逻辑
private extension YHHomeHoldViewPageViewController {
    // 1、强升级 弹窗 > 2、签约用户新人指引 > 3、原则批/正式批 弹窗 > 4、建议更新
    func checkHomeAlertView() {
        self.showFlowAlertView { showFlag in
            if !showFlag {
                self.requestAppNewVersion()
            }
        }
    }
    
    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 = {
                }
            }
        }
    }
    
    //银河管家 引导弹窗
    func showYHManagerTipsView() {
        if YHUatHelper.shared.getUatModuleStatusBy(module: .QiYu_Service) != 1 {
            printLog("非目标用户")
            return
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            //判断是否在 首页tab
            if let vc = UIApplication.shared.keyWindow?.rootViewController as? YHTabBarViewController {
                if vc.selectedIndex != 0 {
                    return
                }
            }
            
            //判断是否在 首页-推荐tab
            if self.segmentedView.selectedIndex != 0 {
                return
            }
            
//            self.princleVM.postAlertStatus(20) { success, error in
//            }
            
            //不在屏幕内 就上移  200px
            var offSetY : CGFloat = 0.0
            
            let viewFrame = self.homePageVC.homeHeaderView.orderTipsView.mgrItem.convert(self.homePageVC.homeHeaderView.orderTipsView.mgrItem.bounds, to: UIScreen.main.coordinateSpace)
            
            if viewFrame.origin.y < 250.fix {
                offSetY = -abs(viewFrame.origin.y) - (KScreenHeight / 2)
            } else {
                offSetY = self.isViewVisibleOnScreen(view: self.homePageVC.homeHeaderView.orderTipsView.mgrItem) ? 0 : 200.0
            }
            var point = self.homePageVC.homeCollectView.contentOffset
            point.y += offSetY
            self.homePageVC.homeCollectView.setContentOffset(point, animated: false)
            
            self.homePageVC.homeCollectView.isScrollEnabled = false
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
                let viewFrame = self.homePageVC.homeHeaderView.orderTipsView.mgrItem.convert(self.homePageVC.homeHeaderView.orderTipsView.mgrItem.bounds, to: UIScreen.main.coordinateSpace)
                
                let view = YHManagerFuncGuildeCheckView.sheetView()
                view.itemRect = viewFrame
                view.block = { [weak self] in
                    guard let self = self else {
                        return
                    }
                    self.princleVM.postAlertStatus(20) { success, error in
                    }
                    self.homePageVC.gotoYinHeMgrVC()
                }
                view.show()
                
                self.homePageVC.homeCollectView.isScrollEnabled = true
            }
        }
        
    }
}
