//
//  YHHKEventViewController.swift
//  galaxy
//
//  Created by EDY on 2024/4/11.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import WebKit
import Photos

class YHHKEventViewController: YHBaseViewController {
    let homeViewModel: YHHomePageViewModel = YHHomePageViewModel()
    var sectionView: YHServiceSectionView!
    var webview = WKWebView()
    var model: YHHKEventModel = YHHKEventModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        setupUI()
        loadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
//        loadData()
    }
    
    lazy var bottomViewForSavePic: YHHomeWebViewBottomForSavePicView = {
        let view = YHHomeWebViewBottomForSavePicView()
        view.isHidden = true
        return view
    }()
    
    
    private var picUrl : String = ""
}

extension YHHKEventViewController {
    func loadData() {
        homeViewModel.getHKEvent {[weak self] success, error in
            guard let self = self else { return }
            self.sectionView.type = 1
            self.sectionView.dataSource = self.homeViewModel.hkList ?? []
            guard let model = self.homeViewModel.hkList?.first, let urlString = model.list.first else { return }
            self.model = model
            let url = NSURL(string: urlString)
            // 创建请求
            let request = NSURLRequest(url: url! as URL)
            // 加载请求
            self.webview.load(request as URLRequest)
        }
    }
    
    func setupUI() {
        gk_navBarAlpha = 1
        gk_navTitle = "香港办事"
        let rightButtonItem = UIBarButtonItem(image: UIImage(named: "share_item")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(share))
        gk_navRightBarButtonItem = rightButtonItem
        gk_navItemRightSpace = 16
        printLog(gk_navigationBar.isHidden)
        
        sectionView = {
            let view = YHServiceSectionView()
            view.hkBlock = {[weak self] model in
                guard let self = self else { return }
                guard let urlString = model.list.first else { return }
                self.model = model
                let url = NSURL(string: urlString)
                // 创建请求
                let request = NSURLRequest(url: url! as URL)
                // 加载请求
                self.webview.load(request as URLRequest)
                
                
                let navHeight = self.navigationController?.navigationBar.frame.height
                //获取状态栏高度
                let statusHeight = k_Height_statusBar()
                if model.tag.contains("日历") {
                    picUrl = urlString
                    bottomViewForSavePic.isHidden = false
                    // 创建wkwebview
                    webview.frame = CGRect(x: 0, y: statusHeight + navHeight! + 48, width: self.view.frame.width, height: self.view.frame.height - statusHeight - navHeight! - 48 - YHHomeWebViewBottomForSavePicView.viewH)
                    
                } else {
                    bottomViewForSavePic.isHidden = true
                    webview.frame = CGRect(x: 0, y: statusHeight + navHeight! + 48, width: self.view.frame.width, height: self.view.frame.height - statusHeight - navHeight! - 48)
                }
            }
            return view
        }()
        
        view.addSubview(sectionView)
        sectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
            make.height.equalTo(48)
        }
        
        let navHeight = self.navigationController?.navigationBar.frame.height
        //获取状态栏高度
        let statusHeight = k_Height_statusBar()
        
        // 创建wkwebview
        webview = WKWebView(frame: CGRect(x: 0, y: statusHeight + navHeight! + 48, width: self.view.frame.width, height: self.view.frame.height - statusHeight - navHeight! - 48))
        // 添加wkwebview
        view.addSubview(webview)
        
        view.addSubview(bottomViewForSavePic)
        bottomViewForSavePic.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(YHHomeWebViewBottomForSavePicView.viewH)
        }
        bottomViewForSavePic.block = { tag in
            self.saveImageToPhotoLib()
        }
    }
    
    @objc func share() {
        if YHLoginManager.shared.isLogin() {
            if model.tag.contains("日历") {
                guard let urlString = model.list.first, let url = URL(string: urlString) else {
                    return
                }
                let task = URLSession.shared.dataTask(with: url) { data, response, error in
                    DispatchQueue.main.async {
                        guard let data = data, error == nil else { return }
                        let image = UIImage(data: data)
                        if let image = image {
                            YHShareManager.shared.sendImageContent(image)
                        }
                    }
                }
                task.resume()
            } else {
                guard let urlString = model.list.first else {
                    return
                }
                YHShareManager.shared.sendLinkContent("一图看清香港办事", "", UIImage(named: "AppIcon") ?? UIImage(), link: urlString)
            }
        } else {
            YHOneKeyLoginManager.shared.oneKeyLogin()
        }
    }
}


extension YHHKEventViewController {
    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, response, 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()
    }
}
