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

import UIKit
import CRRefresh
import WMZDropDownMenu

class QSLFriendController: QSLBaseController {
    
    var friendList: [QSLUserModel] = [QSLUserModel]()
    
    lazy var friendBg: UIImageView = {
       
        let imageView = UIImageView()
        imageView.image = UIImage(named: "mine_bg")
        return imageView
    }()
    
    lazy var friendTitle: UIImageView = {
        
        let imageView = UIImageView()
        imageView.image = UIImage(named: "friends_title")
        return imageView
    }()
    
    lazy var friTableView: 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 = true
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.register(cellClass: QSLFriendTableViewCell.self)
        
        tableView.cr.addHeadRefresh(animator: NormalHeaderAnimator()) { [weak self] in
            self?.requestFriendList()
        }
        
        return tableView
    }()
    
    lazy var bottomView: UIView = {
       
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 12.rpx
        view.layer.shadowOffset = CGSize(width: 0, height: -1)
        view.layer.shadowColor = UIColor.hexStringColor(hexString: "#A7A7A7", alpha: 0.1).cgColor
        view.layer.shadowOpacity = 5
        view.layer.shadowRadius = 0
        return view
    }()
    
    lazy var friAddBtn: UIButton = {
       
        let btn = UIButton()
        btn.addRadius(radius: 22.rpx)
        btn.gradientBackgroundColor(color1: .hexStringColor(hexString: "#15CBA1"), color2: .hexStringColor(hexString: "#1FE0BA"), width: QSLConst.qsl_kScreenW - 32.rpx, height: 44.rpx, direction: .horizontal)
        btn.image(UIImage(named: "home_friends_header_add_icon"))
        btn.title("添加好友")
        btn.mediumFont(16)
        btn.textColor(.white)
        btn.setImageTitleLayout(.imgLeft, spacing: 0)
        btn.addTarget(self, action: #selector(addButtonAction), for: .touchUpInside)
        return btn
    }()
    
    lazy var resortBtn: UIButton = {
       
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "friends_resort_btn"), for: .normal)
        btn.addTarget(self, action: #selector(resortBtnAction), for: .touchUpInside)
        return btn
    }()
    
    private var popView: QSLPopView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initializeView()
        
        friendList.append(QSLBaseManager.shared.userModel)
        self.friTableView.reloadData()
        
        self.friTableView.cr.beginHeaderRefresh()
        
        NotificationCenter.default.addObserver(self, selector: #selector(requestFriendList), name: QSLNotification.QSLLogin, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(requestFriendList), name: QSLNotification.QSLLogout, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(requestFriendList), name: QSLNotification.QSLRefreshRequest, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(requestFriendList), name: QSLNotification.QSLRefreshFriend, object: nil)
    }
}

extension QSLFriendController {
    
    @objc func addButtonAction() {
        
        if QSLBaseManager.shared.isVip() {
            ///点击添加好友埋点
            gravityInstance?.track(QSLGravityConst.vip_friend_click_add, properties: ["id": 04001])
        } else {
            ///点击添加好友埋点
            gravityInstance?.track(QSLGravityConst.friend_click_add, properties: ["id": 04002])
        }
        
        QSLJumpManager.shared.pushToAdd(type: .friend)
    }
    
    @objc func resortBtnAction() {
        
        gravityInstance?.track(QSLGravityConst.contact_shortcut_send)
        QSLNetwork().request(.contactMaydayFavor(dict: [:])) { response in
            self.view.toast(text: "求助信息发送成功")
        } fail: { code, error in
            self.view.toast(text: error)
        }
    }
}

extension QSLFriendController {
    
    // 请求好友列表
    @objc func requestFriendList() {
        
        self.friendList.removeAll()
        self.friendList.append(QSLBaseManager.shared.userModel)
        
        QSLNetwork().request(.friendList(dict: [:])) { response in
            
            self.friTableView.cr.endHeaderRefresh()
            let list = response.mapArray(QSLUserModel.self, modelKey: "data>list")
            self.friendList.append(contentsOf: list)
            self.friTableView.reloadData()
        } fail: { code, error in
            
            self.friTableView.cr.endHeaderRefresh()
            self.friTableView.reloadData()
        }
    }
}

extension QSLFriendController: QSLFriendTableViewCellDelegate {
    
    func roadBtnClickAction(model: QSLUserModel) {
        
        if !QSLBaseManager.shared.isLogin() {
            
            if let view = self.tabBarController?.view {
                
                QSLAlertView.alert(view: view, title: "温馨提示", content: "登录即可体验查看轨迹记录", secondBtnClosure:  {
                    
                    QSLJumpManager.shared.pushToLogin(type: .road)
                })
            }
            return
        }
        
        if !QSLBaseManager.shared.isVip() {
            
            QSLJumpManager.shared.pushToVip(type: .friendRoad)
            return
        }
        
        QSLJumpManager.shared.pushToRoad(type: .friend, model: model)
    }
    
