//
//  YHFilePreviewTool.swift
//  galaxy
//
//  Created by edy on 2024/3/21.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHFilePreviewTool: NSObject {

    weak var targetVC: UIViewController?
    private var documentController: UIDocumentInteractionController?
    
    init(targetVC: UIViewController?) {
        self.targetVC = targetVC
    }
    
    func openXLSXRemoteFile(urlString: String, fileName: String?) {
        guard let url = URL(string: urlString) else { return }
        
        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration)
        DispatchQueue.main.async {
            YHHUD.show(.progress(message: "加载文件中..."))
        }
        let task = session.downloadTask(with: url) { (tempLocalUrl, response, error) in
            DispatchQueue.main.async {
                YHHUD.hide()
            }
            if let tempLocalUrl = tempLocalUrl, error == nil {
                // 下载完成，尝试打开文件
                let fileManager = FileManager.default
                let destination = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(response?.suggestedFilename ?? UUID().uuidString)
                
                try? fileManager.moveItem(at: tempLocalUrl, to: destination)
                
                // 打开文件
                self.openXLSXFile(at: destination, fileName: fileName)
                
            } else {
                print("Error downloading the file: \(error?.localizedDescription ?? "Unknown error")")
                DispatchQueue.main.async {
                    YHHUD.flash(message: "加载文件失败")
                }
            }
        }
        
        task.resume()
    }
     
    func openXLSXFile(at fileURL: URL, fileName: String?) {
        documentController = UIDocumentInteractionController(url: fileURL)
        // 设置标题显示
        if let fileName = fileName, !fileName.isEmpty {
            documentController?.name = fileName
        }
        documentController?.delegate = self
        guard let controller = documentController else {
            printLog("Failed to create UIDocumentInteractionController")
            return
        }

        DispatchQueue.main.async { [weak self] in
            guard let self = self, self.targetVC != nil else {
                printLog("Target view controller is not available")
                return
            }
            controller.presentPreview(animated: true)
        }
    }
}

extension YHFilePreviewTool: UIDocumentInteractionControllerDelegate {
    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
        return targetVC ?? UIViewController.current ?? UIViewController()
    }
    
    func documentInteractionControllerDidEndPreview(_ controller: UIDocumentInteractionController) {
        documentController = nil
    }
    
    func documentInteractionControllerWillBeginPreview(_ controller: UIDocumentInteractionController) {
        let navi = targetVC?.navigationController
        navi?.gk_navItemRightSpace = kMargin
    }
}
