//
//  YHServiceBannerView.swift
//  galaxy
//
//  Created by EDY on 2024/4/8.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import FSPagerView

class YHServiceBannerView: UIView {
    
    // 位置、大小、图片、文本
    var dataArr: [YHBannerModel] = [] {
        didSet {
            self.indicatorView.indicatorItems = self.dataArr.count
            let width = 16 * self.dataArr.count + 3 * (self.dataArr.count - 1)
            indicatorView.snp.remakeConstraints { make in
                make.right.equalToSuperview().offset(-20)
                make.height.equalTo(2)
                make.bottom.equalTo(-14)
                make.width.equalTo(width)
            }
            bannerView.reloadData()
        }
    }
    
    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.isInfinite = true
        view.automaticSlidingInterval = 3
        view.register(YHServiceBannerCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        view.itemSize = FSPagerView.automaticSize
        return view
    }()
    
    lazy var indicatorView : YHHomeBannerIndicatorView = {
        let view = YHHomeBannerIndicatorView()
        return view
    }()
}

private extension YHServiceBannerView {
    func initView() {
        addSubview(bannerView)
        bannerView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalToSuperview()
        }
        
        bannerView.addSubview(indicatorView)
        indicatorView.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-20)
            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 {
                
            }
        }
    }
}

extension YHServiceBannerView: FSPagerViewDataSource, FSPagerViewDelegate {
    
    public func numberOfItems(in pagerView: FSPagerView) -> Int {
        return self.dataArr.count
    }
    
    public func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index) as! YHServiceBannerCollectionViewCell
        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
        }
        
        if model.skip_url.isEmpty == false {
            switch model.skip_type {
            case 1: //跳转H5
                let vc = YHHomeWebViewController()
                vc.url = model.skip_url
                self.parentViewController?.navigationController?.pushViewController(vc)
            case 2: //跳转APP内Tab
                goAppTab(tabBarName:model.skip_url)
            case 3://3-跳转资讯页
                let vc = YHHomeWebViewController()
                vc.url = model.skip_url
                self.parentViewController?.navigationController?.pushViewController(vc)
            case 0://0 不需要跳转
                printLog("0 不需要跳转")
            default:
                YHHUD.flash(message: "不需要处理的类型")
                break
            }
        } else {
            YHHUD.flash(message: "error:skip_url不能为空")
        }
    }
    
    func pagerViewWillEndDragging(_ pagerView: FSPagerView, targetIndex: Int) {
        self.indicatorView.curIndicatorIndex = targetIndex
    }
    
    func pagerViewDidEndScrollAnimation(_ pagerView: FSPagerView) {
        self.indicatorView.curIndicatorIndex = pagerView.currentIndex
    }
}

class YHServiceBannerCollectionViewCell: FSPagerViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        textLabel?.text = ""
        textLabel?.isHidden = true
        imageView?.isHidden = true
        
        initView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var bannerImagV: UIImageView = {
        let imagV : UIImageView = UIImageView()
        imagV.contentMode = .scaleAspectFill
        imagV.clipsToBounds = true
        imagV.image = UIImage(named: "global_default_image")
        return imagV
    }()
    
    lazy var bannerTitleLable: UILabel = {
        let lable = UILabel()
        lable.font = UIFont.PFSC_R(ofSize: 17)
        lable.textColor = UIColor.white
        return lable
    }()
    
    lazy var bgImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "service_title_bg")
        return imageView
    }()
    
    var dataModel : YHBannerModel? {
        didSet {
            updateUI()
        }
    }
}

private extension YHServiceBannerCollectionViewCell {
    
    func initView() {
        contentView.addSubview(bannerImagV)
        bannerImagV.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        contentView.addSubview(bgImageView)
        bgImageView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(64)
        }
        
        contentView.addSubview(bannerTitleLable)
        bannerTitleLable.snp.makeConstraints { make in
            make.right.equalTo(-20)
            make.bottom.equalTo(-20)
            make.left.equalTo(20)
            make.height.equalTo(24)
        }
    }
    
    func updateUI() {
        guard let model = dataModel else { return }
        
        if model.isLocalItemFlag {
            bannerTitleLable.isHidden = true
            
            bannerImagV.image = UIImage(named: model.img_url)
        } else {
            bannerTitleLable.isHidden = false
            if let url = URL(string: model.img_url) {
                if let avifUrl = URL(string: model.img_url_compress) {
                    bannerImagV.kf.setImage(with: avifUrl, placeholder: UIImage(named: "global_default_image")) { result in
                        switch result {
                        case .success: break
                        case .failure(let error):
                            self.bannerImagV.kf.setImage(with: url, placeholder: UIImage(named: "global_default_image"))
                        }
                    }
                } else {
                    bannerImagV.kf.setImage(with: url, placeholder: UIImage(named: "global_default_image"))
                }
            } else {
                bannerImagV.image = UIImage(named: "global_default_image")
            }
            bannerTitleLable.text = model.name
        }
    }
}
