//
//  SecretShowImgVideoController.swift
//  PhoneManager
//
//  Created by edy on 2025/4/3.
//

import UIKit
import Photos

class PMShowImgVideoController: BaseViewController {

    enum ShowState {
        case secret
        // 相似图片
        case similarPhotos
        // 相似视频
        case similarVideos
        // 重复项
        case duplicates
    }
    
    // 资源类型 0-图片 1-视频
    var homeMediaType : Int = 0
    
    // 记录原来进来的
    var oldPageIndexPath : IndexPath?
    
    var state:ShowState = .secret
    
    var imageVideoPath:[String] = []
    
    
    lazy var navView : PhotoVideoDetailNavView = {
        let view = PhotoVideoDetailNavView()
        return view
    }()
    
    
    // 首页过来的数据
    var homeDataSource : [ImageSeletedCollectionItem]? {
        didSet{
            if let data = homeDataSource {
                for (index,item) in data.enumerated() {
                    if item.isSeleted == true {
                        selectSet.add(index)
                    }
                }
            }
        }
    }
    
    var currentIdx = 0 {
        didSet {
            changeNavInfo()
        }
    }
    var selectSet = NSMutableSet()
    
    var backOrgPageCallBack : (IndexPath?,[ImageSeletedCollectionItem]?)->Void = {index,data in}
    
    var url : URL?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white//UIColor(red: 0.95, green: 0.96, blue: 0.99, alpha: 1)
        
        self.view.addSubview(self.navView)
        self.navView.showType = .dateAndSizeNav
        self.navView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(statusBarHeight + 44)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.MaxCollection.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(0)
            make.top.equalTo(titleView.snp.bottom).offset(20)
            make.bottom.equalTo(bottItems.snp.top)
//            make.bottom.equalToSuperview().inset(100 + (cWindow?.safeAreaInsets.bottom ?? 0))
        }
        self.backView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(MaxCollection.snp.bottom)
        }
        self.bottItems.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(20)
//            make.top.equalToSuperview()
            make.height.equalTo(100)
