//
//  QSLContactController.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2024/12/11.
//

import UIKit
import YYText

enum QSLContactJumpPage: Int {
    case shortcut = 1  // 快捷键
    case mine     = 2  // 我的页面
}

class QSLContactController: QSLBaseController {
    
    var type: QSLContactJumpPage?
    
    var contactList: [QSLContactModel]?
    
    lazy var bgImageView: UIImageView = {
       
        let imageView = UIImageView()
        imageView.image = UIImage(named: "mine_bg")
        return imageView
    }()
    
    lazy var backButton: UIButton = {
       
        let button = UIButton()
        button.image(UIImage(named: "public_back_btn"))
        button.title("添加紧急联系人")
        button.mediumFont(17)
        button.textColor(QSLColor.Color_202020)
        button.setImageTitleLayout(.imgLeft, spacing: 4.rpx)
        button.addTarget(self, action: #selector(backBtnAction), for: .touchUpInside)
        return button
    }()
    
    lazy var contactIcon: UIImageView = {
        
        let imageView = UIImageView()
        imageView.image = UIImage(named: "contact_icon")
        return imageView
    }()
    
    lazy var contactLabel: UILabel = {
       
        let label = UILabel()
        label.textAlignment = .center
        label.numberOfLines = 0
        label.text("使用一键求助，需要添加正确的紧急联系人手机号码，您的联系人将会收到短信以及APP消息通知。")
        label.font(13)
        label.textColor = .hexStringColor(hexString: "#404040")
        label.changeLineSpace(space: 5)
        return label
    }()
    
    lazy var titleIcon: UIImageView = {
       
        let imageView = UIImageView()
        imageView.image = UIImage(named: "contact_title_icon")
        return imageView
    }()
    
    lazy var addBtn: UIButton = {
    
        let btn = UIButton()
        btn.title("添加联系人")
        btn.textColor(.hexStringColor(hexString: "#15CBA1"))
        btn.mediumFont(14)
        btn.image(UIImage(named: "contact_add_icon"))
        btn.addTarget(self, action: #selector(addBtnAction), for: .touchUpInside)
        return btn
    }()
    
    lazy var emptyAddLabel: YYLabel = {
       
        let label = YYLabel()
        
        let attr = NSMutableAttributedString()
        
        let firstAttr = NSMutableAttributedString(string: "未添加联系人，")
        firstAttr.font(14)
        firstAttr.color(.hexStringColor(hexString: "#A7A7A7"))
        attr.append(firstAttr)
        
        let addHL = YYTextHighlight()
        var addStr = "点我添加"
        
        let addText = NSMutableAttributedString(string: addStr)
        
        addText.font(14)
        addText.color(.hexStringColor(hexString: "#15CBA1"))
        addText.yy_setTextHighlight(addHL, range: NSRange(location: 0, length: addStr.count))
        addHL.tapAction = { [weak self] containerView, text, range, rect in
            self?.addBtnAction()
        }
        attr.append(addText)

        label.attributedText = attr
        
        return label
    }()
    
    lazy var contactTableView: UITableView = {
        
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.backgroundColor = QSLColor.backGroundColor
        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: QSLContactCell.self)
        
        return tableView
    }()
    
    lazy var bottomView: UIView = {
        
        let view = UIView(frame: CGRect(x: 0, y: 0, width: QSLConst.qsl_kScreenW, height: 76.rpx))
        view.backgroundColor = .white
        view.addFourCorner(topLeft: 12.rpx, topRight: 12.rpx, bottomLeft: 0, bottomRight: 0)
        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 sendBtn: UIButton = {
       
        let btn = UIButton()
        btn.addRadius(radius: 22.rpx)
        btn.gradientBackgroundColor(color1: .hexStringColor(hexString: "#FF5146"), color2: .hexStringColor(hexString: "#FF766D"), width: QSLConst.qsl_kScreenW - 32.rpx, height: 44.rpx, direction: .horizontal)
        btn.title("一键发送求助")
        btn.mediumFont(16)
        btn.textColor(.white)
        btn.addTarget(self, action: #selector(sendAllBtnAction), for: .touchUpInside)
        return btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initView()
        
        self.requestContactList()
        
        NotificationCenter.default.addObserver(self, selector: #selector(requestContactList), name: QSLNotification.QSLRefreshContact, object: nil)
        
        if let type = self.type {
            if type == .mine {
                gravityInstance?.track(QSLGravityConst.contact_show, properties: ["id": 1002])
            } else {
                gravityInstance?.track(QSLGravityConst.contact_show, properties: ["id": 1001])
            }
        }
    }
    
}

extension QSLContactController {
    
    @objc func addBtnAction() {
        
        if !QSLBaseManager.shared.isLogin() {
            
            if let view = self.tabBarController?.view {
                
                QSLAlertView.alert(view: view, title: "温馨提示", content: "登录即可体验查看轨迹记录", secondBtnClosure:  {
                    
                    QSLJumpManager.shared.pushToLogin(type: .contact)
                })
            }
            return
        }
        
        if !QSLBaseManager.shared.isVip() {
            
            QSLJumpManager.shared.pushToVip(type: .contact)
            return
        }
        
        QSLContactAddAlertView.alert(vc: self) { phone in
            self.requestAddContact(phone: phone)
        }
    }
    
    @objc func sendAllBtnAction() {
        
        gravityInstance?.track(QSLGravityConst.contact_resort_all)
//        QSLContactSendFailAlertView.alert(view: self.view, contactList: self.contactList!)
        QSLNetwork().request(.contactMaydayAll(dict: [:])) { response in
            
            if let data = response.fetchJSONString(path: "data>fail").data(using: .utf8), let failList = try? JSONSerialization.jsonObject(with: data, options: []) as? [String] {
                print(failList)
                if failList.count > 0 {
                    QSLContactSendFailAlertView.alert(view: self.view, contactList: failList)
                    gravityInstance?.track(QSLGravityConst.contact_resort_all_fail_alert)
                } else {
                    self.view.toast(text: "求助消息发送成功")
                    gravityInstance?.track(QSLGravityConst.contact_resort_all_success)
                }
            }
        } fail: { code, error in
            gravityInstance?.track(QSLGravityConst.contact_resort_all_fail)
            self.view.toast(text: "求助消息发送失败，请稍后重试")
        }
    }
}

extension QSLContactController: QSLContactCellDelegate {
    
    func resortClickAction(model: QSLContactModel) {
        
        gravityInstance?.track(QSLGravityConst.contact_resort_click)
        QSLAlertView.alert(view: self.view, title: "紧急求助", content: "确认向\(model.phone)发送短信求助？", isOneBtn: true, oneBtnText: "确认", oneBtnClosure:  {
            gravityInstance?.track(QSLGravityConst.contact_resort_confirm)
            QSLNetwork().request(.contactMayday(dict: ["phone": model.phone])) { reponse in
                self.view.toast(text: "求助消息发送成功")
                gravityInstance?.track(QSLGravityConst.contact_resort_success)
            } fail: { code, error in
                self.view.toast(text: "求助消息发送失败，请核实手机号码")
                gravityInstance?.track(QSLGravityConst.contact_resort_fail)
            }
        }, closeBtnClosure:  {
            gravityInstance?.track(QSLGravityConst.contact_resort_cancel)
        })
    }
    
    func favorClickAction(model: QSLContactModel) {
        
        QSLNetwork().request(.contactFavor(dict: ["phone": model.phone, "favor": true])) { reponse in
            self.view.toast(text: "修改默认联系人成功")
            NotificationCenter.default.post(name: QSLNotification.QSLRefreshContact, object: nil)
        } fail: { code, error in
            self.view.toast(text: "修改默认联系人失败，请稍后重试")
        }
    }
    
    func deleteClickAction(model: QSLContactModel) {
        
        gravityInstance?.track(QSLGravityConst.contact_delete)
        QSLAlertView.alert(view: self.view, title: "移除紧急联系人", content: "您确定要将\n\(model.phone)移除紧急联系人吗？", isOneBtn: false, firstBtnClosure: {
            gravityInstance?.track(QSLGravityConst.contact_delete_cancel)
        }, secondBtnClosure:  {
            gravityInstance?.track(QSLGravityConst.contact_delete_confirm)
            QSLNetwork().request(.contactDelete(dict: ["phone": model.phone])) { reponse in
                self.view.toast(text: "删除联系人成功")
                NotificationCenter.default.post(name: QSLNotification.QSLRefreshContact, object: nil)
            } fail: { code, error in
                self.view.toast(text: "删除联系人失败，请稍后重试")
            }
        })
    }
    
}

extension QSLContactController {
    
    @objc func requestContactList() {
        
        QSLNetwork().request(.contactList(dict: [:])) { response in
            
            let list = response.mapArray(QSLContactModel.self, modelKey: "data>list")
            self.contactList = list
            self.contactTableView.reloadData()
        } fail: { code, error in
            
            self.view.toast(text: error)
        }
    }
    
    func requestAddContact(phone: String) {
        
        QSLNetwork().request(.contactCreate(dict: ["phone": phone])) { response in
            
            self.view.toast(text: "添加成功")
            NotificationCenter.default.post(name: QSLNotification.QSLRefreshContact, object: nil)
        } fail: { code, error in
            
            self.view.toast(text: error)
        }
    }
}

extension QSLContactController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.contactList?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(cellType: QSLContactCell.self, cellForRowAt: indexPath)
        cell.delegate = self
        cell.selectionStyle = .none
        if let model = self.contactList?[indexPath.section] {
            cell.config(model: model)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 112.rpx
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.0001
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 8.rpx
    }
}

extension QSLContactController {
    
    func initView() {
        
        self.view.addSubview(bgImageView)
        bgImageView.snp.makeConstraints { make in
            make.left.top.right.equalTo(0)
        }
        
        self.view.addSubview(backButton)
        backButton.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 150.rpx, height: 25.rpx))
            make.left.equalTo(12.rpx)
            make.top.equalTo(QSLConst.qsl_kStatusBarFrameH)
        }
        
        self.view.addSubview(contactIcon)
        contactIcon.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 155.rpx, height: 126.rpx))
            make.centerX.equalToSuperview()
            make.top.equalTo(backButton.snp.bottom).offset(24.rpx)
        }
        
        self.view.addSubview(contactLabel)
        contactLabel.snp.makeConstraints { make in
            make.left.equalTo(20.rpx)
            make.right.equalTo(-20.rpx)
            make.top.equalTo(backButton.snp.bottom).offset(128.rpx)
        }
        
        self.view.addSubview(titleIcon)
        titleIcon.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 89.rpx, height: 26.rpx))
            make.left.equalTo(20.rpx)
            make.top.equalTo(contactLabel.snp.bottom).offset(32.rpx)
        }
        
        self.view.addSubview(addBtn)
        addBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 90.rpx, height: 20.rpx))
            make.right.equalTo(-12.rpx)
            make.bottom.equalTo(titleIcon.snp.bottom)
        }
        
        self.view.addSubview(emptyAddLabel)
        emptyAddLabel.snp.makeConstraints { make in
            make.top.equalTo(addBtn.snp.bottom).offset(110.rpx)
            make.centerX.equalToSuperview()
        }
        
        self.view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(0)
            make.height.equalTo(76.rpx)
        }
        
        bottomView.addSubview(sendBtn)
        sendBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 328.rpx, height: 44.rpx))
            make.center.equalToSuperview()
        }
        
        self.view.addSubview(contactTableView)
        contactTableView.snp.makeConstraints { make in
            make.top.equalTo(addBtn.snp.bottom).offset(13.rpx)
            make.left.equalTo(12.rpx)
            make.right.equalTo(-12.rpx)
            make.bottom.equalTo(bottomView.snp.top)
        }
    }
}
