//
//  YHPictureReviewManager.swift
//  galaxy
//
//  Created by davidhuangA on 2024/8/6.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

import JXPhotoBrowser
import SDWebImage

class YHPictureReviewManager: NSObject {
    static let shared = YHPictureReviewManager()
    
    override init() {
        super.init()
    }
    
    private var curIndex: Int = 0
    private var arrPics: [String] = []
    
}

extension YHPictureReviewManager {
    func showNetWorkPicturs(curIndex: Int, arrPicturs: [String]) {
        guard  curIndex > -1, arrPicturs.count > 0 else { return }
        
        self.curIndex = curIndex
        self.arrPics = arrPicturs
        
        let browser = YHPictureBrowserViewController()
        browser.numberOfItems = {
            self.arrPics.count
        }
        
        browser.reloadCellAtIndex = { context in
            if context.index >= self.arrPics.count {
                return
            }
            let string = self.arrPics[context.index]
            guard string.count > 0, let url = URL(string: string) else { return }
            let browserCell = context.cell as? JXPhotoBrowserImageCell
            browserCell?.index = context.index
            let placeholder = UIImage(named: "global_default_image")
            browserCell?.imageView.sd_setImage(with: url, placeholderImage: placeholder, options: [], completed: { (_, _, _, _) in
                browserCell?.setNeedsLayout()
            })
            
            // 添加长按事件
            browserCell?.longPressedAction = { cell, _ in
                self.longPress(cell: cell)
            }
        }
        
        browser.getImgUrlBlock = { [weak self] index in
            guard let self = self else { return "" }
            if 0 <= index, index < self.arrPics.count {
                return self.arrPics[index]
            }
            return ""
        }
        
        // 数字样式的页码指示器
        browser.pageIndicator = JXPhotoBrowserNumberPageIndicator()
        browser.pageIndex = self.curIndex
        browser.show()
        
    }
}

extension YHPictureReviewManager {
    private func longPress(cell: JXPhotoBrowserImageCell) {
        let index = cell.index
        if index < self.arrPics.count, index > -1 {
            let view = YHLongtapPictureSheetView.sheetView()
            view.myUrl = self.arrPics[index]
            view.show()
        }
    }
}