//            make.bottom.equalToSuperview().offset(-(cWindow?.safeAreaInsets.bottom ?? 0))
            make.bottom.equalTo(self.bottomBtns.snp.top)
        }
        let height:CGFloat = (state == .secret ? 78 : 0)
        self.bottomBtns.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(height)
            make.bottom.equalToSuperview().offset(-(cWindow?.safeAreaInsets.bottom ?? 0))
        }
        self.view.layoutIfNeeded()
        if currentIdx < imageVideoPath.count {
            self.MaxCollection.scrollToItem(at: IndexPath(row: currentIdx, section: 0), at: .centeredHorizontally, animated: false)
        }
        
        changeNavInfo()
        backView.setShadow(cornerRadius: 0, sColor: UIColor.colorWithHex(hexStr: "#1475B9"), offset: CGSizeMake(3, -1),opacity: 0.15)
    }
    
    private func changeNavInfo(){
        DispatchQueue.main.async {
            if let model = self.homeDataSource?[self.currentIdx].id {
                self.navView.sizeLbel.text =  formatFileSize(model.assetSize)
                self.navView.titleLbel.text = self.changeDateToString(model: model)
            }
        }
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 离开返回上一个把选择的数据带过去
        for item in self.selectSet {
            if let index = item as? Int {
                self.homeDataSource?[index].isSeleted = true
            }
        }
        
        self.backOrgPageCallBack(self.oldPageIndexPath,self.homeDataSource)
    }
    
    private func changeDateToString(model : AssetModel) -> String{
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        formatter.timeStyle = .none
        return formatter.string(from: model.createDate)
    }
    
    private lazy var MaxCollection: UICollectionView = {
        let flowlayout = UICollectionViewFlowLayout()
        flowlayout.sectionInset = UIEdgeInsets()
        flowlayout.minimumInteritemSpacing = 0
        flowlayout.minimumLineSpacing = 0
        flowlayout.scrollDirection = .horizontal
        let col = UICollectionView(frame: CGRect(), collectionViewLayout: flowlayout)
        col.delegate = self;
        col.dataSource = self;
        col.isPagingEnabled = true
        col.showsHorizontalScrollIndicator = false
        col.backgroundColor = .clear
        col.isPagingEnabled = true
        col.register(PMShowImgCell.self, forCellWithReuseIdentifier: PMShowImgCellID)
        col.register(PMShowVideoCell.self, forCellWithReuseIdentifier: PMShowVideoCellID)
        view.addSubview(col)
        return col
    }()
    
    private lazy var bottItems: UICollectionView = {
        let flowlayout = UICollectionViewFlowLayout()
        flowlayout.sectionInset = UIEdgeInsets()
        flowlayout.minimumInteritemSpacing = 10
        flowlayout.minimumLineSpacing = 10
        flowlayout.scrollDirection = .horizontal
        let col = UICollectionView(frame: CGRect(), collectionViewLayout: flowlayout)
        col.delegate = self;
        col.dataSource = self;
        col.backgroundColor = .clear
        col.register(PMShowItemCell.self, forCellWithReuseIdentifier: PMShowItemCellID)
        col.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "UICollectionViewCell")
        col.showsHorizontalScrollIndicator = false
        backView.addSubview(col)
        return col
    }()
    
    private lazy var bottomBtns: SecretShowImgDetailView = {
        let btns = SecretShowImgDetailView()
        btns.backgroundColor = .white
        backView.addSubview(btns)
        btns.secretCallBack = {[weak self] selectIdx in
            guard let self = self else { return }
            var items = []
            if selectIdx == 0 {
                if let cell:PMShowImgCell = MaxCollection.cellForItem(at: IndexPath(row: currentIdx, section: 0) ) as? PMShowImgCell {
                    items.append(cell.icon)
                }else if let cell:PMShowVideoCell = MaxCollection.cellForItem(at: IndexPath(row: currentIdx, section: 0) ) as? PMShowVideoCell {
                    if let nbsame:String = self.imageVideoPath[self.currentIdx] as? String {
                        let url = "SecretIm".document().appendingPathComponent(nbsame)
                        items.append(url)
                    }
                }
                PhoneShare(items, parent: self)
            }else{
                let name = self.imageVideoPath[self.currentIdx]
                deleteData(name)
            }
        }
        btns.clipsToBounds = true
        return btns
    }()
    
    private func deleteData(_ name:String) -> Void {
        let DelCallBlock = { [weak self] in
            guard let self = self else { return }
            "".delPhotoVideo([name])
            Print("删除成功")
            if self.imageVideoPath.count == 1 {
                self.navigationController?.popViewController(animated: true)
            }else{
                self.imageVideoPath.remove(at: self.currentIdx)
                self.MaxCollection.deleteItems(at: [IndexPath(row: self.currentIdx, section: 0)])
                if ((self.imageVideoPath.count) == self.currentIdx){
                    self.currentIdx -= 1
                }
                bottItems.scrollToItem(at: IndexPath(row: self.currentIdx, section: 0), at: .left, animated: true)
                self.view.layoutIfNeeded()
                self.MaxCollection.reloadData()
                DispatchQueue.main.async {
                    self.bottItems.reloadData()
                }
            }
        }
//        if SettingConfiguration.share.config.removeImg {
        let alert = PMSecretHintsAlert()
        self.view.showBlur()
        alert.show { idx in
            if idx == 1 {
                DelCallBlock()
            }
            self.view.hideBlur()
            alert.dismiss(animated: true)
        }
//        PMAlert(messsage:"These photos or videos will be deleted from your private space" , action: ["Cancel","Delete"] , complate: {  alert, selectidx in
//            if selectidx == 1 {
//                DelCallBlock()
//            }
//            alert.dismiss(animated: true)
//        })
//        }else{
//            DelCallBlock()
//        }
    }
    
    private lazy var backView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.colorWithHex(hexStr: "#F2F6FC")
        view.addSubview(v)
        return v
    }()

}

