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

import UIKit
import JXSegmentedView

class YHMessageListVC: YHBaseViewController {
    
    var msgArr:[YHMessageInfoModel] = []
    lazy var viewModel = {
        let model = YHMsgViewModel()
        return model
    }()
    
    private var isGoYHManagerFlag : Bool = false
    
    private let serviceCenterMainViewModel : YHServiceCenterMainViewModel = YHServiceCenterMainViewModel()
    private let serviceCenterViewModel = YHServiceCenterViewModel()

    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 = .center
        titleLabel.font = UIFont.PFSC_M(ofSize:17)
        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.edges.equalToSuperview()
        }
        cleanBtn.snp.makeConstraints { make in
            make.width.height.equalTo(24)
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-20)
        }
        
        let backBtn = UIButton()
        backBtn.setImage(UIImage(named: "back_icon"), for: .normal)
        backBtn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        backBtn.addTarget(self, action: #selector(didBackButtonClicked), for: .touchUpInside)
        bar.addSubview(backBtn)
        backBtn.snp.makeConstraints { make in
            make.width.height.equalTo(21)
            make.centerY.equalToSuperview()
            make.left.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
    }()
    
    lazy var managerSession: YHMessageInfoModel = {
        let mgrMsg = YHMessageInfoModel()
        mgrMsg.type = YHMessageType.yinheManager.rawValue
        mgrMsg.unreadCount = YHButlerServiceManager.shared.unreadCount
        if let lastMsg = YHButlerServiceManager.shared.getLastMessage() {
            mgrMsg.lastMessage = lastMsg.content
            mgrMsg.lastMessageTime = Int64(lastMsg.timeStamp)
        }
        return mgrMsg
    }()
    
    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)
        
        // 银河管家 始终放在第一位
        if YHButlerServiceManager.shared.isUatAllowed() {
            msgArr.append(self.managerSession)
        }
        
        self.tableView.reloadData()
        
//        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(14)
            make.bottom.equalToSuperview()
        }
    }
    
    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)
        NotificationCenter.default.addObserver(self, selector: #selector(didRefreshYinHeManagerUnreadMsg), name: YhConstant.YhNotification.didQiYuUnReadMsgCountChangeNotification, object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func loginSuccess() {
        printLog("登录成功，进行相应的 UI刷新操作")
        getUnreadMsgList()
    }
    
    @objc func logoutSuccess() {
        getUnreadMsgList()
    }
    
    @objc func didBackButtonClicked() {
        self.navigationController?.popViewController(animated: true)
    }
    
    @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() {
            // 保留第一个元素银河管家，删除其他元素
            msgArr.removeAll()
            self.tableView.reloadData()
            emptyDataTipsView.isHidden = msgArr.count > 0
            return
        }
        
        self.requestOrderStatus { 
            status in
            
            // status == 1 时是文案段阶段， 当过了文案段阶段需要隐藏文案段相关消息
            let isHidden = (status != 1)
            
            self.viewModel.getUnreadMsgList {
                [weak self] success, error in
                guard let self = self else { return }
                
                // 保留第一个元素银河管家，删除其他元素
                msgArr.removeAll()
                if YHButlerServiceManager.shared.isUatAllowed() {
                    self.managerSession.unreadCount = YHButlerServiceManager.shared.unreadCount
                    if let lastMsg = YHButlerServiceManager.shared.getLastMessage() {
                        self.managerSession.lastMessage = lastMsg.content
                        self.managerSession.lastMessageTime = Int64(lastMsg.timeStamp)
                    }
                    msgArr.append(self.managerSession)
                }

                if success {
                    var hasUnreadMsg = false
                    
                    if !isHidden {
                        // 资料填写
                        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 !self.viewModel.msgList.approval.lastMessage.isEmpty {
                        hasUnreadMsg = true
                    }
                    
                    // 赴港办证
                    if !self.viewModel.msgList.goToHK.lastMessage.isEmpty {
                        hasUnreadMsg = true
                    }
                    
                    // 身份续签
                    if !self.viewModel.msgList.renewal.lastMessage.isEmpty {
                        hasUnreadMsg = true
                    }
                    
                    if hasUnreadMsg {
                        if !isHidden {
                            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)
                        }
                       
                        msgArr.append(self.viewModel.msgList.approval)
                        msgArr.append(self.viewModel.msgList.goToHK)
                        msgArr.append(self.viewModel.msgList.renewal)

                    }
                }
                emptyDataTipsView.isHidden = msgArr.count > 0
                self.tableView.reloadData()
                didRefreshYinHeManagerUnreadMsg()
            }
        }
    }
    
    func requestOrderStatus(callback:((_ status: Int)->())?) {
        // 先获取订单列表
        self.serviceCenterMainViewModel.getContactList {
            [weak self] success, error in
            guard let self = self else { return }
            if success == true {
                if let orderInfo = serviceCenterMainViewModel.arrContactList.first {
                    // 请求申请结果
                    self.serviceCenterViewModel.getServiceMainData(orderId: orderInfo.id) {
                        [weak self] success, error in
                        guard let self = self else { return }
                        callback?(self.serviceCenterViewModel.mainModel.stage)
                    }
                    
                } else {
                    callback?(0)
                }
            } else {
                callback?(0)
            }
        }
    }

    
    func markAllMsgsRead() {
        // 清除银河管家未读消息数
        YHButlerServiceManager.shared.clearUnreadCount()
        
        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 {
        
    private func gotoYinHeManager(completion: @escaping (Bool) -> Void) {
        guard let userId = YHLoginManager.shared.userModel?.id, userId.count > 0 else {
            completion(false)
            return
        }
        YHAnalytics.track("APP_FriendsTab_Conversation_GalaxyButler")
        YHButlerServiceManager.shared.gotoButlerServiceSessionVC(navigationController: navigationController, completion: { success in
            completion(success)
        })
    }
    
    @objc func didRefreshYinHeManagerUnreadMsg() {
        if !YHButlerServiceManager.shared.isUatAllowed() {
            return
        }

        self.managerSession.unreadCount = YHButlerServiceManager.shared.unreadCount
        if let lastMsg = YHButlerServiceManager.shared.getLastMessage() {
            self.managerSession.lastMessage = lastMsg.content
            self.managerSession.lastMessageTime = Int64(lastMsg.timeStamp)
            self.tableView.reloadData()
        } else {
            self.managerSession.lastMessage = ""
            self.managerSession.lastMessageTime = 0
            self.tableView.reloadData()
        }
    }
}


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]
            if msgItem.type == YHMessageType.yinheManager.rawValue { // 进银河管家
                
                if isGoYHManagerFlag {
                    return
                }
                
                isGoYHManagerFlag = true
                self.gotoYinHeManager { success in
                    self.isGoYHManagerFlag = false
                    YHHUD.hide()
                    if success {
                        self.managerSession.unreadCount = 0
                        self.tableView.reloadData()
                    }
                }
                return
            }
            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_M(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
    }
}

extension YHMessageListVC: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
