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

import UIKit
import FSPagerView
// import JXPageControl

class YHAIChatBannerItem {
    var id: Int = 0
    var title: String = ""
    var desc: String = ""
    var msg: String = ""

    required init(id: Int = 0, title: String = "", desc: String = "", msg: String = "") {
        self.id = id
        self.title = title
        self.desc = desc
        self.msg = msg
    }
}

class YHAIChatBannerViewConfig {
    var bgColor: UIColor = .init(hex: 0xE6F4FF)
    var bannerTitleColor: UIColor = .init(hex: 0x6D788A)
    var bgImageName: String = ""
    var title: String = ""
    var desc: String = ""
    var indicatorColor: UIColor = .brandMainColor
    var bannerItems: [YHAIChatBannerItem] = []
    var flowMessages: [String] = []
}

class YHAIChatBannerView: UIView {

    static let bannersHeight = 95.0
    let cellHeight: CGFloat = 33.0 // 单元格的固定高度
    var selectFlowMsgBlock: ((String) -> Void)?
    var selectBannerItemBlock: ((YHAIChatBannerItem) -> Void)?
    
    var config = YHAIChatBannerViewConfig() {
        didSet {
            titleLabel.text = config.title
            descLabel.text = config.desc
            bgCardView.backgroundColor = config.bgColor
            bgImgV.image = UIImage(named: config.bgImageName)
            indicatorView.selectedDotColor = config.indicatorColor
            bannerArr = config.bannerItems
        }
    }

    var messages: [String] = [""] {
        didSet {
            layout.dataSource = messages
            collectView.reloadData()
        }
    }
    
    lazy var titleLabel: UILabel = {
        let lable = UILabel()
        lable.font = UIFont.PFSC_R(ofSize: 12)
        lable.textColor = UIColor.init(hex: 0x6D788A)
        lable.text = "Hello，我是新港生活规划师"
        return lable
    }()
    
    lazy var descLabel: UILabel = {
        let lable = UILabel()
        lable.font = UIFont.PFSC_B(ofSize: 15)
        lable.textColor = UIColor.mainTextColor
        lable.text = "需要香港身份办理找我~"
        return lable
    }()
    
    lazy var bgImgV: UIImageView = {
        let imagV: UIImageView = UIImageView()
        imagV.contentMode = .scaleAspectFill
        imagV.clipsToBounds = true
        imagV.image = UIImage(named: "ai_chat_header_bg_0")
        imagV.isUserInteractionEnabled = true
        return imagV
    }()
    
    lazy var bgCardView: UIView = {
        let v = UIView()
        v.layer.cornerRadius = 12.0
        v.clipsToBounds = true
        return v
    }()
    
