//
//  BsHomeBannerView.swift
//  BaiSiSMApp
//
//  Created by SJ on 2022/11/9.
//  Copyright © 2022 www.davidhuang.com. All rights reserved.
//

import Foundation
import FSPagerView
import Kingfisher

let bannerSildingInterval = 3.0

class YHHomeBannerView: UIView {
    static let viewH: CGFloat = KScreenWidth - 20.0 * 2
    var dataArr: [YHBannerModel] = [] {
        didSet {
            // 设置为0是先停掉自动滑动定时器
            bannerView.automaticSlidingInterval = 0
            self.indicatorView.indicatorItems = self.dataArr.count
            bannerView.reloadData()
            // 指定指示器为第一个
            self.indicatorView.curIndicatorIndex = 0
            // 指定显示图片为第一个
            bannerView.selectItem(at: 0, animated: false)
            // 开启定时器开始滚动
            bannerView.automaticSlidingInterval = bannerSildingInterval
//            if let index = dataArr.firstIndex(where: {
//                $0.skip_type == 100
//            }) {
//                // 开启定时器开始滚动
//                bannerView.automaticSlidingInterval = 0
//                bannerView.scrollToItem(at: index, animated: false)
//                indicatorView.curIndicatorIndex = index
//            } else {
//                // 开启定时器开始滚动
//                bannerView.automaticSlidingInterval = bannerSildingInterval
//            }
            bannerView.removesInfiniteLoopForSingleItem = true
            bannerView.alwaysBounceHorizontal = true
        }
    }
    
    private lazy var viewModel = YHLiveSalesViewModel()
    private lazy var surveyViewModel = YHSurveyViewModel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var bannerView: FSPagerView = {
        let view = FSPagerView()
        view.delegate = self
        view.dataSource = self
        view.bounces = false
        view.isInfinite = true
        view.automaticSlidingInterval = bannerSildingInterval
        view.register(YHHomeBannerCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        view.itemSize = CGSize(width: YHHomeBannerView.viewH, height: YHHomeBannerView.viewH)// FSPagerView.automaticSize
        return view
    }()
    
    lazy var indicatorView: YHHomeBannerIndicatorView = {
        let view = YHHomeBannerIndicatorView()
        return view
    }()
}

private extension YHHomeBannerView {
    func initView() {
        addSubview(bannerView)
        bannerView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(YHHomeBannerView.viewH)
        }
        
        bannerView.addSubview(indicatorView)
        indicatorView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(2)
            make.bottom.equalTo(-14)
        }
        bannerView.reloadData()
    }
    
    func goAppTab(tabBarName: String) {
        if !tabBarName.isEmpty {
            if tabBarName.contains("tabBarHome", caseSensitive: false) {
                // 首页
                goTabBarBy(tabType: .home)
            } else if tabBarName.contains("tabBarService", caseSensitive: false) {
                // 服务中心
                goTabBarBy(tabType: .service)
            } else if tabBarName.contains("tabBarMsg", caseSensitive: false) {
                // 社区
                goTabBarBy(tabType: .community)
            } else if tabBarName.contains("tabBarMine", caseSensitive: false) {
                // 我的
                goTabBarBy(tabType: .mine)
            } else if tabBarName.contains("invitation_with_gifts", caseSensitive: false) {
                
                if YHLoginManager.shared.isLogin() {
                    let vc = YHInvitationWithGiftsViewController()
                    UIViewController.current?.navigationController?.pushViewController(vc)
                } else {
                    YHOneKeyLoginManager.shared.oneKeyLogin()
                }
                
            } else if tabBarName.contains("renewal_plan", caseSensitive: false) {
                if YHLoginManager.shared.isLogin() {
                    YHHUD.show(.progress(message: "加载中..."))
                    surveyViewModel.getRenewalPlanGenerated { state, error in
                        YHHUD.hide()
                        guard let state = state else {
                            if let msg = error?.errorMsg, !msg.isEmpty {
                                YHHUD.flash(message: msg)
                            }
                            return
                        }
                        if state.isGeneratePlan == true {
                            let vc = YHPlanTestViewController()
                            UIViewController.current?.navigationController?.pushViewController(vc)
                        } else {
                            let vc = YHCustomerInformationQuestionnaireVC()
                            UIViewController.current?.navigationController?.pushViewController(vc)
                        }
                    }
                    
                } else {
                    YHOneKeyLoginManager.shared.oneKeyLogin()
                }
                
            } else {
                
            }
        }
    }
    
    func checkLogin() -> Bool {
        if !YHLoginManager.shared.isLogin() {
            YHOneKeyLoginManager.shared.oneKeyLogin()
            return false
        }
        return true
    }
}

