//
//  YHConnectListViewController.swift
//  galaxy
//
//  Created by Dufet on 2025/9/25.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import JXSegmentedView
import UIKit

class YHConnectListViewController: YHBaseViewController {
    let viewModel = YHContactViewModel()
    let matchViewModel = YHMatchUserViewModel()

    var arr: [YHContact] = []

    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.showsVerticalScrollIndicator = false
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.estimatedSectionHeaderHeight = 1.0
        tableView.estimatedSectionFooterHeight = 1.0
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.white
        tableView.register(YHConnectListCell.self, forCellReuseIdentifier: YHConnectListCell.cellReuseIdentifier)
        tableView.es.addYHPullToRefresh {
            self.reguestData(true)
        }
        tableView.es.addInfiniteScrolling {
            self.reguestData(false)
        }
        return tableView
    }()
    
    lazy var noDataView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("暂无内容", kEmptyCommonBgName)
        view.isHidden = true
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navigationBar.isHidden = true
        view.backgroundColor = UIColor.white
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(0)
        }
        view.addSubview(noDataView)
        noDataView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.width.equalTo(KScreenWidth)
            make.height.equalTo(150)
        }
        reguestData(true)
    }
    
    func reguestData(_ isFirstPage: Bool) {
        self.viewModel.getList(isFirstPage) { _, _ in
            self.arr.removeAll()
            self.arr.append(contentsOf: (self.viewModel.contacts))
            self.noDataView.isHidden = self.arr.count > 0
            self.tableView.reloadData()
            self.tableView.es.stopLoadingMore()
            self.tableView.es.stopPullToRefresh()
            if !self.viewModel.hasMore {
                self.tableView.es.noticeNoMoreData()
            }
        }
    }
}

extension YHConnectListViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arr.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHConnectListCell.cellReuseIdentifier, for: indexPath) as? YHConnectListCell else { return UITableViewCell() }
        if 0 <= indexPath.row, indexPath.row < arr.count {
            let model = arr[indexPath.row]
            cell.updateModel(model)
            cell.addFriendBlock = {[weak self] text in
                guard let self = self else { return }
                YHHUD.show(.progress(message: "加载中..."))
                self.matchViewModel.addFriendWithText(text!, yhId: model.yh_id) {
                    success, error in
                    YHHUD.hide()
                    if success {
                        model.type = YHContactRelation.unvalidate.rawValue
                        self.tableView.reloadData()
                        
                    } else {
                        var msg = "申请失败"
                        if let errMsg = error?.errorMsg, !errMsg.isEmpty {
                            msg = errMsg
                        }
                        YHHUD.flash(message: msg)
                    }
                }
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 1.0
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 1.0
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if 0 <= indexPath.row && indexPath.row < arr.count {
            let contact = arr[indexPath.row]
            let vc = YHNewNameCardViewController()
            vc.userId = contact.yh_id
            navigationController?.pushViewController(vc)
        }
    }
}

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