//
//  YHPictureBrowserViewController.swift
//  galaxy
//
//  Created by Dufet on 2025/4/8.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import Kingfisher
import UIKit
import JXPhotoBrowser
import Photos
import PhotosUI

class YHPictureBrowserViewController: JXPhotoBrowser {
    
    var getImgUrlBlock: ((Int) -> (String))?
    
    lazy var navBar: UIView = {
        let v = UIView()
        
        let backBtn = UIButton()
        backBtn.setImage(UIImage(named: "nav_back_white"), for: .normal)
        backBtn.addTarget(self, action: #selector(didBackBtnClicked), for: .touchUpInside)
        v.addSubview(backBtn)
        
        let saveBtn = UIButton()
        let img = UIImage(named: "photo_brower_save")
        let templateImage = img?.withRenderingMode(.alwaysTemplate)
        saveBtn.setImage(templateImage, for: .normal)
        saveBtn.imageView?.tintColor = .white
        saveBtn.addTarget(self, action: #selector(didSaveBtnClicked), for: .touchUpInside)
        v.addSubview(saveBtn)
        
        backBtn.snp.makeConstraints { make in
            make.width.height.equalTo(44)
            make.left.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        saveBtn.snp.makeConstraints { make in
            make.width.height.equalTo(44)
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        return v
    }()
    
    @objc func didBackBtnClicked() {
        dismiss()
    }
    
    @objc func didSaveBtnClicked() {
        let index = self.browserView.pageIndex
        if let block = self.getImgUrlBlock {
            let url = block(self.pageIndex)
            saveLocalPictureSyn(url)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(navBar)
        navBar.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(k_Height_NavigationtBarAndStatuBar)
        }
    }
    
    func saveLocalPictureSyn(_ picUrl: String) {
        guard let url = URL(string: picUrl) else {
            YHHUD.flash(message: "保存失败")
            return
        }
        KingfisherManager.shared.retrieveImage(with: url) { result in
            switch result {
            case .success(let imageLoadingResult):
                self.saveImage(imageLoadingResult.image)
            case .failure:
                YHHUD.flash(message: "保存失败")
            }
        }
        
//        let imageView = UIImageView()
//        imageView.kf.setImage(with: URL(string: picUrl)) { result in
//            switch result {
//            case .success(let value):
//                self.saveImage(value.image)
//            case .failure:
//                YHHUD.flash(message: "保存失败")
//            }
//        }
    }
    
    func saveImage(_ image: UIImage) {
        // 确保应用有权访问相册
        PHPhotoLibrary.requestAuthorization { status in
            if status == .authorized {
                // 保存图片到相册
                DispatchQueue.main.async {
                    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
                    YHHUD.flash(message: "保存成功")
                }
            } else {
                DispatchQueue.main.async {
                    YHHUD.flash(message: "保存失败，请检查系统权限")
                }
            }
        }
    }
}
