//
//  YHMyGoodFriendsVC.swift
//  galaxy
//
//  Created by edy on 2024/6/17.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHMyGoodFriendsVC: YHBaseViewController {
    
    let viewModel = YHMatchUserViewModel()

    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.estimatedSectionHeaderHeight = 100
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor(hex: 0xF8FAFB)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHMyFriendsCell.self, forCellReuseIdentifier: YHMyFriendsCell.cellReuseIdentifier)
        tableView.register(YHAddFriendCardCell.self, forCellReuseIdentifier: YHAddFriendCardCell.cellReuseIdentifier)
        return tableView
    }()
    
    lazy var emptyDataTipsView: YHMyFriendsNoDataView = {
        let view = YHMyFriendsNoDataView(frame: CGRect(x: 0, y: k_Height_NavigationtBarAndStatuBar, width: KScreenWidth, height: KScreenHeight-k_Height_NavigationtBarAndStatuBar))
        view.bottomBtnClick = {
            [weak self] in
            guard let self = self else { return }
            goTabBarBy(tabType: .community)
            UIViewController.current?.navigationController?.popToRootViewController(animated: true)
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
                NotificationCenter.default.post(name: YhConstant.YhNotification.goConnectionVCNotifiction, object: nil)
            }
        }
        view.isHidden = true
        return view
    }()
    
    var friendsArr: [YHFriendModel] = []
    var friendRequestArr: [YHFriendModel] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navTitle = "我的好友"
        gk_navigationBar.backgroundColor = .white
        self.view.backgroundColor = UIColor(hex: 0xF8FAFB)
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.emptyDataTipsView)
        self.tableView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(16+k_Height_NavigationtBarAndStatuBar)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.requestFriendList()
    }
    
    func createCorner(cell: UITableViewCell, isLastCell: Bool) {
        if isLastCell {
            let corner = UIRectCorner(rawValue: UIRectCorner.bottomLeft.rawValue | UIRectCorner.bottomRight.rawValue)
            cell.createCorner(CGSize(width: 12.0, height: 12.0), corner)
            
        } else {
            cell.layer.mask = nil
        }
    }
}

extension YHMyGoodFriendsVC: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if section == 0 {
            return self.friendRequestArr.count > 0 ? 1 : 0
        }
        return friendsArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: YHAddFriendCardCell.cellReuseIdentifier, for: indexPath) as? YHAddFriendCardCell else { return UITableViewCell() }
            
            cell.cardCount = self.friendRequestArr.count
            if self.friendRequestArr.count > 0 {
                cell.friendModel = self.friendRequestArr[0]
            }
            cell.acceptBlock = {
                [weak self] accept in
                guard let self = self else { return }
                if self.friendRequestArr.count > 0 {
                    let user = self.friendRequestArr[0]
                    YHHUD.show(.progress(message: "加载中..."))
                    self.viewModel.receiveFriendApply(userId: user.yhId, isReceive: accept) {
                        [weak self] success, error in
                        YHHUD.hide()
                        guard let self = self else { return }
                        if success {
                            self.requestFriendList()
                        } else {
                            var msg = "处理失败"
                            if let errMsg = error?.errorMsg, !errMsg.isEmpty {
                                msg = errMsg
                            }
                            YHHUD.flash(message: msg)
                        }
                    }
                }
            }
            return cell
        }
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHMyFriendsCell.cellReuseIdentifier, for: indexPath) as? YHMyFriendsCell else { return UITableViewCell() }
        if 0 <= indexPath.row && indexPath.row < friendsArr.count {
            let friend = self.friendsArr[indexPath.row]
            cell.friendModel = friend
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if indexPath.section == 1 {
            self.createCorner(cell: cell, isLastCell: indexPath.row == self.friendsArr.count-1)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if indexPath.section == 1 {
            if 0 <= indexPath.row && indexPath.row < friendsArr.count {
                let friend = self.friendsArr[indexPath.row]
                let vc = YHNewNameCardViewController()
                vc.userId = friend.yhId
                self.navigationController?.pushViewController(vc)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            if friendRequestArr.count > 0 {
                return 38.0
            }
            return 0.1
        }
        if section == 1 {
            if friendsArr.count > 0 {
                return 52.0
            }
            return 0.1
        }
        return 0.1
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 0 {
            if friendRequestArr.count > 0 {
                return 12
            }
            return 0.1
        }
        return 0.1
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        
        if section == 0 {
            if friendRequestArr.count <= 0 { return view }
            
            let titleLabel = UILabel()
            titleLabel.text = "好友请求(\(self.friendRequestArr.count))"
            titleLabel.textColor = UIColor.mainTextColor
            titleLabel.textAlignment = .left
            titleLabel.font = UIFont.PFSC_M(ofSize: 16)
            view.addSubview(titleLabel)
            titleLabel.snp.makeConstraints { make in
                make.left.equalTo(0)
                make.top.equalTo(0)
                make.height.equalTo(22)
            }
            
        } else if section == 1 {
            
            if friendsArr.count <= 0 { return view }
            
            view.frame = CGRect(x: 0, y: 0, width: KScreenWidth-16.0*2, height: 52)
            view.backgroundColor = .white
            
            let titleLabel = UILabel()
            titleLabel.text = "好友列表"
            titleLabel.textColor = UIColor.mainTextColor
            titleLabel.textAlignment = .left
            titleLabel.font = UIFont.PFSC_M(ofSize: 16)
            view.addSubview(titleLabel)
            
            let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
            let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: corner, cornerRadii: CGSize(width: 6.0, height: 6.0))
            let layer = CAShapeLayer()
            layer.frame = view.bounds
            layer.path = path.cgPath
            view.layer.mask = layer
            
            titleLabel.snp.makeConstraints { make in
                make.left.equalTo(16)
                make.top.equalTo(16)
                make.height.equalTo(22)
            }
        }
        return view
    }
}

extension YHMyGoodFriendsVC {
    
    func requestFriendList() {
        self.viewModel.getMyFriendList { 
            [weak self] _, _ in
            guard let self = self else { return }
            self.friendsArr.removeAll()
            self.friendRequestArr.removeAll()
            if self.viewModel.friendListModel.friends.count > 0 {
                self.friendsArr.append(contentsOf: self.viewModel.friendListModel.friends)
            }
            if self.viewModel.friendListModel.applyFriends.count > 0 {
                self.friendRequestArr.append(contentsOf: self.viewModel.friendListModel.applyFriends)
            }
            self.tableView.reloadData()
            if self.friendsArr.count <= 0 && self.friendRequestArr.count <= 0 {
                self.emptyDataTipsView.isHidden = false
            } else {
                self.emptyDataTipsView.isHidden = true
            }
        }
    }
}
