//
//  WP_NewestVC.swift
//  WallpaperHD_Live
//
//  Created by 忆海16 on 2024/7/22.
//

import UIKit
import JXSegmentedView
import MJRefresh
import SDWebImage

class WP_NewestVC: WP_RootVC {
    @IBOutlet weak var collectionView: UICollectionView!
    
    var newestWallpapers: [WallpaperData] = []
    
    
    var currentPage: Int = 1 // 当前页数
    let pageSize: Int = 10 // 每页加载的数量
    
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setCollectionView()
        setRefresh()
    }
    
    
    @objc func setRefresh(){
        refreshData()
        
        header.setRefreshingTarget(self, refreshingAction: #selector(WP_NewestVC.setRefresh))
        // 现在的版本要用mj_header
        
        header.setTitle("pull-to-refresh", for: .idle)
        header.setTitle("Release updates", for: .pulling)
        header.setTitle("Refreshing...", for: .refreshing)
        self.collectionView.mj_header = header
        
        
        // 上拉刷新
        footer.setRefreshingTarget(self, refreshingAction: #selector(WP_NewestVC.loadMoreData))
        footer.setTitle("Pull up loading", for: .idle)
        footer.setTitle("Release Load", for: .pulling)
        footer.setTitle("Loading...", for: .refreshing)
        self.collectionView.mj_footer = footer
        
        
        header.beginRefreshing()
        //        footer.beginRefreshing()
        
        
    }
    // 下拉刷新
    @objc func refreshData() {
        currentPage = 1
        settypeNetwork()
    }
    
    // 上拉加载更多
    @objc func loadMoreData() {
        currentPage += 1
        settypeNetwork()
    }
    
    func setCollectionView(){
        collectionView.delegate = self
        collectionView.dataSource = self
        
        // 设置 collection view 的布局
        let layout = CustomCollectionViewFlowLayout()
        collectionView.collectionViewLayout = layout
        layout.scrollDirection = .vertical
        
        collectionView.register(UINib(nibName: "WP_WallpaperCollectionCell", bundle: nil), forCellWithReuseIdentifier: "WP_WallpaperCollectionCell")
        
    }
    func settypeNetwork(){
        // 读取 JSON 文件路径
        guard let jsonFilePath = Bundle.main.path(forResource: "my_wallpaper", ofType: "json") else {
            fatalError("Unable to locate my_wallpaper.json file.")
        }
        
        // 读取 JSON 数据
        do {
            // 读取 JSON 数据
            let jsonData = try Data(contentsOf: URL(fileURLWithPath: jsonFilePath))
            
            // 尝试将 JSON 数据转换为 Swift 对象
            let decoder = JSONDecoder()
            let wallpaperModels = try decoder.decode([WallpaperModel].self, from: jsonData)
            
            var newwallpaperarr:[WallpaperData] = []
            // 遍历解析后的 WallpaperModel 对象数组
            for wallpaperModel in wallpaperModels {
                // 根据名称将数据放入不同的数组中
                switch wallpaperModel.name {
                case "Newest":
                    newwallpaperarr = wallpaperModel.data
                default:
                    break
                }
            }
            if currentPage == 1 {
                        // 只取前10条数据
                        let firstTenWallpapers = Array(newwallpaperarr.prefix(10))
                self.newestWallpapers = firstTenWallpapers
                        collectionView.reloadData()
                        collectionView.mj_header?.endRefreshing()
                    } else {
                        // 上拉加载更多
                        let startIndex = currentPage * pageSize
                        let moreWallpapers = Array(newwallpaperarr.prefix(startIndex))
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1.5){
                            self.newestWallpapers = moreWallpapers
                            self.collectionView.reloadData()
                            self.collectionView.mj_footer?.endRefreshing()

                                }
                    }
            
        } catch {
            print("Error reading or parsing JSON file: \(error)")
        }
    }
}
extension WP_NewestVC:JXSegmentedListContainerViewListDelegate{
    func listView() -> UIView {
        return view
    }
}
extension WP_NewestVC:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return self.newestWallpapers.count
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WP_WallpaperCollectionCell", for: indexPath)as!WP_WallpaperCollectionCell
        let model = self.newestWallpapers[indexPath.row]
        if let imageURL = URL(string: model.previewThumb ?? "") {
            cell.wpImagV.sd_setImage(with: imageURL, placeholderImage: UIImage(named: "Rectangle"))
        }
        
        return cell
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let vc = WP_WallPaPerDetailsVC()
        vc.type = 2
        vc.modeltype = self.newestWallpapers[indexPath.row]
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
}
