//
//  YHHomeInformationViewController.swift
//  galaxy
//
//  Created by edy on 2024/7/18.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import JXSegmentedView

class YHHomeInformationViewController: YHBaseViewController {

    lazy var viewModel: YHHomePageViewModel = {
        let viewModel = YHHomePageViewModel()
        return viewModel
    }()
    
    var sectionItems: [YHHomeInfoClassifyModel?] = []
    
    lazy var collectView = {
        // 设置布局方向
        let flowLayout = YHHomeCollectionLayout()
        flowLayout.minimumInteritemSpacing = 7.0
        flowLayout.minimumColumnSpacing = 7.0
        let collectinoView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collectinoView.backgroundColor = .white
        collectinoView.register(YHHomeCollectionViewCell.self, forCellWithReuseIdentifier: YHHomeCollectionViewCell.cellReuseIdentifier)
        collectinoView.register(YHHomeInfoSectionHeadView.self, forSupplementaryViewOfKind: CollectionViewWaterfallElementKindSectionHeader, withReuseIdentifier: YHHomeInfoSectionHeadView.reuseIdentifier)
        collectinoView.delegate = self
        collectinoView.dataSource = self
        collectinoView.translatesAutoresizingMaskIntoConstraints = false
        collectinoView.alwaysBounceVertical = true
        collectinoView.showsVerticalScrollIndicator = false
        collectinoView.es.addYHPullToRefresh {
            self.requetData()
        }
        collectinoView.es.addInfiniteScrolling {
            self.getTheNewestInfoList(isFirstPage: false, completion: nil)
        }
        return collectinoView
    }()
    
    lazy var noDataView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("暂无内容", kEmptyCommonBgName)
        view.backgroundColor = .white
        view.topMargin = 150
        view.isHidden = true
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navigationBar.isHidden = true
        self.view.backgroundColor = .white
        self.view.addSubview(self.collectView)
        self.view.addSubview(self.noDataView)
        self.collectView.snp.makeConstraints { make in
            make.top.equalTo(10)
            make.bottom.equalToSuperview()
            make.left.equalTo(20)
            make.right.equalTo(-20)
        }
        self.noDataView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalToSuperview()
        }
        requetData()
    }
    
    func requetData() {
       self.getClassifies {
           self.getTheNewestInfoList(isFirstPage: true) {
               let count = self.viewModel.arrHomeNewsData?.count ?? 0
               if count <= 0, self.sectionItems.count <= 0 {
                   self.noDataView.isHidden = false
               } else {
                   self.noDataView.isHidden = true
               }
           }
        }
    }
}

// MARK: - UICollectionViewDelegate, UICollectionViewDataSource
extension YHHomeInformationViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 最新资讯
        return self.viewModel.arrHomeNewsData?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        if kind == CollectionViewWaterfallElementKindSectionHeader {
            guard let headerView: YHHomeInfoSectionHeadView = collectionView.dequeueReusableSupplementaryView(ofKind: CollectionViewWaterfallElementKindSectionHeader, withReuseIdentifier: YHHomeInfoSectionHeadView.reuseIdentifier, for: indexPath) as? YHHomeInfoSectionHeadView else {
                return UICollectionReusableView()
            }
            headerView.items = sectionItems
            return headerView
        }
        return UICollectionReusableView()
    }
    
    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 = self.viewModel.arrHomeNewsData?[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let model = self.viewModel.arrHomeNewsData?[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 = { item in
                if let arr = self.viewModel.arrHomeNewsData {
                    for (index, targetItem) in arr.enumerated() {
                        if targetItem.id == item.id {
                            targetItem.is_like = item.is_like
                            targetItem.like_count = item.like_count
                            self.collectView.reloadItems(at: [IndexPath.SubSequence(item: index, section: 0)])
                        }
                    }
                }
            }
            self.navigationController?.pushViewController(vc)
        } else if model.type == 1 {
            printLog("直接播放视频")
        }
    }
}

// MARK: - CollectionViewWaterfallLayoutDelegate
extension YHHomeInformationViewController: CollectionViewWaterfallLayoutDelegate {
    func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        
        let count = self.viewModel.arrHomeNewsData?.count ?? 0
        if indexPath.row < count {
            guard let model = self.viewModel.arrHomeNewsData?[indexPath.row] else { return CGSize.zero }
            return CGSize(width: model.img_width_cell, height: model.img_height_cell)
        }
        
        let width = (KScreenWidth - 47) / 2
        return CGSize(width: width, height: 140.0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, heightForHeaderInSection section: Int) -> Float {
        
        if self.sectionItems.count <= 0 {
            return 0.0
        }
        var row = self.sectionItems.count/3
        if self.sectionItems.count%3 != 0 {
            row += 1
        }
        let listHeight = Float(Double(row) * kHomeItemHeight)
        let totalHeight = listHeight + 4.0 + 0.5 + 65.0
        return totalHeight
    }
}

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

extension YHHomeInformationViewController {
    
    // 获取栏目
    func getClassifies(_ completion: (() -> Void)?) {
        self.viewModel.getHomeInfoClassifies { _, _ in
            self.sectionItems.removeAll()
            self.sectionItems.append(contentsOf: self.viewModel.classifyArr)
            self.collectView.reloadData()
            completion?()
        }
    }
    // 获取最新资讯
    func getTheNewestInfoList(isFirstPage: Bool, completion: (() -> Void)?) {
        self.viewModel.getList(isFirsPage: isFirstPage) { _, _ in
            self.collectView.reloadData()
            self.collectView.es.stopPullToRefresh()
            self.collectView.es.stopLoadingMore()
            if self.viewModel.hasMoreForHomeNews == false {
                self.collectView.es.noticeNoMoreData()
                self.collectView.footer?.alpha = 1
            }
            completion?()
        }
    }
}
