//
//  CompressController.swift
//  PhoneManager
//
//  Created by edy on 2025/4/2.
//

import Foundation
import SnapKit
import Photos
import SVProgressHUD


enum CompressType {
    case compressVideo
    case compressPhoto
}

class CompressController : BaseViewController {
    
    private var compressNav:CompressNavView?
    
    // 排序
    var currentSort : ResouceSortType = .latest
    
    // 资源类型 - 相册或者视频
    var currentResourceType : CompressType = .compressPhoto
    
    // 所有的数据
    var resourceData = [AssetModel](){
        didSet{
            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
        }
    }
    
    
    lazy var collectionView:UICollectionView = {
        
        let layout = WaterfallMutiSectionFlowLayout()
        layout.delegate = self
        let sview:UICollectionView = UICollectionView.init(frame: CGRect(x: marginLR, y: self.compressNav!.height, width: self.view.width - 2 * marginLR, height: self.view.height - self.compressNav!.height),  collectionViewLayout: layout)
        sview.register(CompressSelectCell.self, forCellWithReuseIdentifier: "CompressSelectCell")
        sview.register(CompressCustomHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "CompressCustomHeaderView")
        sview.register( UICollectionReusableView.self,forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter,withReuseIdentifier: "footerID")
        
        sview.dataSource = self
        sview.delegate = self
        sview.showsVerticalScrollIndicator = false
        if #available(iOS 11.0, *) {
            sview.contentInsetAdjustmentBehavior = .never
        }
        
