//
//  MPPositive_SearchResultsShowView.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/5/13.
//

import UIKit

class MPPositive_SearchResultsShowView: UIView {
    ///搜索结果管理模型
    var loadModel:MPPositive_SearchResultsLoadViewModel!{
        didSet{
            DispatchQueue.main.async {
                [weak self] in
                guard let self = self else {return}
                if loadModel == nil {
                    emptyImageView.isHidden = false
                }else {
                    if isShowAd == true {
                        MP_AdMobManager.shared.showSearchInterstitialAdIfAvailable { [weak self] ad in
                            guard let self = self else {return}
                            //判断数据是否有值
                            if loadModel?.sectionLists?.count != nil {
                                //有值，不在展示
                                MP_AdMobManager.shared.setInterstitialSwitch(false)
                            }else {
                                MP_AdMobManager.shared.isShowingSearchInterstitialAd = true
                                //没有值，展示
                                MP_AdMobManager.shared.setInterstitialSwitch(true)
                                ad.present(fromRootViewController: nil)
                            }
                        }
                    }
                    //搜索成功了
                    MP_AnalyticsManager.shared.search_result_pvAction()
                    loadModel.resultReloadBlock = {
                        [weak self] in
                        //刷新分页控制器
                        guard let self = self else {return}
                        MP_HUD.hideNow()
                        isHidden = false
                        MP_AnalyticsManager.shared.search_resultsuccess_actionAction()
                        if let loadModel = loadModel, let titles = loadModel.sectionLists?.compactMap({$0.title ?? ""}) {
                            dataSource.titles = titles
                            dataSource.reloadData(selectedIndex: 0)
                            segmentView.reloadData()
                            segmentView.selectItemAt(index: 0)
                            emptyImageView.isHidden = !(titles.count == 0)
                        }
                    }
                }
            }
        }
    }
    ///广告View
    fileprivate lazy var adContainerView:UIView = {
        let adContainerView:UIView = .init(frame: .init(x: 0, y: 0, width: screen_Width, height: 300*width))
        adContainerView.backgroundColor = .clear
        return adContainerView
    }()
    //MARK: - 分页栏设置
    //分页栏View
    lazy var segmentView:JXSegmentedView = {
        var jxSegmentView = JXSegmentedView()
        jxSegmentView.backgroundColor = .init(hex: "1A1A1A")
        return jxSegmentView
    }()
    //数据源
    private lazy var dataSource:JXSegmentedTitleDataSource = {
        var dataSource = JXSegmentedTitleDataSource()
        dataSource.titles = []
        //标题未选中状态
        dataSource.titleNormalColor = .init(hex: "#666666")
        dataSource.titleNormalFont = .systemFont(ofSize: 16*width, weight: .regular)
        //标题选中状态
        dataSource.titleSelectedColor = .init(hex: "#80F988")
        dataSource.titleSelectedFont = .systemFont(ofSize: 16*width, weight: .bold)
        //是否颜色过度
        dataSource.isTitleColorGradientEnabled = true
        dataSource.isSelectedAnimable = true
        dataSource.isItemTransitionEnabled = true
        return dataSource
    }()
    //指示器
    private lazy var indicator:JXSegmentedIndicatorLineView = {
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = 16*width
        indicator.indicatorHeight = 3*width
        indicator.indicatorCornerRadius = 1.5*width
        indicator.indicatorColor = .init(hex: "#80F988")
        indicator.indicatorPosition = .bottom
        return indicator
    }()
    //分页内容承载框
    fileprivate lazy var listContainerView:JXSegmentedListContainerView = {
        let listContainerView = JXSegmentedListContainerView(dataSource: self)
        listContainerView.backgroundColor = .clear
        return listContainerView
    }()
    //数据空图片
    lazy var emptyImageView:UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "empty"))
        imageView.contentMode = .scaleAspectFill
        return imageView
    }()
    var scrollBlock:(() -> Void)?
    //是否展示插页广告
    private var isShowAd:Bool = true
    init(frame: CGRect, isShowAd:Bool = true) {
        super.init(frame: frame)
        self.isShowAd = isShowAd
        backgroundColor = .init(hex: "1A1A1A")
        configure()
        MP_AdMobManager.shared.onSearchNativeAdBlock = {
            [weak adContainerView] in
            guard let adContainerView = adContainerView else {return}
            //展示搜索原生广告
            MP_AdMobManager.shared.layoutSearchNativeAd(in: adContainerView)
        }
        //展示搜索原生广告
        MP_AdMobManager.shared.layoutSearchNativeAd(in: adContainerView)
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    //配置
    private func configure() {
        addSubview(emptyImageView)
        emptyImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(211*width)
            make.height.equalTo(172*width)
        }
        addSubview(adContainerView)
        adContainerView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(0)
        }
        segmentView.indicators = [indicator]
        segmentView.dataSource = dataSource
        //配置View
        addSubview(segmentView)
        segmentView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(adContainerView.snp.bottom)
            make.height.equalTo(60*width)
        }
        addSubview(listContainerView)
        listContainerView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview().priority(999)
            make.top.equalTo(segmentView.snp.bottom).priority(999)
        }
        segmentView.contentScrollView = listContainerView.scrollView
        segmentView.listContainer = listContainerView
    }
}
//MARK: - JXSegmentedTitleDataSource
extension MPPositive_SearchResultsShowView: JXSegmentedListContainerViewDataSource, JXSegmentedViewDelegate {
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        return dataSource.titles.count
    }
    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        if index == 0 {
            //展示预览结果
            let showView:MPPositive_SearchResultPreviewShowView = .init(frame: listContainerView.frame, sectionLists: loadModel.sectionLists)
            showView.scrollBlock = {
                [weak self] in
                guard let self = self else {return}
                if let block = scrollBlock {
                    block()
                }
            }
            showView.chooseMoreIndexBlock = {
                [weak self] (selectedIndex) in
                guard let self = self else {
                    return
                }
                if selectedIndex <= (dataSource.titles.count-1) {
                    //未越界
                    DispatchQueue.main.async {
                        self.segmentView.selectItemAt(index: selectedIndex)
                    }
                }else {
                    //越界
                    print("当前越界")
                }
            }
            return showView
        }else {
            //展示分类结果
            if (loadModel.sectionLists.count-1) >= index {
                let showView:MPPositive_SearchResultTypeShowView = .init(frame: listContainerView.frame, list: loadModel.sectionLists[index])
                showView.scrollBlock = {
                    [weak self] in
                    guard let self = self else {return}
                    if let block = scrollBlock {
                        block()
                    }
                }
                return showView
            }else {
                let showView:MPPositive_SearchResultTypeShowView = .init(frame: listContainerView.frame, list: nil)
                showView.scrollBlock = {
                    [weak self] in
                    guard let self = self else {return}
                    if let block = scrollBlock {
                        block()
                    }
                }
                return showView
            }
        }
    }
}