extension PMShowImgVideoController : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        guard let collectView = scrollView as? UICollectionView else { return }
        if collectView == MaxCollection {
            let offsetx = MaxCollection.contentOffset.x
            let width = collectView.width
            let current:Int = Int(offsetx / width)
            self.currentIdx = current
            bottItems.scrollToItem(at: IndexPath(row: current, section: 0), at: .left, animated: true)
        }
    }
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        guard let collectView = scrollView as? UICollectionView else { return }
        if collectView == MaxCollection {
            let offsetx = MaxCollection.contentOffset.x
            let width = collectView.width
            self.currentIdx = Int(offsetx / width)
        }
    }
    
    
    private func setMaxCollection(collectionView:UICollectionView) -> Void {
        if collectionView == bottItems {
            let offsetX = collectionView.contentOffset.x
            let idx = round(offsetX / (68 + 10))
            UIView.animate(withDuration: 0.5) {
                collectionView.contentOffset = CGPointMake( idx * (68 + 10) , 0)
            }
            self.currentIdx = Int(idx)
            if Int(idx) < imageVideoPath.count {
                MaxCollection.scrollToItem(at: IndexPath(row: Int(idx), section: 0), at: .centeredHorizontally, animated: true)
            }
            
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        guard let collectView = scrollView as? UICollectionView else { return }
        self.setMaxCollection(collectionView: collectView)
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
            guard let collectView = scrollView as? UICollectionView else { return }
            self.setMaxCollection(collectionView: collectView)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if collectionView == bottItems {
            if indexPath.row > (self.homeDataSource?.count ?? 0) - 1 {
                return
            }
            if state != .secret {
                self.vibrate()
                if selectSet.contains(indexPath.row) {
                    self.homeDataSource?[indexPath.row].isSeleted = false
                    selectSet.remove(indexPath.row)
                }else{
                    self.homeDataSource?[indexPath.row].isSeleted = true
                    selectSet.add(indexPath.row)
                }
                if let cell:PMShowImgCell = self.MaxCollection.cellForItem(at: indexPath) as? PMShowImgCell  {
                    cell.isCurrent = selectSet.contains(indexPath.row)
                }
                if let cell:PMShowVideoCell = self.MaxCollection.cellForItem(at: indexPath) as? PMShowVideoCell  {
                    cell.isCurrent = selectSet.contains(indexPath.row)
                }
                collectionView.reloadData()
            }else{
                self.currentIdx = indexPath.row;
                if indexPath.row < imageVideoPath.count{
                    self.MaxCollection.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
                }
            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if self.state == .secret {
            if collectionView == MaxCollection{
                return imageVideoPath.count
            }else{
                return imageVideoPath.count + 1
            }
        }else {
            if collectionView == MaxCollection{
                return self.homeDataSource?.count ?? 0
            }else{
                return (self.homeDataSource?.count ?? 0) + 1
            }
        }
        
    }

    func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        
        if state == .secret && collectionView == MaxCollection{
            if indexPath.row < imageVideoPath.count {
                let showName = imageVideoPath[indexPath.row]
                if !showName.hasSuffix(".png") {
                    guard let zCell:PMShowVideoCell = cell as? PMShowVideoCell else { return }
                    zCell.innerVideoController?.playerViewController.player?.pause()
                }
            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if state == .secret {
            if indexPath.row < imageVideoPath.count {
                let showName = imageVideoPath[indexPath.row]
                if collectionView == MaxCollection {
                    if showName.hasSuffix(".png") {
                        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PMShowImgCellID, for: indexPath) as! PMShowImgCell
                        showName.loadPhotoOrVideo { durs, icon in
                            cell.icon = icon
                        }

                        cell.bestResultButton.isHidden = true
                        if self.homeDataSource == nil {
                            cell.selectBtn.isHidden = true
                        }
                        cell.isCurrent = selectSet.contains(indexPath.row)
                        cell.callblock = {[weak self] in
                            guard let self = self else { return }
                            self.vibrate()
                            if self.selectSet.contains(indexPath.row){
                                self.homeDataSource?[indexPath.row].isSeleted = false
                                self.selectSet.remove(indexPath.row)
                                
                            }else{
                                self.homeDataSource?[indexPath.row].isSeleted = true
                                self.selectSet.add(indexPath.row)
                            }
                            cell.isCurrent = selectSet.contains(indexPath.row)
                            self.bottItems.reloadData()
                        }
                        return cell
                    }else{
                        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PMShowVideoCellID, for: indexPath) as! PMShowVideoCell
                        cell.isCurrent = selectSet.contains(indexPath.row)
                        cell.bestResultButton.isHidden = true
                        cell.playURL = showName
                        cell.reload()
                        cell.callblock = {[weak self] in
                            guard let self = self else { return }
                            self.vibrate()
                            if self.selectSet.contains(indexPath.row){
                                self.homeDataSource?[indexPath.row].isSeleted = false
                                self.selectSet.remove(indexPath.row)
                            }else{
                                self.homeDataSource?[indexPath.row].isSeleted = true
                                self.selectSet.add(indexPath.row)
                            }
                            cell.isCurrent = selectSet.contains(indexPath.row)
                            self.bottItems.reloadData()
                        }
                        return cell
                    }
                }else{
                    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PMShowItemCellID, for: indexPath) as! PMShowItemCell
                    if self.homeDataSource == nil {
                        cell.selectBtn.isHidden = true
                    }
                    showName.loadPhotoOrVideo { duration, icon in
                        DispatchQueue.main.async {
                            cell.icon = icon
                        }
                    }
                    cell.isCurrent = selectSet.contains(indexPath.row)
                    return cell
                }
            }
        }
        
        if state == .similarPhotos || state == .duplicates  {

            if collectionView == MaxCollection {
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PMShowImgCellID, for: indexPath) as! PMShowImgCell
              //  cell.icon = self.homeDataSource![indexPath.row].image ?? UIImage()
                cell.model = homeDataSource?[indexPath.row]
                cell.isCurrent = selectSet.contains(indexPath.row)
                if let data = self.homeDataSource {
                    cell.bestResultButton.isHidden = indexPath.row != 0 || data.count <= 1 || state == .duplicates
                }
                cell.callblock = {[weak self] in
                    guard let self = self else { return }
                    self.vibrate()
                    if self.selectSet.contains(indexPath.row){
                        self.homeDataSource?[indexPath.row].isSeleted = false
                        self.selectSet.remove(indexPath.row)
                    }else{
                        self.homeDataSource?[indexPath.row].isSeleted = true
                        self.selectSet.add(indexPath.row)
                    }
                    self.MaxCollection.reloadData()
                    self.bottItems.reloadData()
                }
                return cell
            }else {
                if indexPath.row < self.homeDataSource?.count ?? 0 {
                    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PMShowItemCellID, for: indexPath) as! PMShowItemCell
                   // cell.icon = self.homeDataSource![indexPath.row].image ?? UIImage()
                    cell.model = homeDataSource?[indexPath.row]
                    cell.isCurrent = selectSet.contains(indexPath.row) //(self.currentIdx == indexPath.row)
                    return cell
                }
            }
           
        }
        if state == .similarVideos{
           // 相似视频
            if collectionView == MaxCollection {
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PMShowVideoCellID, for: indexPath) as! PMShowVideoCell
                // 这里主动获取下视频的链接
                let ident = self.homeDataSource?[indexPath.row].id?.localIdentifier
                if let ident = ident {
                    self.getVideoURLFromLocalIdentifier(localIdentifier: ident) { videoUrl, error in
                        if let videoUrl = videoUrl {
                            cell.homeResouceUrl = videoUrl
                            DispatchQueue.main.async {
                                cell.reload()
                            }
                        }
                    }
                }
                // 表示这个是视频
                cell.type = 1
                cell.isCurrent = selectSet.contains(indexPath.row)
                if let data = self.homeDataSource {
                    cell.bestResultButton.isHidden = indexPath.row != 0 || data.count <= 1
                }
                cell.callblock = {[weak self] in
                    guard let self = self else { return }
                    self.vibrate()
                    if self.selectSet.contains(indexPath.row){
                        self.homeDataSource?[indexPath.row].isSeleted = false
                        self.selectSet.remove(indexPath.row)
                    }else{
                        self.homeDataSource?[indexPath.row].isSeleted = true
                        self.selectSet.add(indexPath.row)
                    }
                    cell.isCurrent = selectSet.contains(indexPath.row)
//                    self.MaxCollection.reloadData()
                    self.bottItems.reloadData()
                }
                return cell
            }else{
                if indexPath.row < self.homeDataSource?.count ?? 0 {
                    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PMShowItemCellID, for: indexPath) as! PMShowItemCell
                    //cell.icon = self.homeDataSource![indexPath.row].image ?? UIImage()
                    cell.model = homeDataSource?[indexPath.row]
                    cell.isCurrent = selectSet.contains(indexPath.row)
                    return cell
                }
            }
        }
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UICollectionViewCell", for: indexPath)
        return cell
    }
 
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if collectionView == MaxCollection {
            return collectionView.size
        }
        if state == .secret {
            if indexPath.row < imageVideoPath.count {
                return CGSize(width: 68, height: 68)
            }
            return CGSize(width: collectionView.width - 68, height: 68)
        }else{
            if indexPath.row < self.homeDataSource?.count ?? 0 {
                return CGSize(width: 68, height: 68)
            }
            return CGSize(width: collectionView.width - 68, height: 68)
        }
    }
    
    
    /// 根据LocalIdentifier获取视频的URL
    /// - Parameters:
    ///   - localIdentifier: 资源标识
    ///   - completion: 回调
    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 = true // 允许从网络下载
        options.deliveryMode = .automatic // 要求高质量格式
        
        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"]))
                }
            }
        }
    }
}