extension YHHomeBannerView: FSPagerViewDataSource, FSPagerViewDelegate {
    
    public func numberOfItems(in pagerView: FSPagerView) -> Int {
        return self.dataArr.count
    }
    
    public func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        guard let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index) as? YHHomeBannerCollectionViewCell else {
            return FSPagerViewCell()
        }
        if index < dataArr.count {
            cell.dataModel = dataArr[index]
        }
        return cell
    }
    
    // MARK: - FSPagerView Delegate
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        pagerView.deselectItem(at: index, animated: true)
        pagerView.scrollToItem(at: index, animated: true)
        if index >= dataArr.count {
            return
        }
        let model = dataArr[index]
        if model.isLocalItemFlag {
            return
        }
        YHAnalytics.track("APP_Home_Banners")
        switch model.skip_type {
        case 1: // 跳转H5
            if model.skip_url.isEmpty == false {
            } else {
                YHHUD.flash(message: "error:skip_url不能为空")
                return
            }
            
            // 1.增加app  token
            var url = ""
            if YHLoginManager.shared.isLogin() {
                let token = YHLoginManager.shared.h5Token
                url = model.skip_url + "?param=" + token
                let urlHasParam = String.hasQueryParameters(urlString: model.skip_url)
                if urlHasParam {
                    url = model.skip_url + "&param=" + token
                }
            } else {
                url = model.skip_url
            }
            
            // 2.增加导航栏高度
            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
            if model.is_double_11_flag {
                vc.isHideNavigationBar = false
            }
            
            if let tag = model.is_full_screen {
                vc.isFullScreenFlag = tag
            }
            
            if model.is_share_h5_flag {
                if let tModel = model.addtition_param {
                    if !tModel.ShareH5Url.isEmpty {
                        vc.isShowRightShareItemFlag = true
                        vc.shareH5Title = tModel.ShareH5Title
                        vc.shareH5Describe = tModel.ShareH5Describe
                        vc.shareUrlFromOutside = tModel.ShareH5Url
                    }
                }
            }
            self.parentViewController?.navigationController?.pushViewController(vc)
            
        case 2: // 跳转APP内Tab
            if model.skip_url.isEmpty == false {
            } else {
                YHHUD.flash(message: "error:skip_url不能为空")
                return
            }
            goAppTab(tabBarName: model.skip_url)
        case 3:// 3-跳转资讯页
            if model.skip_url.isEmpty == false {
            } else {
                YHHUD.flash(message: "error:skip_url不能为空")
                return
            }
            let vc = YHHomeWebViewController()
            vc.url = model.skip_url
            self.parentViewController?.navigationController?.pushViewController(vc)
        case 100:// 直播
            // 文哥
            // media_type 投放类型：1 图片，2 直播
            // live_id 直播ID
            // live_status 直播状态 1:直播中 2:未直播 0:未知状态 3:结束直播
            // live_type  播放类型：1 展示最新直播，2指定直播，3 指定录播
            // live_pull_url 直播拉流链接
            // video_url 视频链接
            // recorded_video_id 录播id token: String? = nil, channelId
            if !checkLogin() {
                return
            }
            let cell: YHHomeBannerCollectionViewCell? = pagerView.cellForItem(at: index) as? YHHomeBannerCollectionViewCell
//            if let player = YHPlayerManager.shared.getPlayer(.secondary) {
//                YHPlayerManager.shared.leaveChannel(for: player)
//                player.clearPlayerView()
//            }
            YHHUD.show(.progress(message: "加载中..."))
            viewModel.getLiveStatus(liveId: model.live_id) { liveInfo, _ in
                YHHUD.hide()
                guard let liveInfo = liveInfo else {
                    let ctl = YHLiveAppointmentViewController(liveId: model.live_id)
                    UIViewController.current?.navigationController?.pushViewController(ctl)
                    return
                }
                if liveInfo.status == 2 {
                    let ctl = YHLiveAppointmentViewController(liveId: model.live_id)
                    UIViewController.current?.navigationController?.pushViewController(ctl)
                } else {
                    let playbackInfo = YHPlayerManager.PlaybackInfo(id: model.live_id, url: nil, title: nil, roomId: nil, token: nil, channelId: nil, uid: nil, isLive: true, scene: .fullscreen)
                    YHPlayerManager.shared.enterLive(from: cell?.bannerImagV, playbackInfo: playbackInfo)
                }
            }
            
            printLog("跳转直播")
        case 101:// 录播
            printLog("跳转录播")
            if !checkLogin() {
                return
            }
            if let player = YHPlayerManager.shared.getPlayer(.secondary) {
                player.stop()
                player.clearPlayerView()
            }
            let cell: YHHomeBannerCollectionViewCell? = pagerView.cellForItem(at: index) as? YHHomeBannerCollectionViewCell
            let playbackInfo = YHPlayerManager.PlaybackInfo(id: model.recorded_video_id, url: nil, title: nil, roomId: nil, uid: nil, isLive: false, scene: .fullscreen)
            YHPlayerManager.shared.enterVOD(from: cell?.bannerImagV, playbackInfo: playbackInfo)
        case 102:// 图片直播
            printLog("跳转录播")
            if !checkLogin() {
                return
            }
//            if let player = YHPlayerManager.shared.getPlayer(.secondary) {
//                YHPlayerManager.shared.leaveChannel(for: player)
//                player.clearPlayerView()
//            }
            let cell: YHHomeBannerCollectionViewCell? = pagerView.cellForItem(at: index) as? YHHomeBannerCollectionViewCell
            YHHUD.show(.progress(message: "加载中..."))
            viewModel.getLiveStatus(liveId: model.live_id) { liveInfo, _ in
                YHHUD.hide()
                guard let liveInfo = liveInfo else {
                    let ctl = YHLiveAppointmentViewController(liveId: model.live_id)
                    UIViewController.current?.navigationController?.pushViewController(ctl)
                    return
                }
                if liveInfo.status == 2 {
                    let ctl = YHLiveAppointmentViewController(liveId: model.live_id)
                    UIViewController.current?.navigationController?.pushViewController(ctl)
                } else {
                    let playbackInfo = YHPlayerManager.PlaybackInfo(id: model.live_id, url: nil, title: nil, roomId: nil, token: nil, channelId: nil, uid: nil, isLive: true, scene: .fullscreen)
                    YHPlayerManager.shared.enterLive(from: cell?.bannerImagV, playbackInfo: playbackInfo)
                }
            }
            
        case 0:// 0 不需要跳转
            printLog("0 不需要跳转")
        default:
            YHHUD.flash(message: "不需要处理的类型")
        }
        YHAnalytics.track("homeBannerClick", properties: ["url": model.img_url, "index": index])
    }
    
    func pagerViewWillEndDragging(_ pagerView: FSPagerView, targetIndex: Int) {
        self.indicatorView.curIndicatorIndex = targetIndex
    }
    
    func pagerViewDidEndScrollAnimation(_ pagerView: FSPagerView) {
        self.indicatorView.curIndicatorIndex = pagerView.currentIndex
    }
    /*
    func pagerView(_ pagerView: FSPagerView, willDisplay cell: FSPagerViewCell, forItemAt index: Int) {
        
        if index >= dataArr.count {
            return
        }
        let model = dataArr[index]
        if model.isLocalItemFlag {
            return
        }
        if let cell = cell as? YHHomeBannerCollectionViewCell {
            if model.skip_type == 100 {
                let playbackInfo = YHPlayerManager.PlaybackInfo(id: model.live_id, token: model.token, channelId: model.rtmp_channel, uid: UInt(model.user_id), isLive: true, scene: .banner, playerType: .secondary)
                YHPlayerManager.shared.enterBanner(playbackInfo: playbackInfo, inView: cell.bannerImagV)
            } else {
                if let player = YHPlayerManager.shared.getPlayer(.secondary) {
                    YHPlayerManager.shared.leaveChannel(for: player)
                    player.clearPlayerView()
                }
            }
            
        }
    }
    
    func pagerView(_ pagerView: FSPagerView, didEndDisplaying cell: FSPagerViewCell, forItemAt index: Int) {
        if index >= dataArr.count {
            return
        }
        let model = dataArr[index]
        if model.isLocalItemFlag {
            return
        }
        if model.skip_url.isEmpty == false {
            if model.skip_type == 100 || model.skip_type == 102 {
                YHPlayerManager.shared.stop(type: .secondary)
                if let player = YHPlayerManager.shared.getPlayer(.secondary) {
                    YHPlayerManager.shared.leaveChannel(for: player)
                    player.clearPlayerView()
                }
            }
        }
    }
     */
}
