//
//  YHAITabViewController.swift
//  galaxy
//
//  Created by Dufet on 2024/11/26.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import JXSegmentedView
import IQKeyboardManagerSwift

class YHAITabViewController: YHBaseViewController, UIGestureRecognizerDelegate {
    
    var defaltIndex: Int = 0
    let viewModel = YHAIViewModel()

    let arrItemTitles = ["港小宝", "对话"]
    var arrItemVCs : [YHBaseViewController] = []

    lazy var headerImgView: UIImageView = {
        let v = UIImageView(image: UIImage(named: "ai_product_list_head"))
        return v
    }()
    
    lazy var bgImgView: UIImageView = {
        let v = UIImageView(image: UIImage(named: "ai_chat_bg"))
        v.isHidden = true
        return v
    }()
    
    lazy var segmentedView : JXSegmentedView = {
       let view = JXSegmentedView(frame: CGRect(x: 0, y: k_Height_safeAreaInsetsTop(), width: KScreenWidth, height: 48))
        view.backgroundColor = .clear
        return view
    }()
    
    lazy var segmentedDataSource: JXSegmentedTitleDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.isTitleColorGradientEnabled = true
        dataSource.titles = arrItemTitles
        
        dataSource.titleNormalFont = UIFont.PFSC_M(ofSize: 16)
        dataSource.titleNormalColor = UIColor.init(hex:0x778FB4)
        
        dataSource.titleSelectedFont = UIFont(name: "AlimamaShuHeiTi-Bold", size: 18)
        dataSource.titleSelectedColor = .mainTextColor
        
