//
//  QSLMessageController.swift
//  QuickSearchLocation
//
//  Created by mac on 2024/4/10.
//

import UIKit
import CRRefresh

class QSLMessageController: QSLBaseController {
    
    lazy var topBgView: UIView = {
       
        let view = UIView()
        view.gradientBackgroundColor(color1: .hexStringColor(hexString: "#EEFFF5"), color2: .hexStringColor(hexString: "#EEFFF5", alpha: 0), width: QSLConst.qsl_kScreenW, height: 52.rpx + QSLConst.qsl_kStatusBarFrameH, direction: .vertical)
        return view
    }()
    
    lazy var titleLabel: UILabel = {
       
        let label = UILabel()
        label.text("消息中心")
        label.boldFont(18)
        label.textColor = QSLColor.Color_202020
        return label
    }()
    
    lazy var allMessBtn: UIButton = {
       
        let btn = UIButton()
        btn.image(UIImage(named: "message_all_btn"))
        btn.addTarget(self, action: #selector(allMessBtnAction), for: .touchUpInside)
        return btn
    }()
    
    lazy var messageTableView: 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.contentInsetAdjustmentBehavior = .never
        tableView.register(cellClass: QSLMessageTableViewCell.self)
        
        tableView.cr.addHeadRefresh(animator: NormalHeaderAnimator()) { [weak self] in
            self?.requestAllList()
        }
        
        return tableView
    }()
    
    // 信息列表
    var messageList: [QSLMessageModel] = [QSLMessageModel]()
    
    var requestModel: QSLRequestModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initializeView()
        
        messageTableView.cr.beginHeaderRefresh()
        
        NotificationCenter.default.addObserver(self, selector: #selector(requestAllList), name: QSLNotification.QSLLogin, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(requestAllList), name: QSLNotification.QSLLogout, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(requestAllList), name: QSLNotification.QSLRefreshRequest, object: nil)
    }
    
    // 点击新的好友按钮
    @objc func allMessBtnAction() {
        
        let vc = QSLRequestController()
        vc.title = "新的好友"
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension QSLMessageController {
    
    // 请求全部
    @objc func requestAllList() {
        
        requestRequestList {
            self.requestMessage()
        }
    }
    
    // 请求好友请求列表
    func requestRequestList(complete: @escaping () -> ()) {
        
        self.requestModel = nil
        QSLNetwork().request(.requestList(dict: [:])) { response in
            
            let requestList = response.mapArray(QSLRequestModel.self, modelKey: "data>list")
            if requestList.count > 0 {
                self.requestModel = requestList.first
            }
            complete()
        } fail: { code, error in
            complete()
        }
    }
    
    // 请求消息列表
    func requestMessage() {
        
        self.messageList.removeAll()
        QSLNetwork().request(.messageList(dict: [:])) { response in
            
            self.messageTableView.cr.endHeaderRefresh()
            let messageList = response.mapArray(QSLMessageModel.self, modelKey: "data>list")
            self.messageList = messageList
            
            for message in self.messageList {
                if message.type == 2 {
                    gravityInstance?.track(QSLGravityConst.message_disagree_show)
                } else if message.type == 3 {
                    gravityInstance?.track(QSLGravityConst.message_agree_show)
                } else if message.type == 4 {
                    gravityInstance?.track(QSLGravityConst.message_resort_show)
                }
            }
            self.messageTableView.reloadData()
        } fail: { code, error in
            self.messageTableView.cr.endHeaderRefresh()
        }
    }
}

extension QSLMessageController: QSLMessageHeaderViewDelegate, QSLMessageTableViewCellDelegate {
    
    // 电话联系
    func contactBtnAction(phone: String) {
        
        gravityInstance?.track(QSLGravityConst.message_resort_click)
        // 创建电话拨号的URL
        if let url = URL(string: "tel://\(phone)"), UIApplication.shared.canOpenURL(url) {
            // 打开URL
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
    
    // 拒绝点击
    func refuseBtnAction(model: QSLRequestModel) {
        
        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) {
        
        QSLAlertView.alert(view: self.view, title: "添加好友", content: "1.您同意添加该用户为好友，则视为您同意本应用合法收集储存和使用信息；\n2.并同意将您的位置、轨迹等信息分享给该好友。", isOneBtn: true, oneBtnText: "确认添加", oneBtnClosure:  {
            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)
            }
        })
    }
    
    func jumpToRequest() {
        allMessBtnAction()
    }
}

// MARK: - 设置Tableview
extension QSLMessageController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.messageList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let cell = tableView.dequeueReusableCell(cellType: QSLMessageTableViewCell.self, cellForRowAt: indexPath)
        cell.selectionStyle = .none
        let model = self.messageList[indexPath.row]
        cell.config(model: model)
        cell.delegate = self
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = self.messageList[indexPath.row]
        if QSLMessageType(rawValue: model.type) == .resort {
            return 88.rpx
        }
        return 72.rpx
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if let _ = self.requestModel {
            return 164.rpx
        }
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.0001
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if var requestModel = self.requestModel {
            let view = QSLMessageHeaderView()
            view.delegate = self
            view.config(model: requestModel)
            return view
        }
        return nil
    }
    
}

extension QSLMessageController {
    
    func initializeView() {
        
        self.view.backgroundColor = .white
        
        self.view.addSubview(topBgView)
        topBgView.snp.makeConstraints { make in
            make.left.top.right.equalTo(0)
            make.height.equalTo(52.rpx + QSLConst.qsl_kStatusBarFrameH)
        }
        
        self.view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(20.rpx)
            make.top.equalTo(QSLConst.qsl_kStatusBarFrameH + 16.rpx)
        }
        
        self.view.addSubview(allMessBtn)
        allMessBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 26.rpx, height: 26.rpx))
            make.right.equalTo(-20.rpx)
            make.centerY.equalTo(titleLabel.snp.centerY)
        }
        
        self.view.addSubview(messageTableView)
        messageTableView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.top.equalTo(topBgView.snp.bottom)
            make.bottom.equalTo(-QSLConst.qsl_kTabbarFrameH)
        }
    }
}
