//
//  YHLifeViewController.swift
//  galaxy
//
//  Created by EDY on 2024/7/19.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import JXSegmentedView
import ESPullToRefresh
import Lottie

class YHLifeViewController: YHBaseViewController {
    var sectionView: YHLifeSectionView!
    var tableView: UITableView!
    var headView = YHLifeHeadView()
    var viewModel: YHHomePageViewModel = YHHomePageViewModel()
    var selectSubTab: YHHomeLifeCategoryModel?
    var selectSubIndex: Int = -1
    var hideFlag: Bool = true

    lazy var myCollectView = {
        // 设置布局方向
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: (KScreenWidth - 52)/2, height: 222)
        flowLayout.minimumInteritemSpacing = 12.0
        flowLayout.minimumLineSpacing = 12.0
        flowLayout.scrollDirection = .vertical
        
        let collectinoView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collectinoView.backgroundColor = .white
//        collectinoView.contentInset = UIEdgeInsets(top: 16, left: 20, bottom: 0, right: 20)
        collectinoView.register(YHLookCollectionViewCell.self, forCellWithReuseIdentifier: YHLookCollectionViewCell.cellReuseIdentifier)
        collectinoView.register(YHLookNodataCollectionViewCell.self, forCellWithReuseIdentifier: YHLookNodataCollectionViewCell.cellReuseIdentifier)
        collectinoView.register(YHlifeCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: YHlifeCollectionReusableView.reuseIdentifier)
        collectinoView.delegate = self
        collectinoView.dataSource = self
        collectinoView.translatesAutoresizingMaskIntoConstraints = false
        collectinoView.alwaysBounceVertical = true
        collectinoView.showsHorizontalScrollIndicator = false
        collectinoView.showsVerticalScrollIndicator = false
        return collectinoView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        loadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
    }
}

extension YHLifeViewController {
    func loadData() {
        let params: [String: Any] = ["pid": 3]
        self.viewModel.getGoodsCategory(params: params) {
            [weak self] _, _ in
            self?.tableView.es.stopPullToRefresh()
            guard let self = self else { return }
            let items = self.viewModel.categoryArr.map { $0?.name }
            let result = items.compactMap { $0 }
            self.sectionView.items = result
            if selectSubIndex == -1 {
                selectSubIndex = 0
                self.selectSubTab = self.viewModel.categoryArr.first ?? YHHomeLifeCategoryModel()
            } else {
                
                if self.viewModel.categoryArr.count > selectSubIndex {
                    self.selectSubTab = self.viewModel.categoryArr[selectSubIndex]
                } else {
                    selectSubIndex = 0
                    self.selectSubTab = self.viewModel.categoryArr.first ?? YHHomeLifeCategoryModel()
                }
            }
            
            getDetailImages()
        }
        
        self.viewModel.getLiveList {[weak self] _, _ in
            guard let self = self else { return }
            self.myCollectView.reloadData()
        }
        
        self.viewModel.getSchedulLiveList {[weak self] _, _ in
            guard let self = self else { return }
            self.myCollectView.reloadData()
        }
    }
    
