//
//  YHMsgViewController.swift
//  galaxy
//
//  Created by davidhuangA on 2024/4/7.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHMessageListVC: YHBaseViewController {
    
    var msgArr:[YHMessageInfoModel] = []
    lazy var viewModel = {
        let model = YHMsgViewModel()
        return model
    }()
    var isNotifyEnabled = false
    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame:.zero, style:.grouped)
        tableView.estimatedSectionHeaderHeight = 1.0
        tableView.estimatedSectionFooterHeight = 1.0
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .white
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.backgroundView = emptyDataTipsView
        tableView.register(YHMessageSessionCell.self, forCellReuseIdentifier: YHMessageSessionCell.cellReuseIdentifier)
        return tableView
    }()
    
    lazy var navBar: UIView = {
        let bar = UIView()
        
        let titleLabel = UILabel()
        titleLabel.textColor = UIColor.mainTextColor
        titleLabel.textAlignment = .left
        titleLabel.font = UIFont.PFSC_M(ofSize:21)
        titleLabel.text = "消息"
        bar.addSubview(titleLabel)
        
        let cleanBtn = UIButton()
        cleanBtn.setImage(UIImage(named: "msg_clean"), for: .normal)
        cleanBtn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        cleanBtn.addTarget(self, action: #selector(didCleanButtonClicked), for: .touchUpInside)
        bar.addSubview(cleanBtn)
        
        titleLabel.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(20)
            make.right.equalTo(cleanBtn.snp.left).offset(-20)
        }
        cleanBtn.snp.makeConstraints { make in
            make.width.height.equalTo(24)
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-20)
        }
        return bar
    }()
    
    lazy var emptyDataTipsView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("暂无消息", kEmptyMessageBgName)
        let topMargin = 310-k_Height_NavigationtBarAndStatuBar
        view.topMargin = topMargin
        view.isHidden = true
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        YHLoginManager.shared.needJumpToMsgTabFlag = false
        getUnreadMsgList()
        checkNotificationPermisson()
        NotificationCenter.default.post(name: YhConstant.YhNotification.didRequestUnreadMsgTotalCountNotification, object: nil)
        
    }
    
    func setupUI() {
        addObservers()
        gk_navigationBar.isHidden = true
        view.backgroundColor = .white
        view.addSubview(navBar)
        view.addSubview(tableView)
        navBar.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(k_Height_statusBar())
            make.height.equalTo(k_Height_NavContentBar)
        }
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalToSuperview().offset(-k_Height_TabBar)
        }
    }
    
    func addObservers() {
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: YhConstant.YhNotification.didLoginSuccessNotifiction, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(logoutSuccess), name: YhConstant.YhNotification.didLogoutSuccessNotifiction, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(getUnreadMsgList), name: YhConstant.YhNotification.didRequestUnreadMsgListNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(getUnreadMsgList), name: YhConstant.YhNotification.didRequestUnreadMsgListNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(checkNotificationPermisson), name: YhConstant.YhNotification.didReqeustNotifyPermissionNotification, object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func loginSuccess() {
        printLog("登录成功，进行相应的 UI刷新操作")
    }
    
    @objc func logoutSuccess() {
        
    }
    
    @objc func didCleanButtonClicked() {
        let unreadMessages = self.msgArr.filter { $0.unreadCount > 0 }
        if unreadMessages.count <= 0 {
            YHHUD.flash(message: "暂无未读消息~")
            return
        }
        YHCommonAlertView.show("清除未读", "确定要清除所有未读提示吗？", "取消", "确认") {
            self.markAllMsgsRead()
        }
    }
    
    @objc func getUnreadMsgList() {
        if !YHLoginManager.shared.isLogin() {
            return
        }
        self.viewModel.getUnreadMsgList {
            [weak self] success, error in
            guard let self = self else { return }
            msgArr.removeAll()

            if success {
                var hasUnreadMsg = false
                // 资料填写
                if !self.viewModel.msgList.information.lastMessage.isEmpty {
                    hasUnreadMsg = true
                }
                // 证件上传
                if !self.viewModel.msgList.certificate.lastMessage.isEmpty  {
                    hasUnreadMsg = true
                }
                // 文书定稿
                if !self.viewModel.msgList.draft.lastMessage.isEmpty {
                    hasUnreadMsg = true
                }
                // 文件签字
                if !self.viewModel.msgList.signature.lastMessage.isEmpty {
                    hasUnreadMsg = true
                }
                
                // 资料递交
                if !self.viewModel.msgList.dataSubmission.lastMessage.isEmpty {
                    hasUnreadMsg = true
                }
                
                if hasUnreadMsg {
                    msgArr.append(self.viewModel.msgList.information)
                    msgArr.append(self.viewModel.msgList.certificate)
                    msgArr.append(self.viewModel.msgList.draft)
                    msgArr.append(self.viewModel.msgList.signature)
                    msgArr.append(self.viewModel.msgList.dataSubmission)
                }
            }
            emptyDataTipsView.isHidden = msgArr.count > 0
            self.tableView.reloadData()
        }
    }
    
    func markAllMsgsRead() {
        YHHUD.show(.progress(message: "清除中..."))
        self.viewModel.readMessages(type:nil, msgIds:nil, isAllRead:true) {
            [weak self] success, error in
            YHHUD.hide()
            guard let self = self else { return }
            if success {
                YHHUD.flash(message: "清除成功")
                for item in self.msgArr {
                    item.unreadCount = 0
                }
                self.tableView.reloadData()
                // 发送清空所有未读消息通知
                NotificationCenter.default.post(name: YhConstant.YhNotification.didMarkAllMessagesReadedNotifiction, object: nil)
                return
            }
            
            if let error = error {
                var msg = "清除失败"
                if error.errorMsg.count > 0 {
                    msg = error.errorMsg
                }
                YHHUD.flash(message: msg)
                return
            }
        }
    }
    
    @objc func checkNotificationPermisson() {
        checkNotificationAuthorizationStatus {
            [weak self] granted in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.isNotifyEnabled = granted
                self.tableView.reloadData()
            }
        }
    }
    
    func checkNotificationAuthorizationStatus(_ callBack:((Bool)->())?) {
        UNUserNotificationCenter.current().getNotificationSettings { settings in
            var enableStatus = false
            switch settings.authorizationStatus {
            case .authorized:
                print("通知已授权")
                enableStatus = true
            case .denied:
                print("通知被拒绝")
                enableStatus = false
            case .notDetermined:
                print("通知权限尚未确定")
                enableStatus = false
            case .provisional:
                print("通知以临时方式授权")
                enableStatus = false
            case .ephemeral:
                enableStatus = false
            @unknown default:
                break
            }
            callBack?(enableStatus)
        }
    }
}

