//
//  RescuePhotoController.swift
//  OrderScheduling
//
//  Created by 中道 on 2023/8/18.
//

import Foundation
import DDControlsKit_Private
import DDAutoUIKit_Private
import RxSwift
import RxCocoa
import RxRelay
import DDZFPlayerKit_Private

extension RescuePhotoController : UICollectionViewDelegate,UICollectionViewDataSource {
   public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return environmentPics.count
    }
    
   public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? RescuePendingDispatchPhotoCell
        let model = environmentPics[indexPath.item]
       cell?.imageView.image = nil
       
       if model.url.contains(".mp4?") == true {
           if let url = URL(string: model.url) {
               DispatchQueue.global().async {
                   DDImage.dd_thumbnailImage(forVideo: url) { (thumbnailImage, _, _) in
                       let image = thumbnailImage?.dd_compress(withQulitySize: 5 * 1024)
                       DispatchQueue.main.async {
                           cell!.imageView.image = image
                       }
                   }
               }

               DispatchQueue.global().async {
                   let cmTime = TOOL.getDuration(url: url)
                   DispatchQueue.main.async {
                       cell!.dateLabel.text = TOOL.getVideoDateString(duration: Int(cmTime.seconds))
                   }
               }
           }
        }else{
            cell!.imageView.sd_setImage(with: URL(string: model.url))
            cell!.dateLabel.text = nil
        }
       
       if model.isSelected == true {
           cell?.imageView.layer.borderColor = UIColor.white.cgColor
           cell?.imageView.layer.borderWidth = 2
       }else{
           cell?.imageView.layer.borderColor = UIColor.clear.cgColor
           cell?.imageView.layer.borderWidth = 0
       }
        return cell!
    }
    
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let preciousModel,let preciousIndexPath {
            preciousModel.isSelected = false
            collectionView.reloadItems(at: [preciousIndexPath])
        }

        let model = environmentPics[indexPath.item]
        model.isSelected = true
        
        preciousModel = model
        preciousIndexPath = indexPath
        collectionView.reloadItems(at: [preciousIndexPath!])
        
        if model.url.contains(".mp4?") == true {
            let vc = children.first as? VehicleMonitoringVideoDetailController
            vc?.playAssetURL(assetURL: URL(string: model.url)!)
            vc?.view.isHidden = false
            rescuePhotoView.largeImageView.isHidden = true
         }else{
            rescuePhotoView.largeImageView.sd_setImage(with: URL(string: model.url)!)
            let vc = children.first as? VehicleMonitoringVideoDetailController
            vc?.stop()
            vc?.view.isHidden = true
            rescuePhotoView.largeImageView.isHidden = false
         }
    }
}

open class RescuePhotoController : ZDViewController {
    private let rescuePhotoView = RescuePhotoView()
    private var environmentPics : [RescuePhotoModel] = []
    private var preciousModel : RescuePhotoModel?
    private var preciousIndexPath : IndexPath?
    class RescuePhotoModel : Decodable {
        var url : String
        var isSelected : Bool
        init(url: String, isSelected: Bool) {
            self.url = url
            self.isSelected = isSelected
        }
    }
    
    public init(environmentPics:[String]) {
        for index in 0..<environmentPics.count {
            let url = environmentPics[index]
            let model = RescuePhotoModel(url: url, isSelected: false)
            self.environmentPics.append(model)
        }
        super.init(nibName: nil, bundle: nil)
    }
    
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        dd_navigationItemTitle = "现场照片"
        dd_navigationBarBackgroundColor = .hex("000000")
        dd_navigationBarTitleTextAttributes = [.foregroundColor : UIColor.white(alpha: 0.7),.font:UIFont.mediumFont(auto(15))]
        dd_navigationBarBarButtonItemAttributes = [.foregroundColor : UIColor.white]
        view.backgroundColor = .hex("000000")
        
        view.addSubview(rescuePhotoView)
        rescuePhotoView.snp.makeConstraints { make in
            make.top.equalTo(CGRectGetHeight(UIApplication.shared.dd_statusBarFrame)+CGRectGetHeight(navigationController?.navigationBar.frame ?? .zero))
            make.left.bottom.right.equalToSuperview()
        }
        
        let videoDetailVc = VehicleMonitoringVideoDetailController(assetURL: nil)
        videoDetailVc.dd_navigationBarBackgroundColor = .hex("000000")
        addChild(videoDetailVc)
        rescuePhotoView.addSubview(videoDetailVc.view)
        videoDetailVc.view.snp.makeConstraints { make in
            make.top.equalTo(rescuePhotoView.largeImageView)
            make.left.right.equalTo(rescuePhotoView.largeImageView)
            make.height.equalTo(rescuePhotoView.largeImageView)
        }
        
        rescuePhotoView.collectionView.backgroundColor = .hex("000000")
        rescuePhotoView.collectionView.delegate = self
        rescuePhotoView.collectionView.dataSource = self
        rescuePhotoView.collectionView.register(RescuePendingDispatchPhotoCell.self, forCellWithReuseIdentifier: "cell")

        rescuePhotoView.collectionView.reloadData()
        collectionView(rescuePhotoView.collectionView, didSelectItemAt: IndexPath(item: 0, section: 0))
    }

}

class RescuePhotoView : DDView {
    public let largeImageView : DDImageView
    public let collectionView : DDCollectionView
    override init(frame: CGRect) {
        largeImageView = DDImageView()
        let flowLayout = UICollectionViewFlowLayout.init()
        flowLayout.itemSize = CGSize(width: auto(85), height: auto(60))
        flowLayout.scrollDirection = .vertical
        flowLayout.minimumInteritemSpacing = auto(5)
        flowLayout.minimumLineSpacing = auto(5)
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: auto(10), bottom: 0, right: auto(10))
        collectionView = DDCollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
        super.init(frame: frame)
        
        largeImageView.contentMode = .scaleAspectFit
        addSubview(largeImageView)
        addSubview(collectionView)
        
        largeImageView.snp.makeConstraints { make in
            make.top.equalTo(auto(30))
            make.centerX.equalToSuperview()
            make.width.equalTo(auto(375))
            make.height.equalTo(auto(210))
        }
        
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(largeImageView.snp.bottom).offset(auto(30))
            make.left.right.equalTo(0)
            make.bottom.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
