//
//  PQPQChoseMaterialCell.swift
//  PQSpeed
//
//  Created by SanW on 2020/8/28.
//  Copyright © 2020 BytesFlow. All rights reserved.
//

import Kingfisher
import UIKit
import Photos

public class PQChoseMaterialCell: UICollectionViewCell {
    // 是否显示素材标识
    public var isShowMediaTag: Bool = true
    // 是否是已经添加过的
    public var isAdded: Bool = false
    public var representedAssetIdentifier: String!
    public var materialClicHandle: ((_ sender: UIButton, _ materialData: PQEditVisionTrackMaterialsModel?) -> Void)?

    lazy public var materialImageView: AnimatedImageView = {
        let materialImageView = AnimatedImageView()
        materialImageView.contentMode = .scaleAspectFill
        materialImageView.isUserInteractionEnabled = true
        materialImageView.clipsToBounds = true
        return materialImageView
    }()

    lazy public var borderView: UIView = {
        let borderView = UIView()
        borderView.layer.borderColor = UIColor.hexColor(hexadecimal: "#333333").cgColor
        borderView.layer.borderWidth = 1.5
        return borderView
    }()

    lazy public var statusLab: UILabel = {
        let statusLab = UILabel()
        statusLab.textColor = UIColor.white
        statusLab.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7)
        statusLab.font = UIFont.systemFont(ofSize: 11)
        statusLab.text = "GIF"
        statusLab.addCorner(corner: 3)
        return statusLab
    }()

    lazy public var videoStatuImageView: UIImageView = {
        let videoStatuImageView = UIImageView(image: UIImage.init().BF_Image(named:  "allPreview"))
        return videoStatuImageView
    }()

    lazy public var videoLoadingView: AnimatedImageView = {
        let videoLoadingView = AnimatedImageView()
        videoLoadingView.kf.setImage(with: URL(fileURLWithPath:  Bundle.init().BF_mainbundle().path(forResource: "material_loading", ofType: ".gif")!))
        videoLoadingView.stopAnimating()
        return videoLoadingView
    }()

    lazy public var choseContentView: UIView = {
        let choseContentView = UIView()
        let ges = UITapGestureRecognizer(target: self, action: #selector(choseTap(ges:)))
        choseContentView.addGestureRecognizer(ges)
//        choseContentView.backgroundColor = UIColor.hexColor(hexadecimal: "#FF0000")
        return choseContentView
    }()

    lazy public var choseBtn: UIButton = {
        let choseBtn = UIButton(type: .custom)
        choseBtn.setBackgroundImage(UIImage.init().BF_Image(named:  "videomk_chose_nomal"), for: .normal)
        choseBtn.setBackgroundImage(UIImage.init().BF_Image(named:  "videomk_chose_selected").withRenderingMode(.alwaysTemplate), for: .selected)
        choseBtn.tintColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
        choseBtn.setTitleColor(UIColor.white, for: .normal)
        choseBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        choseBtn.tag = 1
        choseBtn.addCorner(corner: 15)
        choseBtn.isUserInteractionEnabled = false
        return choseBtn
    }()

    /// 删除按钮
    lazy public var deleteBtn: UIButton = {
        let deleteBtn = UIButton(type: .custom)
        deleteBtn.tintColor = PQBFConfig.shared.styleBackGroundColor
        deleteBtn.setImage(PQBFConfig.shared.materialDeleteImage, for: .normal)
        deleteBtn.tag = 2
        deleteBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        deleteBtn.isHidden = !isAdded
        return deleteBtn
    }()

    @objc class public func choseMaterialCell(collectionView: UICollectionView, indexPath: IndexPath) -> PQChoseMaterialCell {
        let cell: PQChoseMaterialCell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PQChoseMaterialCell.self), for: indexPath) as! PQChoseMaterialCell
        return cell
    }

    override public init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(borderView)
        contentView.addSubview(materialImageView)
        contentView.addSubview(deleteBtn)
        materialImageView.addSubview(videoStatuImageView)
        materialImageView.addSubview(choseContentView)
        choseContentView.addSubview(choseBtn)
        materialImageView.addSubview(statusLab)
        materialImageView.addSubview(videoLoadingView)
    }

    required public  init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    public  var materialData: PQEditVisionTrackMaterialsModel? {
        didSet {
            addData()
            addLayout()
        }
    }

    public func addData() {
        if materialData?.coverImageUI != nil {
            materialImageView.image = materialData?.coverImageUI
        } else if materialData?.asset != nil{
//            DispatchQueue.global().async {[weak self] in
//                (PHCachingImageManager.default() as? PHCachingImageManager)?.requestImage(for: (self?.materialData?.asset)!, targetSize: photoItemSize, contentMode: .aspectFill, options: nil) {[weak self] image, info in
//                    if info?.keys.contains("PHImageResultIsDegradedKey") ?? false, "\(info?["PHImageResultIsDegradedKey"] ?? "0")" == "0", self?.representedAssetIdentifier == self?.materialData?.asset?.localIdentifier {
//                        if image != nil {
//                            self?.materialData?.coverImageUI = image
//                            DispatchQueue.main.async {[weak self] in
//                                self?.materialImageView.image = image
//                            }
//                        } else if image == nil, info?.keys.contains("PHImageResultIsInCloudKey") ?? false {
//                            let option = PHImageRequestOptions()
//                            option.isNetworkAccessAllowed = true
//                            option.resizeMode = .fast
//                            (PHCachingImageManager.default() as? PHCachingImageManager)?.requestImageData(for: (self?.materialData?.asset)!, options: option) { data, _, _, _ in
//                                if data != nil, self?.representedAssetIdentifier == self?.materialData?.asset?.localIdentifier {
//                                    let image = UIImage(data: data!)
//                                    self?.materialData?.coverImageUI = image
//                                    DispatchQueue.main.async {[weak self] in
//                                        self?.materialImageView.image = image
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
        }else if(materialData?.netResCoverImageURL != nil){
            materialImageView.setNetImage(url: materialData?.netResCoverImageURL ?? "")
        }

        if materialData?.type == StickerType.VIDEO.rawValue {
            var duration = (materialData?.duration ?? 0.0)
            if duration < 1 {
                duration = 1
            }
            statusLab.text = "  \(Float64(duration).formatDurationToHMS())  "
            statusLab.isHidden = false
        } else if materialData?.type == StickerType.GIF.rawValue {
            statusLab.text = "  GIF  "
            statusLab.isHidden = false
        } else {
            statusLab.text = nil
            statusLab.isHidden = true
        }
        videoStatuImageView.isHidden = !isShowMediaTag || materialData?.type != StickerType.VIDEO.rawValue
        choseContentView.isHidden = isAdded
        deleteBtn.isHidden = !isAdded
        if !isAdded {
            choseBtn.isSelected = materialData?.isSelected ?? false
            if materialData?.isSelected ?? false {
                choseBtn.setTitle("\(materialData?.selectedIndex ?? 1)", for: .normal)
            } else {
                choseBtn.setTitle(nil, for: .normal)
            }
        }else{
            materialImageView.contentMode = .scaleAspectFit
            materialImageView.backgroundColor = UIColor.hexColor(hexadecimal: "#0F0F14")
        }
        videoLoadingView.isHidden = !(!isAdded && materialData?.type == StickerType.VIDEO.rawValue && materialData?.isSelected == true && materialData?.downloadState == .downloading)
        if videoLoadingView.isHidden {
            videoLoadingView.stopAnimating()
        } else {
            videoLoadingView.startAnimating()
        }
        BFLog(message: "导出视频 = \(videoLoadingView.isHidden),asset = \(String(describing: materialData?.asset)),downloadState = \(String(describing: materialData?.downloadState))")
//        if videoLoadingView.isHidden {
//            videoLoadingView.stopAnimating()
//            videoLoadingView.layer.removeAllAnimations()
//        } else {
//            videoLoadingView.stopAnimating()
//            videoLoadingView.layer.removeAllAnimations()
//            videoLoadingView.showLoadingAnimation()
//        }
    }

    public  func addLayout() {
        if isAdded {
            borderView.snp.makeConstraints { make in
                make.size.equalTo(CGSize.zero)
            }
            deleteBtn.snp.makeConstraints { make in
                make.right.equalToSuperview()
                make.top.equalToSuperview()
                make.width.height.equalTo(cDefaultMargin * 2)
            }
            materialImageView.snp.makeConstraints { make in
                make.left.equalToSuperview()
                make.right.equalTo(deleteBtn.snp_centerX)
                make.top.equalTo(deleteBtn.snp_centerY)
                make.width.equalTo(materialImageView.snp_height)
            }
        } else {
            borderView.snp.makeConstraints { make in
                make.size.equalToSuperview()
            }
            materialImageView.snp.makeConstraints { make in
                make.size.equalToSuperview()
            }
            choseContentView.snp.makeConstraints { make in
                make.top.right.equalToSuperview()
                make.width.height.equalTo(cDefaultMargin * 5)
            }
            choseBtn.snp.makeConstraints { make in
                make.top.right.equalToSuperview()
                make.width.height.equalTo(cDefaultMargin * 3)
            }
        }
        statusLab.snp.makeConstraints { make in
            make.bottom.right.equalToSuperview().offset(-4)
            make.height.equalTo(18)
        }
        videoStatuImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        videoLoadingView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.height.equalTo(cDefaultMargin * 4)
        }
    }

    @objc public func btnClick(sender: UIButton) {
        if materialClicHandle != nil {
            materialClicHandle!(sender, materialData)
        }
    }

    @objc public func choseTap(ges _: UITapGestureRecognizer) {
        btnClick(sender: choseBtn)
    }

    deinit {
        videoLoadingView.stopAnimating()
    }
}
