//
//  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!
    
    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?) {
        let controller = UIDocumentInteractionController(url: fileURL)
        // 设置标题显示
        if let fileName = fileName, !fileName.isEmpty {
            controller.name = fileName
        }
        controller.delegate = self
        DispatchQueue.main.async {
            controller.presentPreview(animated: true)
        }
    }
}

extension YHFilePreviewTool: UIDocumentInteractionControllerDelegate {
    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
        return targetVC
    }
}