    func getDetailImages() {
        if let selectItem = self.selectSubTab {
            let params: [String: Any] = ["categoryId": "3",
                                        "levelId": selectItem.id]
            self.viewModel.getGoodsCategoryDetail(params: params) {
                [weak self] _, _ in
                guard let self = self else { return }
                guard let url = URL(string: selectItem.image) else { return }
                self.headView.imageView.kf.setImage(with: url)
                if self.viewModel.detailModel.products.count == 0 {
                    let label = UILabel(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: self.view.height - 44 - KScreenWidth - 16))
                    label.text = "商品未上架，好货不怕晚，敬请期待！"
                    label.textColor = UIColor.mainTextColor30
                    label.font = UIFont.PFSC_R(ofSize: 14)
                    label.textAlignment = .center
                    self.tableView.tableFooterView = label
                } else {
                    self.tableView.tableFooterView = UIView()
                }
                self.tableView.reloadData()
            }
        }
    }
    
    @objc func didJumpToEduTab() {
        
        let index: Int = 1
        if index < self.viewModel.categoryArr.count {
            selectSubIndex = index
            self.selectSubTab = self.viewModel.categoryArr[index]
            self.getDetailImages()
            self.sectionView.selectIndex = index
        }
    }
    
    func setupUI() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(didJumpToEduTab), name: YhConstant.YhNotification.didJumpToHomePageLifeEduTabNotification, object: nil)
        
        gk_navBarAlpha = 0
        gk_navigationBar.isHidden = true
        view.backgroundColor = .white
        sectionView = {
            let view = YHLifeSectionView()
            view.block = {[weak self] itemIndex in
                guard let self = self else { return }
                selectSubIndex = itemIndex
                self.selectSubTab = self.viewModel.categoryArr[itemIndex]
                self.getDetailImages()
            }
            return view
        }()
        view.addSubview(sectionView)
        sectionView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(44)
        }
        headView.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenWidth + 28)
        tableView = {
            let tableView = UITableView(frame: .zero, style: .grouped)
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.showsHorizontalScrollIndicator = false
            tableView.showsVerticalScrollIndicator = false
            tableView.dataSource = self
            tableView.delegate = self
            tableView.tableHeaderView = headView
            tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 0.01))
            tableView.register(cellWithClass: YHLifeItemTableViewCell.self)
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.top.equalTo(44)
        }
        
        if !hideFlag {
            tableView.es.addYHPullToRefresh {
                self.loadData()
            }
        }
         
        sectionView.isHidden = hideFlag
        tableView.isHidden = hideFlag
        
        view.addSubview(myCollectView)
        myCollectView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
        }
        
        myCollectView.es.addYHPullToRefresh {
            self.loadData()
            self.myCollectView.es.stopPullToRefresh()
        }
         
        myCollectView.isHidden = !hideFlag
    }
    
    func checkLogin() -> Bool {
        if YHLoginManager.shared.isLogin() == false {
            YHOneKeyLoginManager.shared.oneKeyLogin()
            return false
        }
        return true
    }
}

extension YHLifeViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.detailModel.products.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YHLifeItemTableViewCell.self)
        cell.dataSource = self.viewModel.detailModel.products[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 124
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        YHAnalytics.track("APP_LiveListPage_ClickLiveStream")

        let model = self.viewModel.detailModel.products[indexPath.row]
        
        let vc = YHLifeDetailViewController()
        vc.tabId =  self.selectSubTab?.id ?? ""
        vc.productModel = model
        vc.codeUrl = self.viewModel.detailModel.imageURLDefault
        vc.downloadUrl = self.viewModel.detailModel.imageURLDefaultDownload
        self.navigationController?.pushViewController(vc)
    }
}

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

extension YHLifeViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if self.viewModel.liveArr.count == 0 {
            return 1
        }
        return self.viewModel.liveArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if self.viewModel.liveArr.count == 0 {
            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHLookNodataCollectionViewCell.cellReuseIdentifier, for: indexPath) as? YHLookNodataCollectionViewCell else {
                return UICollectionViewCell()
            }
            return cell
        }
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHLookCollectionViewCell.cellReuseIdentifier, for: indexPath) as?  YHLookCollectionViewCell else {
            return UICollectionViewCell()
        }
        cell.dataSource = self.viewModel.liveArr[indexPath.row]
        
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // 跳转直播 文哥代办
        guard self.viewModel.liveArr.count > indexPath.row else {
            return
        }
        if !checkLogin() {
            return
        }
        let item = self.viewModel.liveArr[indexPath.row]
        let playbackInfo = YHPlayerManager.PlaybackInfo(id: item.id, url: nil, title: item.live_title, roomId: item.room_id.count > 0 ? item.room_id : nil, uid: nil, isLive: true, scene: .fullscreen)
        YHPlayerManager.shared.enterLive(from: nil, playbackInfo: playbackInfo)
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionFooter {
            guard let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: YHlifeCollectionReusableView.reuseIdentifier, for: indexPath) as? YHlifeCollectionReusableView else {
                return YHlifeCollectionReusableView()
            }
            // 配置 footerView
            footerView.dataSource = self.viewModel.schedulLiveArr
            return footerView
        }
        return UICollectionReusableView()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        if self.viewModel.schedulLiveArr.count != 0 {
            let height = 50.0 + 104.0 * Double(self.viewModel.schedulLiveArr.count)
            return CGSize(width: KScreenWidth, height: height) // 根据需要设置高度
        }
        return CGSize(width: KScreenWidth, height: 0) // 根据需要设置高度
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if self.viewModel.liveArr.count == 0 {
            return CGSize(width: KScreenWidth - 40, height: 250)
        }
        return CGSize(width: (KScreenWidth - 52)/2, height: 222)
    }
}

