//
//  YTDocumentWeb_Vc.swift
//  TWIM
//
//  Created by YouT on 2020/9/3.
//  Copyright © 2020 fsToone. All rights reserved.
//

import UIKit
import WebKit
import SVProgressHUD

public class YTDocumentWeb_Vc: UIViewController {
    
   public var fileUrlStr = ""
   public var fileName = ""
    public var filePdfData: Data?
    
   fileprivate lazy var webView: WKWebView = {
        let curWeb = WKWebView()
        curWeb.navigationDelegate = self
        return curWeb
    }()
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        webView.frame = view.bounds
        view.addSubview(webView)
        
        if fileName.isEmpty {
            let pathName = NSString(string: fileUrlStr).lastPathComponent
            navigationItem.title = pathName
        }else{
            navigationItem.title = fileName
        }
        
        if fileUrlStr.hasPrefix("http") {
            guard let urlCodeStr =  fileUrlStr.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else { return }
            if let showUrl = URL(string: urlCodeStr) {
                let urlRequest = URLRequest(url: showUrl)
                webView.load(urlRequest)
            }
        }else{
            guard let urlEncodeStr = fileUrlStr.removingPercentEncoding else { return }
            let showUrl = URL(fileURLWithPath: urlEncodeStr)
            webView.loadFileURL(showUrl, allowingReadAccessTo: showUrl)
        }
        
        if let pdfData = filePdfData {
            let bUrl = NSURL() as URL
            webView.load(pdfData, mimeType: "application/pdf", characterEncodingName: "GBK", baseURL: bUrl)
        }
        
        let closeButton = UIButton.init(type: .custom)
        closeButton.addTarget(self, action: #selector(backItemAction), for: .touchUpInside)
        closeButton.setTitle("关闭", for: .normal)
        closeButton.setTitleColor(UIColor.darkGray, for: .normal)
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: closeButton)
    }
    
    func addCustomerBackItem(_ titleStr:String = "") {
        let backBtn = UIButton(type: UIButton.ButtonType.custom)
        backBtn.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        if titleStr.isEmpty {
            backBtn.setImage(UIImage(named: "icon_back_black"), for: .normal)
        }else{
            backBtn.setTitle(titleStr, for: .normal)
            backBtn.setTitleColor(UIColor(hexString: "#333333"), for: UIControl.State.normal)
            backBtn.titleLabel?.font = UIFont(name: "PingFangSC-Medium",size: 16)
        }
        backBtn.addTarget(self, action: #selector(self.backItemAction), for: UIControl.Event.touchUpInside)
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn)
    }
    
    @objc func backItemAction() {
        if let navigationC = navigationController {
            if navigationC.viewControllers.count == 1 {
                dismiss(animated: true, completion: nil)
            }else{
                navigationController?.popViewController(animated: true)
            }
        }
    }
    
}

extension YTDocumentWeb_Vc :WKNavigationDelegate{
    
    public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        SVProgressHUD.show()
    }
    
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        SVProgressHUD.dismiss()
    }
    
    public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        SVProgressHUD.dismiss()
        SVProgressHUD.showInfo(withStatus: "无法打开此类型的文件")
    }
    
    public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        decisionHandler(.allow)
    }
    
}


