//
//  YHServiceListViewController.swift
//  galaxy
//
//  Created by EDY on 2024/4/8.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import JXSegmentedView

class YHServiceListViewController: YHBaseViewController {
    let homeViewModel: YHHomePageViewModel = YHHomePageViewModel()
    var tableHeadView: YHServerTableHeadView!
    var tableFootView: YHServiceTableFootView!
    var sectionView: YHServiceSectionView!
    var classId: Int = 0
    var cell: YHServerHKLifeViewCell!
    var dataSouce: [YHHomeListModel?] = [] {
        didSet {
            homeCollectView.reloadData()
        }
    }
    
    lazy var homeCollectView = {
        // 设置布局方向
        let flowLayout = YHHomeCollectionLayout()
        flowLayout.minimumInteritemSpacing = 7.0
        flowLayout.minimumColumnSpacing = 7.0
        flowLayout.sectionInset = UIEdgeInsets(top: 8, left: 20, bottom: 0, 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.translatesAutoresizingMaskIntoConstraints = false
        collectinoView.alwaysBounceVertical = true
        return collectinoView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
        updateDefaultSearchKeyWord()
    }
    
    func updateDefaultSearchKeyWord() {
        var placeHolder = "香港身份"
        if isHaveLocalSearchRecords() {
            let latestValidSearchWord = getLatestValidSearchWord()
            if !latestValidSearchWord.isEmpty {
                placeHolder = latestValidSearchWord
            }
        }
        tableHeadView.searchPlaceHolder = placeHolder
    }
    
}

extension YHServiceListViewController {
    func loadData() {
        self.tableHeadView.bannarView.dataArr = [YHBannerModel.localDefaultItem()]

        homeViewModel.getHomeBanner(1){[weak self] success, error in
            guard let self = self else { return }
            self.tableHeadView.bannarView.dataArr = self.homeViewModel.banners ?? [YHBannerModel.localDefaultItem()]
        }
        
        homeViewModel.getHomeClassify{[weak self] success, error in
            guard let self = self, let classify = self.homeViewModel.classify  else { return }
            for item in classify {
                let model = item as YHHomeClassifyModel
                if model.id == 1 {
                    self.sectionView.items = model.children
                    if self.classId == 0 {
                        let classifyID = model.children.first?.id ?? 0
                        self.classId = classifyID
                        self.homeViewModel.getList(true, classifyID) {[weak self] success, error in
                            guard let self = self else { return }
                            self.dataSouce = self.homeViewModel.arrHomeNewsData ?? []
                            if self.homeViewModel.hasMoreForHomeNews == false {
                                self.homeCollectView.es.noticeNoMoreData()
                            }
                        }
                    }
                }
            }
        }
    }
    
    func setupUI() {
        gk_navBarAlpha = 0
        gk_navigationBar.isHidden = true
        view.backgroundColor = .white
        sectionView = {
            let view = YHServiceSectionView()
            view.block = {[weak self] model in
                guard let self = self else { return }
                self.homeCollectView.es.resetNoMoreData()
                if homeCollectView.contentOffset.y > -48 {
                    self.homeCollectView.setContentOffset(CGPoint(x: 0, y: -48), animated: false)
                }
                self.classId = model.id
                self.homeViewModel.getList(true, model.id) {[weak self] success, error in
                    guard let self = self else { return }
                    self.dataSouce = self.homeViewModel.arrHomeNewsData ?? []
                    if self.homeViewModel.hasMoreForHomeNews == false {
                        self.homeCollectView.es.noticeNoMoreData()
                    }
                }
            }
            return view
        }()
        
        view.addSubview(homeCollectView)
        homeCollectView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        tableHeadView = YHServerTableHeadView()
        tableHeadView.titleLabel.text = "香港身份攻略"
        tableHeadView.frame = CGRect(x: 0, y: -365 - 48, width: KScreenWidth, height: 365)
        sectionView.frame = CGRect(x: 0, y: -48, width: KScreenWidth, height: 48)
        homeCollectView.addSubview(tableHeadView)
        homeCollectView.addSubview(sectionView)
        homeCollectView.contentInset = UIEdgeInsets(top: 365 + 48, left: 0, bottom: 0, right: 0)
        homeCollectView.delegate = self
        homeCollectView.dataSource = self
        
        homeCollectView.es.addInfiniteScrolling {
            self.loadMoreData()
        }
    }
    
    func loadMoreData() {
        self.homeViewModel.getList(false, self.classId) {[weak self] success, error in
            guard let self = self else { return }
            DispatchQueue.main.asyncAfter(wallDeadline: .now() + 0.35, execute: {
                CATransaction.setDisableActions(true)
                self.dataSouce = self.homeViewModel.arrHomeNewsData ?? []
                CATransaction.commit()
                self.homeCollectView.es.stopLoadingMore()
                if self.homeViewModel.hasMoreForHomeNews == false {
                    self.homeCollectView.es.noticeNoMoreData()
                }
            })
        }
    }
}

extension YHServiceListViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataSouce.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHHomeCollectionViewCell.cellReuseIdentifier, for: indexPath) as! YHHomeCollectionViewCell
        cell.listModel = self.dataSouce[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let model = self.dataSouce[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
                let arr = self.dataSouce
                for (index,targetItem) in arr.enumerated() {
                    guard let target = targetItem else { return }
                    if target.id == item.id {
                        target.is_like = item.is_like
                        target.like_count = item.like_count
                        self.homeCollectView.reloadItems(at: [IndexPath.SubSequence(item: index, section: 0)])
                    }
                }
                
            }
            self.navigationController?.pushViewController(vc)
        } else if model.type == 1 {
            printLog("直接播放视频")
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offset = scrollView.contentOffset.y
        if offset > -48 {
            sectionView.frame.origin.y = offset
        } else {
            sectionView.frame.origin.y = -48
        }
    }
}

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

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