    var bannerArr: [YHAIChatBannerItem] = [] {
        didSet {
            // 设置为0是先停掉自动滑动定时器
            bannerView.automaticSlidingInterval = 0
            self.indicatorView.numberOfPages = self.bannerArr.count
            bannerView.reloadData()
            // 指定指示器为第一个
            self.indicatorView.currentPage = 0
            // 指定显示图片为第一个
//            bannerView.selectItem(at: 0, animated: false)
            // 开启定时器开始滚动
            bannerView.automaticSlidingInterval = bannerSildingInterval
            bannerView.removesInfiniteLoopForSingleItem = true
            bannerView.alwaysBounceHorizontal = true
        }
    }
    
    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(YHAIChatBannerItemCell.self, forCellWithReuseIdentifier: YHAIChatBannerItemCell.cellReuseIdentifier)
        view.itemSize = CGSize(width: KScreenWidth-40.0, height: YHAIChatBannerView.bannersHeight)// FSPagerView.automaticSize
        return view
    }()
    
    lazy var indicatorView: YHPageControl = {
        let pageControl = YHPageControl(frame: .zero)
        let dotHeight = 3.0
        pageControl.spacing = 2.0
        pageControl.dotSize = CGSize(width: 5, height: dotHeight)
        pageControl.selectedDotSize = CGSize(width: 12, height: dotHeight)
        pageControl.numberOfPages = 0
        pageControl.currentPage = 0
        pageControl.dotColor = .init(hex: 0xD5DAE1)
        pageControl.selectedDotColor = .brandMainColor
        return pageControl
    }()
    
    lazy var layout: YHAIChatCustomFlowLayout = {
        let layout = YHAIChatCustomFlowLayout()
        layout.scrollDirection = .horizontal
        layout.dataSource = []
        return layout
    }()
    
    lazy var collectView: UICollectionView = {
        let collectView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectView.delegate = self
        collectView.dataSource = self
        collectView.backgroundColor = .clear
        collectView.showsHorizontalScrollIndicator = false
        collectView.showsVerticalScrollIndicator = false
        // 注册自定义单元格
        collectView.register(YHAIChatBannerCollectionCell.self, forCellWithReuseIdentifier: YHAIChatBannerCollectionCell.cellReuseIdentifier)
        return collectView
    }()
    
    lazy var shadowView: YHAIChatShadowView = {
        let v = YHAIChatShadowView()
        return v
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func createUI() {
        
        addSubview(shadowView)
        addSubview(bgCardView)
        addSubview(bgImgV)
        bgImgV.addSubview(titleLabel)
        bgImgV.addSubview(descLabel)
        bgImgV.addSubview(bannerView)
        bgImgV.addSubview(indicatorView)
        
        shadowView.snp.makeConstraints { make in
            make.edges.equalTo(bgCardView)
        }
        
        let bgImgHeight = 242.0/335.0 * (KScreenWidth-40.0)
        
        bgCardView.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(bgImgV)
            make.top.equalTo(bgImgV).offset(33.0/242.0 * bgImgHeight)
        }

        bgImgV.snp.makeConstraints { make in
            make.top.equalTo(10)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(bgImgHeight)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(bgCardView).offset(24.0)
            make.left.equalTo(20)
            make.height.equalTo(20)
        }
        
        descLabel.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom)
            make.left.equalTo(20)
            make.height.equalTo(24)
        }

        bannerView.snp.makeConstraints { make in
            make.bottom.equalTo(bgImgV)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(YHAIChatBannerView.bannersHeight/242.0 * bgImgHeight)
        }
        
        indicatorView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(3)
            make.bottom.equalTo(-16)
        }
        bannerView.reloadData()
        
        addSubview(collectView)
        collectView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(33.0*2+10.0 + 10.0*2.0)
            make.top.equalTo(bgImgV.snp.bottom).offset(6)
        }
    }
    
    // 计算文字宽度大小
    func getwith(font: UIFont, height: CGFloat, string: String) -> CGSize {
        let size = CGSize.init(width: CGFloat(MAXFLOAT), height: height)
        let dic = [NSAttributedString.Key.font: font] // swift 4.2
        let strSize = string.boundingRect(with: size, options: [.usesLineFragmentOrigin], attributes: dic, context: nil).size
        return CGSize(width: ceil(strSize.width), height: strSize.height)
    }

}

extension YHAIChatBannerView: FSPagerViewDataSource, FSPagerViewDelegate {
    
    public func numberOfItems(in pagerView: FSPagerView) -> Int {
        return self.bannerArr.count
    }
    
    public func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        guard let cell = pagerView.dequeueReusableCell(withReuseIdentifier: YHAIChatBannerItemCell.cellReuseIdentifier, at: index) as? YHAIChatBannerItemCell else {
            return FSPagerViewCell()
        }
        if index < bannerArr.count {
            let model = bannerArr[index]
            cell.model = model
            cell.titleLabel.textColor = self.config.bannerTitleColor
        }
        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 0 <= index, index < bannerArr.count {
            let model = bannerArr[index]
            selectBannerItemBlock?(model)
            return
        }
    }
    
    func pagerViewWillEndDragging(_ pagerView: FSPagerView, targetIndex: Int) {
        self.indicatorView.currentPage = targetIndex
    }
    
    func pagerViewDidEndScrollAnimation(_ pagerView: FSPagerView) {
        self.indicatorView.currentPage = pagerView.currentIndex
    }
}

extension YHAIChatBannerView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
        // 返回单元格数量
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            
            return messages.count
        }
        
        // 返回每个单元格的大小
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
            return layout.getSize(index: indexPath.item)
        }
        
        // 返回自定义单元格
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHAIChatBannerCollectionCell.cellReuseIdentifier, for: indexPath) as? YHAIChatBannerCollectionCell else {
                return UICollectionViewCell()
            }
            if 0 <= indexPath.item && indexPath.item < messages.count {
                cell.titleLabel.text = messages[indexPath.item]
            }
            return cell
        }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if 0 <= indexPath.item && indexPath.item < messages.count {
            let text = messages[indexPath.item]
            selectFlowMsgBlock?(text)
        }
    }
}
