//
//  KMAdvertisementShowScroll_iOS.swift
//  KMAdvertisement_iOS
//
//  Created by lizhe on 2022/11/29.
//

import UIKit


open class KMAdvertisementShowScroll_iOS: KMAdvertisementBaseView {

    @IBOutlet var contentView: UIView!
    // MARK: 初始化
    @IBOutlet weak var collectionView: UICollectionView!
    
    lazy var presenter: KMAdvertisementTableViewPresenter! = KMAdvertisementTableViewPresenter()
    
    //内部使用数据
    fileprivate var data: [KMAdvertisementModelSection]?
    /**
      @abstract 外部传入数据
      @param inputData 文件路劲
      */
    open var inputData: KMAdvertisementModel! {
        didSet {
            self.presenter.initPresenter(view: self, data: inputData)
        }
    }
    
    override public var loadCompletion: KMAdvertisementLoadCompletion? {
        didSet {
            if self.data != nil {
                if self.loadCompletion != nil {
                    self.loadCompletion!(self.data!)
                }
            }
        }
    }
    
    convenience init (data: KMAdvertisementModel, superView: UIView) {
        self.init(frame: superView.bounds)
        self.presenter.initPresenter(view: self, data: data)
        superView.addSubview(self)
        self.autoresizingMask = [.flexibleHeight , .flexibleWidth]
    }
    
    public required init?(coder decoder: NSCoder) {
        super.init(coder: decoder)
        initContentView()
        setup()
    }
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        initContentView()
        setup()
    }

    private func initContentView() {
        //绑定xib
        let resource = UINib(nibName: String(describing: self.classForCoder.self),
                             bundle: Bundle(for: self.classForCoder.self))
        resource.instantiate(withOwner: self)
        addSubview(contentView)
        contentView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            contentView.topAnchor.constraint(equalTo: topAnchor),
            contentView.leftAnchor.constraint(equalTo: leftAnchor),
            contentView.rightAnchor.constraint(equalTo: rightAnchor),
            contentView.bottomAnchor.constraint(equalTo: bottomAnchor)])
        contentView.updateConstraintsIfNeeded()
    }
    
    func setup() {
        //设置代理
        let layout = KMAdvertisementFlowLayout()
        //设置滚动方向
        layout.scrollDirection = .horizontal
//        layout.minimumLineSpacing = 10
        
        self.collectionView.collectionViewLayout = layout
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.showsHorizontalScrollIndicator = false
        self.collectionView.showsVerticalScrollIndicator = false
//        self.collectionView.isPagingEnabled = true
        self.collectionView.register(UINib(nibName: "KMAdvertisementShowScrollCell_iOS", bundle: nil), forCellWithReuseIdentifier: "KMAdvertisementShowScrollCell_iOS")
        self.collectionView.reloadData()
    }
    
    public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
         print("scrollViewDidEndDragging")
    }
}

extension KMAdvertisementShowScroll_iOS: KMAdvertisementTableViewPresenterDelegate {
    func showData(presenter: KMAdvertisementTableViewPresenter, data: Array<KMAdvertisementModelSection>) {
        self.data = data
        self.collectionView.reloadData()
        if self.loadCompletion != nil {
            self.loadCompletion!(self.data!)
        }
    }
}

extension KMAdvertisementShowScroll_iOS: UICollectionViewDelegate {
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if self.data != nil {
            let model = (self.data?[indexPath.section])
            let content = model?.content![indexPath.item]
            if actionCompletion != nil {
                content?.index = indexPath.item
                actionCompletion!(.tap, content!)
            }
        }
    }
    
    public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        print("取消选中")
    }
}

extension KMAdvertisementShowScroll_iOS: UICollectionViewDataSource {
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if self.data != nil {
            let model: KMAdvertisementModelSection = (self.data?[section])!
            return model.content!.count
        } else {
            return 0
        }
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: KMAdvertisementShowScrollCell_iOS = collectionView.dequeueReusableCell(withReuseIdentifier: "KMAdvertisementShowScrollCell_iOS", for: indexPath) as! KMAdvertisementShowScrollCell_iOS
        weak var weakSelf = self
        cell.cancelActionBlock = {
            if weakSelf != nil {
                if weakSelf.data != nil {
                    let model = (weakSelf.data?[indexPath.section])
                    let content = weakSelf.model?.content![indexPath.item]
                    weakSelf.presenter.deleteItem(item: content!)
                }
            }
        }

        weak var weakSelf = self
        cell.buttonActionBlock = { item in
            if weakSelf != nil {
                if weakSelf.actionCompletion != nil {
                    weakSelf.actionCompletion!(.tap, item)
                }
            }
        }
        
        if self.data != nil {
            let model = (self.data?[indexPath.section])
            cell.model = model?.content![indexPath.item]
        }

        return cell
    }
}

extension KMAdvertisementShowScroll_iOS: UICollectionViewDelegateFlowLayout {
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSizeMake(self.contentView.bounds.width - 40, self.contentView.bounds.height)
    }
}