class YHLookCollectionViewCell: UICollectionViewCell {
    static let cellReuseIdentifier = "YHLookCollectionViewCell"
    
    var lookImageView: UIImageView!
    var flagImageView: LottieAnimationView!
    var headImageView: UIImageView!
    var titleLabel: UILabel!
    var nameLabel: UILabel!
    
    var dataSource: YHLiveModel? {
        didSet {
            updataAllSubViews()
        }
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    private func setupUI() {
        lookImageView = {
            let imageView = UIImageView()
            imageView.image = UIImage(named: "home_look_bg")
            return imageView
        }()
        contentView.addSubview(lookImageView)
        lookImageView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(162)
        }
        
        flagImageView = {
            let view = LottieAnimationView(name: "live")
            view.backgroundColor = UIColor.black.withAlphaComponent(0.6)
            view.loopMode = .loop
            return view
        }()
        contentView.addSubview(flagImageView)
        flagImageView.snp.makeConstraints { make in
            make.top.left.equalTo(8)
            make.width.height.equalTo(16)
        }
        
        headImageView = {
            let imageView = UIImageView()
            imageView.image = UIImage(named: "home_look_head")
            imageView.layer.cornerRadius = 10
            imageView.layer.masksToBounds = true
            return imageView
        }()
        contentView.addSubview(headImageView)
        headImageView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.width.height.equalTo(20)
            make.bottom.equalTo(-8)
        }
        
        titleLabel = {
            let label = UILabel()
            label.text = "双11高才最强返场"
            label.textColor = UIColor.mainTextColor
            label.font = UIFont.PFSC_R(ofSize: 14)
            return label
        }()
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(-32)
            make.height.equalTo(20)
        }
        
        nameLabel = {
            let label = UILabel()
            label.text = "高才专家社"
            label.textColor = UIColor(hex: 0x6d788a)
            label.font = UIFont.PFSC_R(ofSize: 12)
            return label
        }()
        contentView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { make in
            make.left.equalTo(24)
            make.height.equalTo(20)
            make.bottom.equalTo(-8)
            make.right.equalToSuperview()
        }
        flagImageView.play()
    }
    
    func updataAllSubViews() {
        guard let dataSource = dataSource else { return }
        lookImageView.kf.setImage(with: URL(string: dataSource.live_image))
        titleLabel.text = dataSource.live_title
        headImageView.kf.setImage(with: URL(string: dataSource.avatar))
        nameLabel.text = dataSource.account
    }
    
}

class YHLookNodataCollectionViewCell: UICollectionViewCell {
    static let cellReuseIdentifier = "YHLookNodataCollectionViewCell"
    
    lazy var noDataView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("暂无直播", kEmptyCommonBgName)
        return view
    }()

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    private func setupUI() {
        contentView.addSubview(noDataView)
        noDataView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.width.equalToSuperview()
            make.height.equalTo(150)
        }

    }
    
}
