//
//  YHInformationFillVC.swift
//  galaxy
//
//  Created by edy on 2024/4/11.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import SafariServices

class YHMessageDetailListVC: YHBaseViewController {
    
    var type:Int = -1
    var msgArr:[YHDetailMessageModel] = []
    // 滑动过程中出现在屏幕上的未读消息集合
    var visibleUnreadMsgIdSet = Set<String>()
    var visibleUnreadMsgArr = [YHDetailMessageModel]()
    var currentPage = 1
    var isLastPage = false
    
    lazy var viewModel = {
        let model = YHMsgViewModel()
        return model
    }()
    
    let principleViewModel: YHPrincleViewModel = YHPrincleViewModel()

    
    lazy var navBar: YHCustomNavigationBar = {
        let bar = YHCustomNavigationBar.navBar()
        bar.backgroundColor = .white
        if let title = self.title, !title.isEmpty {
            bar.title = title
        }
        bar.showRightButtonType(.clean)
        bar.backBlock = {
            [weak self] in
            guard let self = self else { return }
            self.navigationController?.popViewController(animated: true)
        }
        bar.rightBtnClick = {
            [weak self] in
            guard let self = self else { return }
            let unreadMessages = self.msgArr.filter { !$0.isRead }
            if unreadMessages.count <= 0 {
                YHHUD.flash(message: "暂无未读消息~")
                return
            }
            YHCommonAlertView.show("清除未读", "确定要清除所有未读提示吗？", "取消", "确认") {
                self.markAllMsgsRead()
            }
        }
        return bar
    }()
    
    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 = UIColor(hex:0xF8F8F8)
        tableView.backgroundView = emptyDataTipsView
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHDetailMessageCell.self, forCellReuseIdentifier: YHDetailMessageCell.cellReuseIdentifier)
        tableView.es.addInfiniteScrolling {
            self.getMsgList(more: true)
        }
        return tableView
    }()
    
    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()
        getMsgList()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    func setupUI() {
        
        gk_navigationBar.isHidden = true
        view.backgroundColor = .white
        view.addSubview(tableView)
        view.addSubview(navBar)
        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()
        }
    }
    
    func getMsgList(more:Bool = false) {
        
        if isLastPage {
            tableView.es.stopLoadingMore()
            return
        }
        
        if more {
            currentPage += 1
        } else {
            currentPage = 1
        }
        
        self.viewModel.getMsgDetailList(type: self.type, page:currentPage) {
            [weak self] success, isLastPage in
            guard let self = self else { return }
            msgArr.removeAll()
            msgArr.append(contentsOf: self.viewModel.msgDetailList)
            emptyDataTipsView.isHidden = msgArr.count > 0
            self.isLastPage = isLastPage
            tableView.es.stopLoadingMore()
            if isLastPage {
                tableView.es.noticeNoMoreData()
            }
            self.tableView.reloadData {
                [weak self] in
                guard let self = self else { return }
                self.addUpAppearUnreadMessages()
                self.markAppearMessagsReaded()
            }
        }
    }
    
    func markAllMsgsRead() {
        YHHUD.show(.progress(message: "清除中..."))
        self.viewModel.readMessages(type:self.type, 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.isRead = true
                }
                self.tableView.reloadData()
                return
            }
            var msg = "清除失败"
            if let error = error {
                if error.errorMsg.count > 0 {
                    msg = error.errorMsg
                }
            }
            YHHUD.flash(message: msg)
        }
    }
    
    func markAppearMessagsReaded() {
        var msgIds:[Int] = []
        var resultArr:[YHDetailMessageModel] = []
        for msgItem in visibleUnreadMsgArr {
            if let msgId = Int(msgItem.id), msgItem.isRead == false  {
                msgIds.append(msgId)
                resultArr.append(msgItem)
            }
        }
        if msgIds.count <= 0 { return }
        self.viewModel.readMessages(type: self.type, msgIds: msgIds, isAllRead:false) {
            [weak self] success, error in
            guard let self = self else { return }
            if success {
                for msgItem in resultArr {
                    msgItem.isRead = true
                }
                self.tableView.reloadData()
                return
            }
        }
    }
}