extension YHMessageListVC {
    
    @objc func didEnableNotifyBtnClicked() {
        self.goToSettingPage()
    }
    
    func goToSettingPage() {
        let url = URL(string: UIApplication.openSettingsURLString)
        if let url = url, UIApplication .shared.canOpenURL(url) {
            UIApplication .shared.open(url, options: [:], completionHandler: {
                (success) in
            })
        }
    }
}

extension YHMessageListVC: UITableViewDelegate, UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return msgArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: YHMessageSessionCell.cellReuseIdentifier, for: indexPath) as! YHMessageSessionCell
        if 0 <= indexPath.row && indexPath.row < msgArr.count {
            let model = msgArr[indexPath.row]
            cell.updateModel(model)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 76.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
        if 0 <= indexPath.row && indexPath.row < msgArr.count {
            let msgItem = msgArr[indexPath.row]
            let vc = YHMessageDetailListVC()
            vc.type = msgItem.type
            vc.title = msgItem.getTitle()
            self.navigationController?.pushViewController(vc)
        }
    }

    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        if !isNotifyEnabled {
            return 52.0
        }
        return 1.0
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 1.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if isNotifyEnabled {
            return UIView()
        }
        let view = UIView()
        let contentview = UIView()
        contentview.backgroundColor = UIColor.brandMainColor6
        view.addSubview(contentview)
        contentview.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalToSuperview().offset(-10)
        }
        
        let label = UILabel()
        label.textColor = UIColor.mainTextColor
        label.textAlignment = .left
        label.font = UIFont.PFSC_R(ofSize:13)
        label.text = "开启通知，及时掌握最新消息".local
        contentview.addSubview(label)
        
        let enableBtn = UIButton()
        enableBtn.setTitle("开启".local, for: .normal)
        enableBtn.setTitleColor(UIColor.brandMainColor, for: .normal)
        enableBtn.titleLabel?.font = .PFSC_R(ofSize: 13)
        enableBtn.YH_clickEdgeInsets = UIEdgeInsets(top: 12, left: 20, bottom: 12, right: 20)
        enableBtn.addTarget(self, action: #selector(didEnableNotifyBtnClicked), for: .touchUpInside)
        contentview.addSubview(enableBtn)

        label.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalTo(enableBtn.snp.left).offset(-20)
            make.centerY.equalToSuperview()
        }
        
        enableBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 26, height: 42.0))
            make.right.equalToSuperview().offset(-20)
            make.top.bottom.equalToSuperview()
        }
        return view
    }
}
