//
//  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 {
        guard let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index) as? YHServiceBannerCollectionViewCell 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
        }
        
        if model.skip_url.isEmpty == false {
            switch model.skip_type {
            case 1: // 跳转H5
                // for test hjl 建明机器IP
                // var url = "http://192.168.23.66:10300/superAppBridge.html#/schoolEvaluation"
                
                // for test hjl 梁辉机器IP
//                model.skip_url = "http://192.168.23.75:10300/superAppBridge.html#/double11-home"
                
                // for test hjl steve机器IP
//                model.skip_url = "http://192.168.52.158:10300/superAppBridge.html#/double11-home"
                
                // for test hjl 测试环境
//                model.skip_url = "https://test-hkdiy-h5.galaxy-immi.com/superAppBridge.html#/double11-home"
                
                // for test hjl
//                model.skip_url = "http://192.168.23.35:10300/signatureQrcode/EcqtQYs%2Bxey7t6jLbn6JkQ%3D%3D"
                
                // 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 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
                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: "不需要处理的类型")
            }
        } 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.layer.shadowColor = UIColor.clear.cgColor
        contentView.layer.shadowRadius = 0
        contentView.layer.shadowOpacity = 0
        contentView.layer.shadowOffset = .zero
        
        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
        }
    }
}
