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

import UIKit
import JXSegmentedView
import UniformTypeIdentifiers

class YHCertificateResourceUploadVC: YHBaseViewController {

    var items:[String] = ["1", "2", "2", "2", "2", "2", "2", "2"]

    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame:.zero, style:.grouped)

        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.estimatedSectionHeaderHeight = 14.0
        tableView.estimatedSectionFooterHeight = 1.0
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor(hexString:"#F8F8F8")
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHCertificateInfoCell.self, forCellReuseIdentifier: YHCertificateInfoCell.cellReuseIdentifier)
        return tableView
    }()
    
    lazy var documentPickerVC: UIDocumentPickerViewController = {
        
        let docTypes =   [ "public.image",
                           "com.adobe.pdf",
                           "com.microsoft.word.doc",
                           "com.microsoft.powerpoint.ppt"]

         if #available(iOS 14.0, *) {
             var arr:[UTType] = []
             for docStr in docTypes {
                 if let type = UTType(docStr) {
                     arr.append(type)
                 }
             }
             let docPickerVC = UIDocumentPickerViewController(forOpeningContentTypes: arr)
             docPickerVC.delegate = self
             return docPickerVC
             
         }
         let docPickerVC = UIDocumentPickerViewController(documentTypes: docTypes, in: .open)
         docPickerVC.delegate = self
         return docPickerVC
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.gk_navigationBar.isHidden = true
        createUI()
    }
    
    func createUI() {
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(KScreenHeight - k_Height_NavigationtBarAndStatuBar - YHMaterialListViewController.segmentHeight)
        }
    }
}

extension YHCertificateResourceUploadVC: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return items.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let item = items[indexPath.section]
        let cell = tableView.dequeueReusableCell(withIdentifier: YHCertificateInfoCell.cellReuseIdentifier, for: indexPath)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if true {
            
            selectUploadFileFromICouldDrive()
            return
        }
        
        YHCertificateFilterView.sheetView.show()
        return
        
        print("ZZZ")
        let vc = YHUploadContentVC()
        self.navigationController?.pushViewController(vc)
    }

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

// MARK: - JXSegmentedListContainerViewListDelegate
extension YHCertificateResourceUploadVC: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}

extension YHCertificateResourceUploadVC: UIDocumentPickerDelegate {
    
    private func selectUploadFileFromICouldDrive()  {
        
       present(documentPickerVC, animated: true)
    }
    
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let url = urls.first, let fileName = url.lastPathComponent.removingPercentEncoding else {
        
            return
        }
        print("\(url)")
        // 读取文件数据
        // 获取授权
        let fileUrlAuthozied = url.startAccessingSecurityScopedResource()
        if fileUrlAuthozied {
            // 通过文件协调工具来得到新的文件地址，以此得到文件保护功能
            let fileCoordinator = NSFileCoordinator()
            var error: NSError?
            fileCoordinator.coordinate(readingItemAt: url, options:[.forUploading], error: &error) {
                newFileUrl in
                
                if let fileData = try? Data(contentsOf: newFileUrl) {
                    // 将文件数据上传到服务器
                    uploadFile(fileData)
                }
            }
            url.stopAccessingSecurityScopedResource()
            if let error = error {
                
            }
        } else {
            print("授权失败")
        }
    }
    
    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        
    }
    
    func uploadFile(_ data: Data) {

        let format = String(format: "%.2fM", Double(data.count)/(1024.0 * 1024.0))
        print("\(format)")
    }
}