        sview.backgroundColor = .clear
        return sview
        
    }()
    
    
    func setUI(){
        compressNav = CompressNavView(frame: CGRect(x: 0, y: 0, width: self.view.width, height: statusBarHeight + 44))
        self.view.addSubview(compressNav!)
        
        compressNav?.snp.makeConstraints({ make in
            make.top.centerX.width.equalToSuperview()
            make.height.equalTo(statusBarHeight + 44)
        })
        self.view.insertSubview(collectionView, at: 0)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        APIReportManager.shared.startReport(type: .Compress_show)
        view.backgroundColor = .white
        self.navigationController?.navigationBar.isHidden = true
        getViewData()
        setUI()
    }
    
    
    /// 获取当前页面数据
    func getViewData(){
        
        if PhotoManager.shared.permissionStatus == .denied{
            loadPermissView(CGRect(x: 0, y: 300, width: ScreenW, height: 450))
            return
        }
        
        self.resourceData.removeAll()
        CompressViewModel().getAllPhotosToAssets(sortType: self.currentSort, assetType: self.currentResourceType) { [weak self] models in
            guard let self else {return}
            self.resourceData = models
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
}


extension CompressController:WaterfallMutiSectionDelegate,UICollectionViewDataSource,UICollectionViewDelegate {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return self.resourceData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CompressSelectCell", for: indexPath) as! CompressSelectCell
        cell.currentMediaType = self.currentResourceType
        cell.model = self.resourceData[indexPath.row]
        cell.indexPath = indexPath
        return cell
        
    }
    
    func heightForRowAtIndexPath(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, indexPath: IndexPath, itemWidth: CGFloat) -> CGFloat {
        if indexPath.row % 2  == 0{
            return itemWidth
        }
        return itemWidth + 67
        
    }
    
    func columnNumber(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> Int {
        
        return 2
    }
    
    func lineSpacing(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGFloat {
        
        return 8
    }
    
    func interitemSpacing(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGFloat {
        
        return 11
    }
    func spacingWithLastSection(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGFloat {
        
        return 8
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if self.currentResourceType == .compressPhoto{
            // 判断资源是否存在
            let options = PHImageRequestOptions()
            options.isNetworkAccessAllowed = false
            options.progressHandler = nil
            let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [self.resourceData[indexPath.row].localIdentifier], options: nil)
            guard let phAsset = fetchResult.firstObject else {
                showAlert()
                return
            }
            PHImageManager.default().requestImageDataAndOrientation(
                for: phAsset,
                options: options
            ) { data, _, _, info in
                if data == nil {
                    self.showAlert()
                }else {
                    self.startCompress(model: self.resourceData[indexPath.row])
                }
            }
        }else {
            self.getVideoURLFromLocalIdentifier(localIdentifier: self.resourceData[indexPath.row].localIdentifier) { url, error in
                if url != nil {
                    self.startCompress(model: self.resourceData[indexPath.row])
                }else {
                    self.showAlert()
                }
            }
        }
        
    }
    func referenceSizeForHeader(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGSize {
        return CGSize (width: self.collectionView.width, height: 188)
    }
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "CompressCustomHeaderView", for: indexPath) as! CompressCustomHeaderView
            header.sortViewSubmitCallBack = { [weak self] filterModel in
                guard let self else {return}
                // 重新获取数据，过滤数据
                self.currentSort = filterModel.sortType
                CompressViewModel().getAllPhotosToAssets(sortType: self.currentSort, assetType: self.currentResourceType) { [weak self] models in
                    guard let self else {return}
                    // 过滤数据
                    let tempData =  self.filterDataByDate(orgModels: models  , startDate: filterModel.startDate, endDate: filterModel.endDate)
                    self.resourceData = tempData
                }
            }
            header.changeView.callBack = {[weak self] flag in
                guard let self else {return}
                if self.currentResourceType != flag {
                    self.currentResourceType = flag
                    // 先移除下，防止点到
                    self.resourceData.removeAll()
                    // 如果是图片，直接从缓存中加载
                    if self.currentResourceType == .compressPhoto {
                        self.getViewData()
                    }else{
                        CompressViewModel().getAllPhotosToAssets(sortType: self.currentSort, assetType: flag) { [weak self] models in
                            guard let self else {return}
                            self.resourceData = models
                        }
                    }
                }
            }
            header.modeData = self.resourceData
            return header
        }else{
            let footer = collectionView.dequeueReusableSupplementaryView(
                ofKind: kind,
                withReuseIdentifier: "footerID",
                for: indexPath
            )
            
            return footer
        }
    }
    
    private func filterDataByDate(orgModels : [AssetModel], startDate:Date? ,endDate : Date?)->[AssetModel]{
        var array = orgModels
        if startDate != nil {
            array = array.filter({$0.createDate >= startDate!})
        }
        if endDate != nil {
            array = array.filter({$0.createDate <= endDate!})
        }
        return array
    }
    
    func sortByType(sortType:ResouceSortType){
        switch sortType {
        case .largest:
            self.resourceData = self.resourceData.sorted { $0.assetSize > $1.assetSize }
            break
        case .smallest:
            self.resourceData = self.resourceData.sorted { $0.assetSize < $1.assetSize }
            break
        case .latest:
            self.resourceData = self.resourceData.sorted { $0.createDate > $1.createDate }
            break
        case .oldest:
            self.resourceData = self.resourceData.sorted { $0.createDate < $1.createDate }
            break
        }
    }
    
    func startCompress(model:AssetModel){
        self.jumpToNextPage(model: model)
    }
    
    func jumpToNextPage(model:AssetModel){
        
        // 先将值传到下一个页面
        let vc : CompressQualityController = CompressQualityController()
        vc.currentMediaType = self.currentResourceType
        vc.model = model
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    func showAlert(){
        let alert = UIAlertController(title: nil, message: "ICloud video cannot be viewed", preferredStyle: .alert)
        self.present(alert, animated: true, completion: nil)
        
        // 2 秒后关闭弹窗
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            alert.dismiss(animated: true, completion: nil)
        }
    }
    
    // 注意私有方法（某些参数不一样） 这个只能在这个类中使用
    private func getVideoURLFromLocalIdentifier(localIdentifier: String, completion: @escaping (URL?, Error?) -> Void) {
        // 通过 localIdentifier 获取 PHAsset
        let fetchOptions = PHFetchOptions()
        let assets = PHAsset.fetchAssets(withLocalIdentifiers: [localIdentifier], options: fetchOptions)
        guard let asset = assets.firstObject, asset.mediaType == .video else {
            DispatchQueue.main.async {
                completion(nil, NSError(domain: "com.example.error", code: 1, userInfo: [NSLocalizedDescriptionKey: "未找到对应视频资源"]))
            }
            return
        }

        let options = PHVideoRequestOptions()
        options.isNetworkAccessAllowed = false // 允许从网络下载
        options.deliveryMode = .fastFormat // 要求高质量格式
        
        PHImageManager.default().requestAVAsset(forVideo: asset, options: options) { (avAsset, audioMix, info) in
            if let error = info?[PHImageErrorKey] as? Error {
                DispatchQueue.main.async {
                    completion(nil, error)
                }
                return
            }
            
            if let urlAsset = avAsset as? AVURLAsset {
                DispatchQueue.main.async {
                    completion(urlAsset.url, nil)
                }
            } else {
                DispatchQueue.main.async {
                    completion(nil, NSError(domain: "CustomErrorDomain", code: -1, userInfo: [NSLocalizedDescriptionKey: "Failed to get video URL"]))
                }
            }
        }
    }
    
    
}