    func moreBtnAction(model: QSLUserModel, btn: UIButton) {
        
        var item3Text = ""
        if !model.blockedHim {
            item3Text = "不给TA看"
        } else {
            item3Text = "给TA看"
        }
        
        let items = [(UIImage(), "互删好友"), (UIImage(), "修改备注"), (UIImage(), item3Text), (UIImage(), "查看TA的手机号")]
        popView = QSLPopView(items: items) { index in
            print("选择了第 \(index) 项")
            
            switch index {
            case 0:
                self.deleteFri(model: model)
                break
            case 1:
                self.editRemark(model: model)
                break
            case 2:
                self.blockHime(model: model)
                break
            case 3:
                self.checkPhoneNum(model: model)
                break
            default:
                break
            }
        }
        
        popView?.contentWidth = 130.rpx
        popView?.isShowMaskView = true
        
        popView?.show(from: btn, selfVC: self)
    }
    
    // 删除好友
    func deleteFri(model: QSLUserModel) {
        
        gravityInstance?.track(QSLGravityConst.friend_delete)
        if let view = self.tabBarController?.view {
            QSLAlertView.alert(view: view, title: "温馨提示", content: "互删好友后，双方将停止位置的分享，以及清除相关定位记录，是否确认互删？", isOneBtn: false, secondBtnClosure:  {
                QSLNetwork().request(.friendDelete(dict: ["friendId": model.friendId])) { response in
                    
                    gravityInstance?.track(QSLGravityConst.friend_delete_success)
                    self.view.toast(text: "删除成功")
                    NotificationCenter.default.post(name: QSLNotification.QSLRefreshFriend, object: nil)
                } fail: { code, error in
                    
                    gravityInstance?.track(QSLGravityConst.friend_delete_fail)
                }
            })
        }
    }
    
    // 修改备注
    func editRemark(model: QSLUserModel) {
        
        gravityInstance?.track(QSLGravityConst.friend_remark)
        if let view = self.tabBarController?.view {
            QSLFriendRemarkAlertView.alert(view: view) { remark in
                
                QSLNetwork().request(.friendRemark(dict: ["friendId": model.friendId, "remark": remark])) { response in
                    
                    UIApplication.keyWindow?.toast(text: "修改成功")
                    NotificationCenter.default.post(name: QSLNotification.QSLRefreshFriend, object: nil)
                } fail: { code, error in
                    
                }
            }
        }
    }
    
    // 给他看
    func blockHime(model: QSLUserModel) {
        
        if model.blockedHim {
            gravityInstance?.track(QSLGravityConst.friend_not_block_him)
        } else {
            gravityInstance?.track(QSLGravityConst.friend_block_him)
        }
        
        QSLNetwork().request(.friendBlocked(dict: ["friendId": model.friendId, "blocked": !model.blockedHim])) { response in
            
            NotificationCenter.default.post(name: QSLNotification.QSLRefreshFriend, object: nil)
        } fail: { code, error in
            
        }
    }
    
    // 查看手机号码
    func checkPhoneNum(model: QSLUserModel) {
        
        gravityInstance?.track(QSLGravityConst.friend_phoneNum)
        if let view = self.tabBarController?.view {
            QSLAlertView.alert(view: view, title: "Ta的手机号", content: model.phone, isOneBtn: true, oneBtnText: "复制号码", oneBtnClosure:  {
                gravityInstance?.track(QSLGravityConst.friend_phoneNum_click)
                UIPasteboard.general.string = model.phone
                view.toast(text: "复制成功")
            })
        }
    }
}


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

extension QSLFriendController {
    
    func initializeView() {
        
        self.view.addSubview(friendBg)
        friendBg.snp.makeConstraints { make in
            make.left.top.right.equalTo(0)
        }
        
        self.view.addSubview(friendTitle)
        friendTitle.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 82.rpx, height: 26.rpx))
            make.left.equalTo(12.rpx)
            make.top.equalTo(QSLConst.qsl_kStatusBarFrameH)
        }
        
        self.view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.bottom.equalTo(-QSLConst.qsl_kTabbarFrameH)
            make.height.equalTo(76.rpx)
        }
        
        bottomView.addSubview(friAddBtn)
        friAddBtn.snp.makeConstraints { make in
            make.left.top.equalTo(16.rpx)
            make.right.bottom.equalTo(-16.rpx)
        }
        
        self.view.addSubview(friTableView)
        friTableView.snp.makeConstraints { make in
            make.left.equalTo(12.rpx)
            make.right.equalTo(-12.rpx)
            make.top.equalTo(friendTitle.snp.bottom).offset(13.rpx)
            make.bottom.equalTo(bottomView.snp.top)
        }
        
        self.view.addSubview(resortBtn)
        resortBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 60.rpx, height: 60.rpx))
            make.right.equalTo(-12.rpx)
            make.bottom.equalTo(bottomView.snp.top).offset(-32.rpx)
        }
    }
}
