//
//  ImageSeletedCollectionCell.swift
//  PhoneManager
//
//  Created by edy on 2025/3/26.
//

import UIKit
import SnapKit
import Photos

class ImageSeletedCollectionCell:UICollectionViewCell {
    
    static let identifiers = "ImageSeletedCollectionCellID"
    
    private var backImageView: UIImageView?
    
    private var seletedBtn:UIButton?
    
    var callBack:callBack<Any> = {text in}
    
    var keepAllCallBack : ()->Void = {}
    
    
    lazy var allKeepButton : UIButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = UIColor(red: 0.33, green: 0.77, blue: 0.49, alpha: 1)
        button.layer.cornerRadius = 12
        button.clipsToBounds = true
        button.setTitle( "All retained", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .semibold)
        button.addTarget(self, action: #selector(allKeepButtonAction), for: .touchUpInside)
        button.isHidden = true
        return button
    }()
    
    lazy var bestResultButton : UIButton = {
        let button = UIButton(type: .custom)
        button.layer.cornerRadius = 10
        button.clipsToBounds = true
        button.backgroundColor = UIColor(red: 1, green: 0.65, blue: 0, alpha: 1)
        button.setTitle( "Best", for: .normal)
        button.setImage(UIImage(named: "Frame"), for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.isHidden = true
        button.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .semibold)
        return button
    }()
    
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
        addViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    var photsFileType: PhotsFileType?
    
    var model:ImageSeletedCollectionItem! {
        
        didSet {
            
            DispatchQueue.main.async {[weak self] in
                
                guard let self else {return}
                
                seletedBtn?.isSelected = model.isSeleted ?? false
            }
            let placeImage = model.id?.mediaType == 1 ? "othermoren" : "videosmoren"
            if let id = model.id?.localIdentifier{
                backImageView?.asset.load(withLocalIdentifier: id,placeholder: UIImage.init(named: placeImage))
            }else{
                backImageView?.image = UIImage.init(named: placeImage)
            }
            
//            if let image = model.image {
//                
//                DispatchQueue.main.async {[weak self] in
//                    
//                    guard let self else {return}
//                    
//                    backImageView?.image = image
//                    
//                }
//                
//            }else {
//                
//                DispatchQueue.global().async {[weak self] in
//                    guard let self else {return}
//                    // 如果是图片
//                    if self.photsFileType == .SimilarVideos {
//                        // 定义请求选项来获取视频的第一帧
//                        let options = PHImageRequestOptions()
//                        // 获取当前版本的照片或视频
//                        options.version = .current
//                        // 尽可能快地提供结果
//                        options.deliveryMode = .highQualityFormat
//                        // 允许从iCloud请求
//                        options.isNetworkAccessAllowed = true
//                        // 异步请求
//                        options.isSynchronous = false
//                        // 从 PHAsset 获取 AVAsset
//                        if let videoAsset = PhotoAndVideoMananger.mananger.getPHAsssetwithID(ids: [model.id!.localIdentifier]){
//                            // 使用requestImageForAsset方法请求视频的第一帧图片
//                            PHImageManager.default().requestImage(for: videoAsset, targetSize: CGSize(width: 400, height: 400), contentMode: PHImageContentMode.aspectFit, options: options) { image, _ in
//                                // 处理获取到的图片
//                                if let thumbnailImage = image {
//                                    // 使用获取到的图片，例如显示在UIImageView上
//                                    DispatchQueue.main.async { [weak self] in
//                                        guard let self else {return}
//                                        // 确保在主线程更新UI
//                                        self.model.image = thumbnailImage
//                                        self.backImageView?.image = thumbnailImage
//                                    }
//                                } else {
//                                    print("无法获取图片")
//                                }
//                            }
//                        }
//                    }else{
//                        if let asset = PhotoAndVideoMananger.mananger.getPHAsssetwithID(ids: [model.id!.localIdentifier]){
//                            let image = PhotoAndVideoMananger.mananger.getImageFromAsset(asset: asset)
//                            
//                            model.image = image
//                            
//                            DispatchQueue.main.async {[weak self] in
//                                
//                                guard let self else {return}
//                                
//                                backImageView?.image = image
//                                
//                            }
//                        }
//                    }
//                }
//            }
        }
    }
    
    lazy var extensionView: UIView = {
           let view = UIView()
           let tap = UITapGestureRecognizer()
           tap.addTarget(self, action: #selector(seletedBtnClick))
           view.addGestureRecognizer(tap)
           return view
       }()
    
    func setupUI() {
        
        backImageView = UIImageView()
        
        backImageView?.contentMode = .scaleAspectFill
        backImageView?.clipsToBounds = true
        backImageView?.layer.masksToBounds = true
        
        seletedBtn = UIButton()
        
        seletedBtn?.setImage(UIImage(named: "重复项说明-icon-未选中"), for: .normal)
        seletedBtn?.setImage(UIImage(named: "重复项说明-icon-选中"), for: .selected)
        seletedBtn?.addTarget(self, action: #selector(seletedBtnClick), for: .touchUpInside)
        
        self.backgroundColor = .clear
        
    }
    
    func addViews() {
        
        self.addSubview(backImageView!)
        self.addSubview(seletedBtn!)
        self.addSubview(self.extensionView)
        
        self.addSubview(self.allKeepButton)
        self.addSubview(self.bestResultButton)
        
        self.allKeepButton.snp.makeConstraints { make in
            make.top.left.equalToSuperview().offset(4)
            make.width.equalTo(80)
            make.height.equalTo(24)
        }
        
        self.bestResultButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(4)
            make.bottom.equalToSuperview().offset(-4)
            make.width.equalTo(60)
            make.height.equalTo(20)
        }
        
    }
    
    @objc func seletedBtnClick() {
        
        model.isSeleted = !(seletedBtn?.isSelected ?? true)
        seletedBtn?.isSelected = model.isSeleted ?? false
        callBack("")
    }
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        backImageView?.snp.makeConstraints({ make in
            
            make.top.left.width.height.equalToSuperview()
        })
        
        backImageView?.layer.cornerRadius = 12
        
        seletedBtn?.snp.makeConstraints({ make in
            
            make.width.height.equalTo(18.38.RW())
            make.bottom.equalToSuperview().offset(-6)
            make.right.equalToSuperview().offset(-6)
        })
        
        self.extensionView.snp.makeConstraints { make in
            make.center.equalTo((self.seletedBtn?.snp.center)!)
            make.height.width.equalTo(80)
        }
        
    }
    
}

extension ImageSeletedCollectionCell {
    @objc func allKeepButtonAction(){
        Print("点击了全部保留按钮")
        
        self.keepAllCallBack()
    }
}

