//
//  FrinendsListController.swift

//
//  Created by Leon on 2025/8/13.
//

import JXSegmentedView
import UIKit
class FrinendsListController: CLBaseTableController {
    lazy var headView: FriendsHeartBeatHead = {
        let headView = FriendsHeartBeatHead()
        headView.frame = CGRectMake(0, 0, UIScreen.width, 0) // 60
        
        headView.heightChangeBlock = { [weak self] height in
            self?.headView.height = height
            self?.tableView.tableHeaderView = self?.headView
        }
        headView.isHidden = true
        return headView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationView.isHidden = true

        // Do any additional setup after loading the view.
        setupViews()
        setupDatas()
        setupEvents()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if headView.noticeOnceView.isHidden == false {
            headView.noticeOnceView.tapClose()
        }
    }

    private func setupViews() {
        view.backgroundColor = .clear
        tableView.register(FriendsListCell.self, forCellReuseIdentifier: "FriendsListCell")
        tableView.tableHeaderView = headView
        
        addRefreshHeaderFooter()

        loadData()
    
        if let friendsHeartBeatNoticeConfig = AppCache.fetchCache(key: CacheKey.friendsHeartBeatShowedOnce.rawValue, type: Bool.self), friendsHeartBeatNoticeConfig == true{
            headView.showNoticeOnce(false)
        }else{
            headView.showNoticeOnce(true)
        }
    }

    private func setupDatas() {

    }

    override func loadData() {
        let pageData = RequestPageData()
        pageData.pn = page
        var request = FriendsListRequest()
        request.page = pageData
        let params = request.toNonNilDictionary()
        
        FriendsProvider.request(.heartbeatRelationList(params: params), modelType: ResponseContentPageData<RelationFriend>.self) { [weak self] result in
            self?.tableView.mj_header?.endRefreshing()
            self?.tableView.mj_footer?.endRefreshing()
            switch result {
            case let .success(model):
                if let validDatas = model?.datas {
                    if pageData.pn == 1 {
                        self?.datas = validDatas
                        self?.tableView.mj_footer?.resetNoMoreData()
                        self?.view.setupEmpty(empty: validDatas.count <= 0, msg: "暂无关系")
                    } else {
                        self?.datas.append(contentsOf: validDatas)
                        if validDatas.count <= 0 {
                            self?.tableView.mj_footer?.endRefreshingWithNoMoreData()
                        }
                    }
                    self?.tableView.reloadData()
                }
            case .failure:
                break
            }
        }
        
        if page == 1{
            loadHeartBeatRank()
        }
    }
    
    func loadHeartBeatRank(){
        AIRoleProvider.request(.heartBeatRankGet, modelType: CGFloat.self) {[weak self] result in
            switch result {
            case .success(let model):
                self?.headView.isHidden = false
                self?.headView.config(percent: model)
            case .failure:
                break
            }
        }
    }

    private func setupEvents() {
        NotificationCenter.default.addObserver(self, selector: #selector(notifiyRelationHiddenUpdate), name: AppNotificationName.heartbeatRelationHiddenUpdate.notificationName, object: nil)
    }

    // MARK: - Override

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "FriendsListCell", for: indexPath) as! FriendsListCell
        cell.delegate = self
        if let data = datas[indexPath.row] as? RelationFriend {
            cell.config(data)
        }
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let data = datas[indexPath.row] as? RelationFriend, let aiId = data.aiId else{
            return
        }
        AppRouter.goAIRoleHome(aiId: Int(aiId))
    }
}

extension FrinendsListController {
    @objc func notifiyRelationHiddenUpdate(){
        loadNewData()
    }
}

extension FrinendsListController: FriendsListCellDelegate{
    func friendsCellTapChat(aiId: Int) {
        AppRouter.goChatVC(aiId: aiId)
    }
}

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