//
//  QSLRequestController.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2024/12/5.
//

import UIKit
import CRRefresh

class QSLRequestController: QSLBaseController {
    
    lazy var requestTableView: UITableView = {
        
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableViewNeverAdjustContentInset()
        tableView.bounces = true
        tableView.isUserInteractionEnabled = true
        tableView.isScrollEnabled = false
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.register(cellClass: QSLRequestCell.self)
        
        tableView.cr.addHeadRefresh(animator: NormalHeaderAnimator()) { [weak self] in
            self?.requestRequestList()
        }
        
        return tableView
    }()
    
    var requestList: [QSLRequestModel] = [QSLRequestModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initializeView()
        
        requestTableView.cr.beginHeaderRefresh()
        
        NotificationCenter.default.addObserver(self, selector: #selector(requestRequestList), name: QSLNotification.QSLRefreshRequest, object: nil)
        
        gravityInstance?.track(QSLGravityConst.message_request_show)
    }
    
    override func viewWillAppear(_ animated:Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: animated)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: animated)
    }
}

extension QSLRequestController {
    
    // 请求好友请求列表
    @objc func requestRequestList() {
        
        self.requestList.removeAll()
        QSLNetwork().request(.requestList(dict: [:])) { response in
            
            self.requestTableView.cr.endHeaderRefresh()
            let requestList = response.mapArray(QSLRequestModel.self, modelKey: "data>list")
            self.requestList = requestList
            self.requestTableView.reloadData()
        } fail: { code, error in
            
            self.requestTableView.cr.endHeaderRefresh()
            self.requestTableView.reloadData()
        }
    }
}

extension QSLRequestController: QSLRequestCellDelegate {
    
    // 拒绝点击
    func refuseBtnAction(model: QSLRequestModel) {
        
        gravityInstance?.track(QSLGravityConst.message_request_disagree)
        QSLNetwork().request(.requestRefuse(dict: ["id": model.requestId])) { response in
            
            // 发送通知
            NotificationCenter.default.post(name: QSLNotification.QSLRefreshRequest, object: nil)
        } fail: { code, error in
            self.view.toast(text: error)
        }
    }
    
    // 同意点击
    func accpetBtnAction(model: QSLRequestModel) {
        
        gravityInstance?.track(QSLGravityConst.message_request_agree)
        gravityInstance?.track(QSLGravityConst.message_request_agree_show)
        QSLAlertView.alert(view: self.view, title: "添加好友", content: "1.您同意添加该用户为好友，则视为您同意本应用合法收集储存和使用信息；\n2.并同意将您的位置、轨迹等信息分享给该好友。", isOneBtn: true, oneBtnText: "确认添加", oneBtnClosure:  {
            gravityInstance?.track(QSLGravityConst.message_request_agree_show_confirm)
            QSLNetwork().request(.requestAccept(dict: ["id": model.requestId])) { response in
                
                // 发送通知
                NotificationCenter.default.post(name: QSLNotification.QSLRefreshRequest, object: nil)
            } fail: { code, error in
                self.view.toast(text: error)
            }
        }, closeBtnClosure: {
            
            gravityInstance?.track(QSLGravityConst.message_request_agree_show_cancel)
        })
    }
}

// MARK: - 设置Tableview
extension QSLRequestController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.requestList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let cell = tableView.dequeueReusableCell(cellType: QSLRequestCell.self, cellForRowAt: indexPath)
        cell.selectionStyle = .none
        let model = self.requestList[indexPath.row]
        cell.config(model: model)
        cell.delegate = self
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 117.rpx
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 1.rpx
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.0001
    }
    
}


extension QSLRequestController {
    
    func initializeView() {
        
        self.view.addSubview(requestTableView)
        requestTableView.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(0)
            make.top.equalTo(0)
        }
    }
}
