//
//  YHHKEventWebViewController.swift
//  galaxy
//
//  Created by EDY on 2024/6/13.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import Photos
import WebKit
import JXSegmentedView

class YHHKEventWebViewController: YHBaseViewController {
    var webview = WKWebView()
    var model: YHHKEventModel = YHHKEventModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        setupUI()
        loadData()
    }
    
    lazy var bottomViewForSavePic: YHWebViewBottomForSavePicView = {
        let view = YHWebViewBottomForSavePicView()
        view.isHidden = true
        return view
    }()
    
    private var picUrl: String = ""
}

extension YHHKEventWebViewController {
    func loadData() {
        guard let urlString = model.list.first else { return }
        if let url = URL(string: urlString) {
            let request = URLRequest(url: url)
            webview.load(request)
        } else {
            let tmpUrl = YHURLEncodeHelper.urlEncodedString(urlString)
            if let url = URL(string: tmpUrl) {
                let request = URLRequest(url: url)
                webview.load(request)
            } else {
                printLog("url: 有问题")
            }
        }
        
        if model.tag.contains("日历") {
            picUrl = urlString
//            bottomViewForSavePic.isHidden = false
            // 创建wkwebview
            webview.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height - YHHomeWebViewBottomForSavePicView.viewH - 55 - k_Height_NavigationtBarAndStatuBar)
            
        } else {
            bottomViewForSavePic.isHidden = true
            webview.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height - 55 - k_Height_NavigationtBarAndStatuBar)
        }
    }
    
    func setupUI() {
        gk_navigationBar.isHidden = true
        
        // 创建wkwebview
        webview = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height - 0))
        webview.navigationDelegate = self
        // 添加wkwebview
        view.addSubview(webview)
        
        view.addSubview(bottomViewForSavePic)
        bottomViewForSavePic.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(YHHomeWebViewBottomForSavePicView.viewH)
        }
        bottomViewForSavePic.block = { _ in
            self.saveImageToPhotoLib()
        }
    }
}

extension YHHKEventWebViewController: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        if model.tag.contains("日历") {
            bottomViewForSavePic.isHidden = false
        }
    }
}

extension YHHKEventWebViewController {
    func saveImageToPhotoLib() {
        let urlString  = self.picUrl
        guard let url = URL(string: urlString) else {
            YHHUD.flash(message: "参数错误,保存失败")
            return
        }
        
        YHHUD.show(.progress(message: "处理中..."))
        let task = URLSession.shared.dataTask(with: url) { data, _, error in
            DispatchQueue.main.async {
                YHHUD.hide()
                guard let data = data, error == nil else { return YHHUD.flash(message: "保存成功") }
                let image = UIImage(data: data)
                if let image = image {
                    // 保存图片到图库
                    PHPhotoLibrary.shared().performChanges({
                        PHAssetChangeRequest.creationRequestForAsset(from: image)
                    }, completionHandler: { success, error in
                        if success {
                            // 图片保存成功
                            DispatchQueue.main.async {
                                YHHUD.flash(message: "保存成功")
                            }
                        } else if let error = error {
                            // 保存失败
                            DispatchQueue.main.async {
                                YHHUD.flash(message: "保存失败")
                            }
                            print("保存图片出错: \(error.localizedDescription)")
                        }
                    })
                }
            }
        }
        task.resume()
    }
}

extension YHHKEventWebViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