extension YHMessageDetailListVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return msgArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: YHDetailMessageCell.cellReuseIdentifier, for: indexPath) as! YHDetailMessageCell
        if 0 <= indexPath.row && indexPath.row < msgArr.count {
            let item = msgArr[indexPath.row]
            cell.updateModel(item, type:self.type)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if 0 <= indexPath.row && indexPath.row < msgArr.count {
            let item = msgArr[indexPath.row]
            printLog("order_id: \(item.orderId)")
            
            if !item.isRead, let msgId = Int(item.id), msgId > 0 { // 消息为未读消息
                self.viewModel.readMessages(type: self.type, msgIds: [msgId], isAllRead: false) { 
                    [weak self] success, error in
                    guard let self = self else { return }
                    if success {
                        item.isRead = true
                        self.tableView.reloadData()
                    }
                }
            }
            
            if self.type == YHMessageType.infoFill.rawValue { // 资料填写
                if let orderId = Int(item.orderId), orderId > 0 {
                    let vc = YHInformationPerfectListVC()
                    vc.orderId = orderId
                    navigationController?.pushViewController(vc)
                }
                
            } else if self.type == YHMessageType.cerUpload.rawValue { // 证件上传
                if let orderId = Int(item.orderId), orderId > 0 {
                    let vc = YHMineCertificateEntryViewController()
                    vc.orderId = orderId
                    navigationController?.pushViewController(vc)
                }
                
            } else if self.type == YHMessageType.draft.rawValue { // 文书定稿
                if let orderId = Int(item.orderId), orderId > 0 {
                    let vc = YHMyDocumentsListViewController()
                    vc.orderId = orderId
                    navigationController?.pushViewController(vc)
                }
                
            } else if self.type == YHMessageType.fileSign.rawValue { // 文件签字
                if let orderId = Int(item.orderId), orderId > 0 {
                    let vc = YHMySignatureListViewController()
                    vc.orderId = orderId
                    navigationController?.pushViewController(vc)
                }
                
            } else if self.type == YHMessageType.infoSubmit.rawValue { // 资料递交
                if !item.url.isEmpty {
                    if let url = URL(string: item.url) {
                        let safariViewController = SFSafariViewController(url: url)
                        safariViewController.dismissButtonStyle = .close
                        safariViewController.modalPresentationStyle = .fullScreen
                        present(safariViewController, animated: true, completion: nil)
                    } else {
                        YHHUD.flash(message: "url无效")
                    }
                    return
                }
                self.navigationController?.popToRootViewController(animated: false)
                goTabBarBy(tabType: .service)
                
            } else if self.type == YHMessageType.identityApproved.rawValue { // 身份获批
                self.navigationController?.popToRootViewController(animated: false)
                goTabBarBy(tabType: .service)
            }
        }
    }

    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        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? {

        return UIView()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if scrollView == tableView && !decelerate {
            // 在这里处理滑动停止事件
            print("TableView 滑动停止")
            markAppearMessagsReaded()
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        addUpAppearUnreadMessages()
    }
    
    // 累计出现在屏幕上的未读消息集合
    func addUpAppearUnreadMessages() {
        let visibleCells = tableView.visibleCells as! [YHDetailMessageCell]
        if visibleCells.count <= 0 { return }
        for cell in visibleCells {
            if let msgItem = cell.model {
                if !msgItem.isRead {
                    if !visibleUnreadMsgIdSet.contains(msgItem.id) {
                        visibleUnreadMsgIdSet.insert(msgItem.id)
                        visibleUnreadMsgArr.append(msgItem)
                    }
                }
            }
        }
        printLog("visiblemsgIdSet:/n \(visibleUnreadMsgIdSet)")
    }
}

