//
//  YHGalaxyNewsListViewController.swift
//  galaxy
//
//  Created by Dufet on 2025/4/17.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

let yh_newsList = YHGalaxyNewsListViewController()

class YHGalaxyNewsListViewController: YHBaseViewController {
    
    let type: Int = YHMessageType.article.rawValue
    var newsArr: [YHNewsModel] = []
    var currentPage = 1
    var isLastPage = false
    
    let viewModel = YHMsgViewModel()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        tableView.estimatedSectionHeaderHeight = 1.0
        tableView.estimatedSectionFooterHeight = 1.0
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.backgroundView = emptyDataTipsView
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHGalaxyNewsCell.self, forCellReuseIdentifier: YHGalaxyNewsCell.cellReuseIdentifier)
        tableView.es.addYHPullToRefresh {
            self.getMsgList(more: false)
        }

        tableView.es.addInfiniteScrolling {
            self.getMsgList(more: true)
        }
        return tableView
    }()
    
    lazy var emptyDataTipsView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("暂无资讯", kEmptyMessageBgName)
        let topMargin = 310-k_Height_NavigationtBarAndStatuBar
        view.topMargin = topMargin
        view.isHidden = true
        return view
    }()

    override func viewDidLoad() {
        
        super.viewDidLoad()
        gk_navTitle = "银河资讯"
        gk_navigationBar.backgroundColor = .white

        let rightButtonItem = UIBarButtonItem(image: UIImage(named: "msg_clean")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(didCleanBtnClicked))
        gk_navRightBarButtonItem = rightButtonItem
        gk_navItemRightSpace = 16
        
        view.backgroundColor = .init(hex: 0xF8F9FB)
        view.addSubview(tableView)
    
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalToSuperview()
        }
        
        getMsgList()
    }
    
    @objc func didCleanBtnClicked() {
        
        YHCommonAlertView.show("清除未读", "确定要清除所有未读提示吗？", "取消", "确认") {
            
        } callBack: {
            self.markAllMsgsRead()
        }
    }
    
    func getMsgList(more: Bool = false) {
        if isLastPage {
            if more {
                tableView.es.stopLoadingMore()
            } else {
                tableView.es.stopPullToRefresh()
            }
            self.tableView.es.noticeNoMoreData()
            self.tableView.footer?.isHidden = false
            return
        }
        
        if more {
            currentPage += 1
            
        } else {
            currentPage = 1
        }
        
        self.viewModel.getNewsDetailList(type: self.type, page: currentPage) { [weak self] _, isLastPage in
            guard let self = self else { return }
            newsArr.removeAll()
            newsArr.append(contentsOf: self.viewModel.newsDetailList)
            emptyDataTipsView.isHidden = newsArr.count > 0
            self.isLastPage = isLastPage
            if more {
                tableView.es.stopLoadingMore()
            } else {
                tableView.es.stopPullToRefresh()
            }
            if isLastPage {
                self.tableView.es.noticeNoMoreData()
                self.tableView.footer?.isHidden = false
            }
            self.tableView.reloadData()
        }
    }
    
    func markAllMsgsRead() {
        YHHUD.show(.progress(message: "清除中..."))
        self.viewModel.readMessages(type: self.type, msgIds: nil, isAllRead: true) { [weak self] success, error in
            YHHUD.hide()
            guard let self = self else { return }
            if success {
                YHHUD.flash(message: "清除成功")
                for item in self.newsArr {
                    item.is_read = true
                }
                self.tableView.reloadData()
                return
            }
            var msg = "清除失败"
            if let error = error {
                if error.errorMsg.count > 0 {
                    msg = error.errorMsg
                }
            }
            YHHUD.flash(message: msg)
        }
    }
    
    func markRead(_ model: YHNewsModel) {
        if let id = Int(model.id) {
            self.viewModel.readMessages(type: self.type, msgIds: [id], isAllRead: false) { [weak self] success, _ in
                guard let self = self else { return }
                if success {
                    for msgItem in newsArr {
                        if msgItem.article_id == model.article_id, msgItem.id == model.id {
                            msgItem.is_read = true
                            break
                        }
                    }
                    self.tableView.reloadData()
                    return
                }
            }
        }
    }
    
     func enterDetail(_ item: YHNewsModel) {
        if item.news_type == 2 { // 图文
            let vc = YHHomeWebViewController()
            vc.url = YHBaseUrlManager.shared.curH5URL() + "articleDetail.html" + "?id=\(item.article_id)"
            vc.id = item.article_id
            UIViewController.current?.navigationController?.pushViewController(vc)
            return
            
        } else if item.news_type == 1 { // 视频
            if !item.media_url.isEmpty, let _ = URL(string: item.media_url) {
                let vc = YHVideoPlayerVC()
                if !item.media_transcode_url.isEmpty {
                    vc.url = item.media_transcode_url
                } else {
                    vc.url = item.media_url
                }
                vc.id = item.article_id
                UIViewController.current?.navigationController?.pushViewController(vc)
            }
            return
            
        } else if item.news_type == 4 {  // 纯网页
            let vc = YHWebViewViewController()
            vc.url = item.url
            vc.navTitle = item.title
            UIViewController.current?.navigationController?.pushViewController(vc)
        }
    }
}

extension YHGalaxyNewsListViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return newsArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHGalaxyNewsCell.cellReuseIdentifier, for: indexPath) as? YHGalaxyNewsCell else { return UITableViewCell() }
        if 0 <= indexPath.row && indexPath.row < newsArr.count {
            let item = newsArr[indexPath.row]
            cell.updateModel(item)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if 0 <= indexPath.row && indexPath.row < newsArr.count {
            let item = newsArr[indexPath.row]
            self.enterDetail(item)
            self.markRead(item)
        }
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 1.0
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 1.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        return UIView()
    }
}