        dataSource.isItemSpacingAverageEnabled = false
        dataSource.itemWidth = JXSegmentedViewAutomaticDimension
        dataSource.itemSpacing = 28.0
        return dataSource
    }()
    
    //分类title 所对应的VC
    lazy var listContainerView: JXSegmentedListContainerView! = {
        let view = JXSegmentedListContainerView(dataSource: self, type: .scrollView)
        view.backgroundColor = .clear
        return view
    }()
    
    lazy var backBtn: UIButton = {
       let btn = UIButton()
        btn.setImage(UIImage(named: "back_icon"), for: .normal)
        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
        btn.addTarget(self, action: #selector(didBackBtnClicked), for: .touchUpInside)
        return btn
    }()
    
    lazy var cleanBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "msg_clean"), for: .normal)
        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        btn.addTarget(self, action: #selector(didCleanButtonClicked), for: .touchUpInside)
        btn.isHidden = true
        return btn
    }()
    
    lazy var listVC: YHAIServiceListViewController = {
        let vc = YHAIServiceListViewController()
        return vc
    }()
    
    lazy var mainChatVC: YHAIMainChatViewController = {
        let vc = YHAIMainChatViewController()
        return vc
    }()
    
    
    @objc func didBackBtnClicked() {
        
        mainChatVC.bottomInputView.showKeyBoard(false)
        if segmentedView.selectedIndex == 1 { // AI 对话
            // tab切换到港小宝
            self.segmentedView.selectItemAt(index: 0)
            return
        }
        
        self.navigationController?.popViewController(animated: true)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .init(hex:0xDEECFE)
        self.navigationController?.interactivePopGestureRecognizer?.delegate = self
        
        gk_navBarAlpha = 0
        gk_navigationBar.isHidden = true
        createUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //处于第一个item的时候，才允许屏幕边缘手势返回
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = (self.segmentedView.selectedIndex == 0)
        self.gk_interactivePopDisabled = (self.segmentedView.selectedIndex != 0)
        self.gk_fullScreenPopDisabled = (self.segmentedView.selectedIndex != 0)
        requestList()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = (self.segmentedView.selectedIndex == 0)
        self.gk_interactivePopDisabled = (self.segmentedView.selectedIndex != 0)
        self.gk_fullScreenPopDisabled = (self.segmentedView.selectedIndex != 0)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //离开页面的时候，需要恢复屏幕边缘手势，不能影响其他页面
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
        self.gk_interactivePopDisabled = false
        self.gk_fullScreenPopDisabled = false
    }
    
    override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        
        if self.segmentedView.selectedIndex == 0 {
            self.gk_interactivePopDisabled = false
            self.gk_fullScreenPopDisabled = false
            return true
        }
        return false
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    func createUI() {
        
        IQKeyboardManager.shared.isEnabled = false

        NotificationCenter.default.addObserver(self, selector: #selector(didJumoToAIChat(_:)), name: YhConstant.YhNotification.didSwitchToAIChatNotification, object: nil)
        
        view.addSubview(bgImgView)
        view.addSubview(headerImgView)
        
        arrItemVCs.removeAll()
        for i in 0..<arrItemTitles.count {
            if i == 0 { // 银河AI
                arrItemVCs.append(listVC)
                
            } else if i == 1 { // 对话
                arrItemVCs.append(mainChatVC)
            }
        }
        
        //segmentedViewDataSource一定要通过属性强持有！！！！！！！！！
        segmentedView.dataSource = segmentedDataSource
        view.addSubview(segmentedView)

        segmentedView.listContainer = listContainerView
        view.addSubview(listContainerView)
        view.addSubview(cleanBtn)
        
        //分类Title
        segmentedView.dataSource = segmentedDataSource
        segmentedView.delegate = self
        
        //配置指示器
        let indicator = YHAITabIndicatorView()
        indicator.indicatorWidth = 34
        indicator.indicatorHeight = 14
        indicator.indicatorCornerRadius = 0.0
        indicator.verticalOffset = 5
        segmentedView.indicators = [indicator]
        segmentedView.defaultSelectedIndex = defaltIndex
        
        view.addSubview(backBtn)
        backBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.width.height.equalTo(21)
            make.centerY.equalTo(segmentedView)
        }
        
        bgImgView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        headerImgView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(300)
        }
        
        let segmentHeight = 48.0
        segmentedView.snp.makeConstraints { make in
            make.left.equalTo(61-25)
            make.right.equalToSuperview()
            make.top.equalTo(k_Height_safeAreaInsetsTop())
            make.height.equalTo(segmentHeight)
        }
        
        listContainerView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_safeAreaInsetsTop() + segmentHeight)
            make.bottom.equalTo(0)
        }
        
        cleanBtn.snp.makeConstraints { make in
            make.width.height.equalTo(24)
            make.centerY.equalTo(segmentedView)
            make.right.equalToSuperview().offset(-20)
        }
    }
    
    func requestList() {
        viewModel.getAIEntranceList {
            [weak self] success, error in
            guard let self = self else { return }
            self.mainChatVC.robotId = self.viewModel.listModel.mainBotId
            self.listVC.serviceArr.removeAll()
            
            var arrT = self.viewModel.listModel.entranceConfig
            if let configModel = YHConfigManager.shared.reqVM.configModel,configModel.is_integral_open {
//                arrT = self.viewModel.listModel.entranceConfig.filter {
//                    !($0.redirectPath == YHAIJumpPageType.galaxySelect.rawValue)
//                 }
            } else {
                //
                arrT = self.viewModel.listModel.entranceConfig.filter {
                    !($0.redirectPath == YHAIJumpPageType.galaxySelect.rawValue)
                 }
            }
            
            self.listVC.serviceArr.append(contentsOf: arrT)
            self.listVC.collectionView.reloadData()
        }
    }
    
    func jumpToItemIndex(itemIndex : Int) {
        self.segmentedView.selectItemAt(index: itemIndex)
    }
    
    @objc func didJumoToAIChat(_ notify: Notification) {
        
        var showImg = false
        var showKeyBoard = false
        if let dict = notify.object as? [String : Any] {
            if let isShowImg = dict[isNeedShowAutoPictureMsg] as? Bool {
                showImg = isShowImg
            }
            if let isShowKeyBoard = dict[isNeedShowAIChatKeyBoard] as? Bool {
                showKeyBoard = isShowKeyBoard
            }
        }
        
        printLog("SHOW_IMG: \(showImg)")
        mainChatVC.isNeedAutoResponseImage = showImg
        jumpToItemIndex(itemIndex: 1)
        mainChatVC.bottomInputView.showKeyBoard(showKeyBoard)
        
    }
    
    @objc func didCleanButtonClicked() {
        self.mainChatVC.didCleanButtonClicked()
    }
}

extension YHAITabViewController: JXSegmentedViewDelegate {
    
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {

        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = (self.segmentedView.selectedIndex == 0)
        self.gk_interactivePopDisabled = (self.segmentedView.selectedIndex != 0)
        self.gk_fullScreenPopDisabled = (self.segmentedView.selectedIndex != 0)

        if segmentedView.selectedIndex == 1 { // AI对话
            bgImgView.isHidden = false
            headerImgView.isHidden = true
            cleanBtn.isHidden = false
            mainChatVC.bottomInputView.backgroundColor = mainChatVC.bottomInputView.bgColor
            
        } else { // 港小宝
            bgImgView.isHidden = true
            headerImgView.isHidden = false
            cleanBtn.isHidden = true
            mainChatVC.bottomInputView.backgroundColor = .clear
        }
    }
}

extension YHAITabViewController: 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
    }
}
