//
//  YHOtherServiceListView.swift
//  galaxy
//
//  Created by EDY on 2024/6/13.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import JXSegmentedView

class YHOtherServiceListViewController: YHBaseViewController {
    let homeViewModel: YHHomePageViewModel = YHHomePageViewModel()
    var items: [YHHomeListModel?] = [] {
        didSet {
            self.myCollectView.reloadData()
        }
    }
    
    lazy var myCollectView = {
        // 设置布局方向
        let flowLayout = YHHomeCollectionLayout()
        flowLayout.minimumInteritemSpacing = 7.0
        flowLayout.minimumColumnSpacing = 7.0
        flowLayout.sectionInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        let collectinoView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collectinoView.backgroundColor = .white
        collectinoView.register(YHHomeCollectionViewCell.self, forCellWithReuseIdentifier: YHHomeCollectionViewCell.cellReuseIdentifier)
        collectinoView.delegate = self
        collectinoView.dataSource = self
//        collectinoView.bounces = false
        collectinoView.translatesAutoresizingMaskIntoConstraints = false
        collectinoView.alwaysBounceVertical = true
        collectinoView.showsVerticalScrollIndicator = false
        collectinoView.showsHorizontalScrollIndicator = false
        return collectinoView
    }()
    
    var classId: Int = 0
    public var vcCanScroll: Bool = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        setupUI()
        loadData()
    }
}

extension YHOtherServiceListViewController {
    func loadData() {
        self.homeViewModel.getList(true, classId) {[weak self] _, _ in
            guard let self = self else { return }
            self.items = self.homeViewModel.arrHomeNewsData ?? []
            if self.homeViewModel.hasMoreForHomeNews == false {
                self.myCollectView.es.noticeNoMoreData()
                self.myCollectView.footer?.alpha = 1
            }
        }
    }
    
    func setupUI() {
        gk_navBarAlpha = 1
        gk_navigationBar.isHidden = true
        view.addSubview(myCollectView)
        myCollectView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalToSuperview()
        }
        
        myCollectView.es.addInfiniteScrolling {[weak self] in
            guard let self = self else { return }
            self.homeViewModel.getList(false, self.classId) {[weak self] _, _ in
                guard let self = self else { return }
                DispatchQueue.main.asyncAfter(wallDeadline: .now() + 0.35, execute: {
                    CATransaction.setDisableActions(true)
                    self.items = self.homeViewModel.arrHomeNewsData ?? []
                    CATransaction.commit()
                    self.myCollectView.es.stopLoadingMore()
                    if self.homeViewModel.hasMoreForHomeNews == false {
                        self.myCollectView.es.noticeNoMoreData()
                    }
                })
            }
        }
    }
}

extension YHOtherServiceListViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}

extension YHOtherServiceListViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHHomeCollectionViewCell.cellReuseIdentifier, for: indexPath) as? YHHomeCollectionViewCell else { return UICollectionViewCell() }
        cell.listModel = items[indexPath.row]
        return cell
        
    }
    
    private func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print("index is \(indexPath.row)")
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let model = items[indexPath.row] else { return }
        if model.type == 2 {
            let vc = YHHomeWebViewController()
            vc.url = YHBaseUrlManager.shared.curH5URL() + "articleDetail.html" + "?id=\(model.id)"
            vc.id = model.id
            vc.block = {[weak self] model in
                guard let self = self else { return }
                let arr = self.items
                for (index, targetItem) in arr.enumerated() {
                    guard let target = targetItem else { return }
                    if target.id == model.id {
                        target.is_like = model.is_like
                        target.like_count = model.like_count
                        self.myCollectView.reloadItems(at: [IndexPath.SubSequence(item: index, section: 0)])
                    }
                }
            }
            UIViewController.current?.navigationController?.pushViewController(vc)
        } else if model.type == 1 {
            printLog("直接播放视频")
        }
    }
}

extension YHOtherServiceListViewController: CollectionViewWaterfallLayoutDelegate {
    func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        guard let model = items[indexPath.row] else { return CGSize.zero }
        return CGSize(width: model.img_width_cell, height: model.img_height_cell)
    }
}
