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

import UIKit
import FSPagerView

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 YHAIChatBannerView: UIView {

    static let bannersHeight = 95.0
    let cellHeight: CGFloat = 33.0 // 单元格的固定高度
    var selectFlowMsgBlock:((String)->())?
    var selectBannerItemBlock:((YHAIChatBannerItem)->())?

    var messages:[String] = [] {
        didSet {
            layout.dataSource = messages
            collectionView.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
    }()
    
    var bannerArr: [YHAIChatBannerItem] = [] {
        didSet {
            // 设置为0是先停掉自动滑动定时器
            bannerView.automaticSlidingInterval = 0
            self.indicatorView.indicatorItems = self.bannerArr.count
            bannerView.reloadData()
            // 指定指示器为第一个
            self.indicatorView.curIndicatorIndex = 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 = CGSizeMake(KScreenWidth-40.0, YHAIChatBannerView.bannersHeight)//FSPagerView.automaticSize
        view.layer.cornerRadius = 4.0
        view.clipsToBounds = true
        return view
    }()
    
    lazy var indicatorView : YHHomeBannerIndicatorView = {
        let view = YHHomeBannerIndicatorView()
        view.normalColor = .init(hex: 0x6D788A)
        view.selectedColor = .brandMainColor
        return view
    }()
    
    lazy var layout: YHAIChatCustomFlowLayout = {
        let layout = YHAIChatCustomFlowLayout()
        layout.scrollDirection = .horizontal
        layout.dataSource = []
        return layout
    }()
    
    lazy var collectionView: 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(bgImgV)
        bgImgV.addSubview(titleLabel)
        bgImgV.addSubview(descLabel)
        bgImgV.addSubview(bannerView)
        bannerView.addSubview(indicatorView)
        
        shadowView.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(bgImgV)
            make.top.equalTo(bgImgV.snp.top).offset(33)
        }

        bgImgV.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(242)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(57)
            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)
        }
        
        indicatorView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(2)
            make.bottom.equalTo(-16)
        }
        bannerView.reloadData()
        
        addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(33.0*2+10.0 + 10.0*2.0)
            make.top.equalTo(bannerView.snp.bottom).offset(6)
            make.bottom.equalTo(-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 CGSizeMake(ceil(strSize.width), 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 {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: YHAIChatBannerItemCell.cellReuseIdentifier, at: index) as! YHAIChatBannerItemCell
        if index < bannerArr.count {
            let model = bannerArr[index]
            cell.model = model
        }
        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.curIndicatorIndex = targetIndex
    }
    
    func pagerViewDidEndScrollAnimation(_ pagerView: FSPagerView) {
        self.indicatorView.curIndicatorIndex = 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 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHAIChatBannerCollectionCell.cellReuseIdentifier, for: indexPath) as! YHAIChatBannerCollectionCell
            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)
        }
    }
}
