//
//  PartExplodedFileWebVc.swift
//  VattiCSS
//
//  Created by Jan on 2023/11/15.
//

import UIKit

class PartExplodedFileWebVc: UIViewController {
    var showPath = ""
    var isNeedTranslucent = false
    
    lazy var curWeb: WKWebView = {
        let configuration = WKWebViewConfiguration()
        configuration.preferences.setValue("TRUE", forKey: "allowFileAccessFromFileURLs")
       
        let cWeb = WKWebView.init(frame: CGRect.zero, configuration: configuration)
        cWeb.backgroundColor = UIColor.white
        cWeb.navigationDelegate = self
        cWeb.uiDelegate = self
        return cWeb
    }()
    
    lazy var showChangeBtn: UIButton = {
        let btn = UIButton.init(frame: CGRect.init(x: SCREEN_W-60, y: SCREEN_H-200, width: 60, height: 60))
        btn.setImage(UIImage.init(named: "icon_switch"), for: .normal)
        btn.setTitleColor(KMainColour, for: .normal)
        btn.isHidden = true
        btn.addTarget(self, action: #selector(changeLandscape), for: .touchUpInside)
        return btn
    }()
    
    var isLandscape = false
    override func loadView() {
        view = curWeb
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setNavigationBackButton()
        self.view.addSubview(showChangeBtn)
        self.view.bringSubviewToFront(showChangeBtn)
        
        self.downLoadFile()

    }
    
    func downLoadFile(){
        if showPath.isEmpty {
            SVProgressHUD.showError(withStatus: "文件读取发生错误~")
            return
        }
        
        guard let attachmenturl = URL(string: showPath) else {
            SVProgressHUD.showError(withStatus: "文件读取发生错误~")
            return
        }
        
        SVProgressHUD.show(withStatus: "下载中...")
     
        let curNet = TWOCNetwork()
        curNet.progressCall = { ( curPro ) in
            SVProgressHUD.showProgress(Float(curPro), status: "下载中...")
        }
        curNet.successCall = { [weak self] (result) in
            SVProgressHUD.dismiss()
            guard let weakSelf = self else { return }
            weakSelf.loadFilePath(filePath: result.stringValue(forKey: "filePath"))
        }
        curNet.failCall = { (tag,errorStr) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showError(withStatus: errorStr)
        }
        curNet.downLoadFile(showPath)
    }
    
    func loadFilePath(filePath: String) {
        //普通预览文件
        if filePath.hasPrefix("file:") {
            curWeb.load(URLRequest(url: URL(string: filePath)!))
            }else{
             curWeb.load(URLRequest(url: URL(fileURLWithPath: filePath)))
            }
    }
    
    
    @objc func changeLandscape(){
        if isLandscape{
            forceOrientationPortrait()//竖屏
        }else{
            forceOrientationLandscape()//横屏
        }
    }
    
    ///强制横屏
       func forceOrientationLandscape() {
           isLandscape = true
           showChangeBtn.frame = CGRect.init(x: SCREEN_W-80, y:SCREEN_H-100 , width: 60, height: 60)
           
           let appdelegate = UIApplication.shared.delegate as! AppDelegate
           appdelegate.isForceLandscape = true
           appdelegate.isForcePortrait = false
           
           //强制翻转屏幕，Home键在右边。
           UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
           //刷新
           UIViewController.attemptRotationToDeviceOrientation()
       }
    
    ///强制竖屏
     func forceOrientationPortrait() {
         isLandscape = false
         showChangeBtn.frame = CGRect.init(x: SCREEN_W-60, y:SCREEN_H-200 , width: 60, height: 60)
         
         let appdelegate = UIApplication.shared.delegate as! AppDelegate
         appdelegate.isForceLandscape = false
         appdelegate.isForcePortrait = true
        
         //强制翻转屏幕，Home键在右边。
         UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
         //刷新
         UIViewController.attemptRotationToDeviceOrientation()
     }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        SVProgressHUD.setDefaultMaskType(.none)
        
        if isNeedTranslucent {
            self.navigationController?.navigationBar.isTranslucent = false
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        SVProgressHUD.setDefaultMaskType(.clear)
        if SVProgressHUD.isVisible() {
            SVProgressHUD.dismiss()
        }
        
        forceOrientationPortrait()
        
        if isNeedTranslucent {
            self.navigationController?.navigationBar.isTranslucent = true
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
}

// MARK: - webView
extension PartExplodedFileWebVc: WKUIDelegate, WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        SVProgressHUD.show(withStatus: "正在加载中...")
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        SVProgressHUD.dismiss()
        if SVProgressHUD.isVisible() {
            SVProgressHUD.dismiss()
        }
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void)
    {
        decisionHandler(.allow)
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        SVProgressHUD.dismiss()
        SVProgressHUD.showError(withStatus: "读取文件发生错误~")
        if SVProgressHUD.isVisible() {
            SVProgressHUD.dismiss()
        }
    }
    
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        SVProgressHUD.dismiss()
        debugPrint(error.localizedDescription)
        
    }
    
    func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
        debugPrint("xxxxxxx")
    }
    
}

