//
//  TSPhotoBrowseVC.swift
//  KittensTravelNotes
//
//  Created by 100Years on 2025/7/9.
//


private let cellId = "TSPhotoBrowseCell"
private let videoCellId = "TSAIVideoBrowseCell"
import RealmSwift
class TSPhotoBrowseVC: TSBaseVC {
    var deleteComplete:((TSDBActionInfoModel)->Void)?
    var dataModelArray:Results<TSDBActionInfoModel>//惰性加载特性
    
    init(dataModelArray: Results<TSDBActionInfoModel>,
         currentIndex: Int,
         deleteComplete: ((TSDBActionInfoModel) -> Void)? = nil) {
        self.deleteComplete = deleteComplete
        self.dataModelArray = dataModelArray
        self.currentIndex = currentIndex
        super.init()
    }
    
    @MainActor required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var currentImage:UIImage?{
        let cell = collectionView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? TSPhotoBrowseCell
        var image = cell?.netWorkImageView.image
        image = image?.pngImage
        return image
    }

    var currentModel:TSDBActionInfoModel?{
        if let model = dataModelArray[safe:currentIndex]{
            return model
        }
        return nil
    }
    
    
    var currentIndex:Int = 0 {
        didSet{
            reloadUI()
        }
    }
    
    lazy var collectionView: UICollectionView = {

        let layout = TSBaseCollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: k_ScreenWidth, height: k_ScreenHeight)
        
        let collectionView = TSBaseCollectionView(frame: CGRectMake(0, 0, k_ScreenWidth, k_ScreenHeight), collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(TSPhotoBrowseCell.self, forCellWithReuseIdentifier: cellId)
//        collectionView.register(TSAIVideoBrowseCell.self, forCellWithReuseIdentifier: videoCellId)
        
        collectionView.isPagingEnabled = true
        collectionView.isHidden = true
        return collectionView
    }()

    lazy var bottomViewH = 56+k_Height_safeAreaInsetsBottom()
    lazy var bottomView: UIView = {
        let bottomView = UIView(frame: CGRectMake(0, k_ScreenHeight-bottomViewH, k_ScreenWidth, bottomViewH))
        let colorView = UIView()
        colorView.backgroundColor = .clear
        colorView.frame = bottomView.bounds
        bottomView.addSubview(colorView)

        return bottomView
    }()
    
//    //左边分享按钮
//    lazy var shareBtn: TSVerticalButton = {
//        let shareBtn = TSVerticalButton()
//        shareBtn.setUpButton(title: "Share".localized,
//                                  image: UIImage(named: "share"),
//                                  font: .font(size: 11),
//                                  titleColor: .white.withAlphaComponent(0.8)){ [weak self]  in
//            guard let self = self else { return }
//            clickShare()
//        }
//        shareBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
//        return shareBtn
//    }()
    
    //保存按钮
    lazy var bigSaveBtn: UIButton = {
        let bigSaveBtn = kCreateNormalSubmitBtn(title: "Save".localized,backgroundColor: .themeColor) { [weak self]  in
            guard let self = self else { return }
            clickSubmitBtn()
        }
        bigSaveBtn.setTitleColor(.mainText, for:.normal)
//        bigSaveBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
//        bigSaveBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
//        kSetBtnVipIcon(btn: bigSaveBtn, show: true)
        return bigSaveBtn
    }()
    
    lazy var xBtn: UIButton = {
        let xBtn = UIButton.createButton(image: UIImage(named: "close_gray")) { [weak self]  in
            guard let self = self else { return }
            clickXBtn()
        }
        return xBtn
    }()
    
    lazy var deleteBtn: UIButton = {
        let deleteBtn = UIButton.createButton(image: UIImage(named: "delete_gray")) { [weak self]  in
            guard let self = self else { return }
            TSCustomAlertController.show(in: self, config: TSCustomAlertController.AlertConfig(
                message: "Are you sure to delete?".localized,
                cancelTitle: "Delete".localized,
                cancelColor: .red,
                confirmTitle: "Retain".localized,
                confirmColor: .white,
                cancelAction: { [weak self]  in
                    guard let self = self else { return }
                    if let currentModel = currentModel {

                        deleteComplete?(currentModel)
                        if dataModelArray.count <= 0 {
                            clickXBtn()
                        }
                        
                        collectionView.deleteItems(at: [IndexPath(item: currentIndex, section: 0)])
                    }
                }
            ))
        }
        return deleteBtn
    }()
    
    

    
    override func createView() {
        super.createView()
        
        setNavBarViewHidden(true)
        contentView.addSubview(collectionView)

        DispatchQueue.main.async {
            self.collectionView.isHidden = false
            self.collectionView.reloadData()
            self.collectionView.setContentOffset(CGPoint(x: CGFloat(self.currentIndex) * self.collectionView.frame.size.width, y: 0), animated: false)

            if let flowLayout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
                flowLayout.itemSize = self.collectionView.bounds.size
            }
        }
        
        
        //关闭按钮
        contentView.addSubview(xBtn)
        xBtn.snp.makeConstraints { make in
            make.top.equalTo(k_Height_StatusBar + 4)
            make.leading.equalTo(16)
            make.width.equalTo(36)
            make.height.equalTo(36)
        }
        
        contentView.addSubview(deleteBtn)
        deleteBtn.snp.makeConstraints { make in
            make.top.equalTo(k_Height_StatusBar + 4)
            make.trailing.equalTo(-16)
            make.width.equalTo(36)
            make.height.equalTo(36)
        }
        

        let bottomBtnTop:CGFloat = 0.0
        contentView.addSubview(bottomView)
        
        bottomView.addSubview(bigSaveBtn)
        bigSaveBtn.snp.makeConstraints { make in
            make.top.equalTo(bottomBtnTop)
            make.leading.equalTo(16)
            make.trailing.equalTo(-16)
            make.height.equalTo(56)
        }
        
//        bottomView.addSubview(shareBtn)
//        shareBtn.snp.makeConstraints { make in
//            make.top.equalTo(bottomBtnTop)
//            make.leading.equalTo(16)
////            make.width.equalTo(86)
//            make.width.equalTo(shareBtn.intrinsicContentSize.width)
//            make.height.equalTo(44)
//        }
        reloadUI()
    }
    
    override func dealThings() {
        addPullDownClosePage()
    }
    @objc func clickSubmitBtn(){
  
        guard let currentModel = currentModel else { return }
        if currentModel.modelType != 1{
            if kPurchaseBusiness.kJudgeVip(externalBool: true,vc: self) {
                return
            }
        }

        guard let response = currentModel.response else { return }
        let urlString = response.resultUrl
//        if currentModel.isVideo {
//            TSDownloadManager.getDownLoadVideo(urlString: urlString) { url, _ in
//                if let url = url {
//                    PhotoManagerShared.saveVideoToAlbum(videoURL: url) { success, error in
//                        if success {
//                            kSaveSuccesswShared.show(atView: self.view)
//                        }else{
//                            debugPrint(error)
//                        }
//                    }
//                }
//            }
//        }else{
            TSImageStoreTool.downloadImageWithProgress(urlString: urlString) { image in
                if let image = image{
                    PhotoManagerShared.saveToAlbum(image) { success, error in
                        if success {
                            kSaveSuccesswShared.show(atView: self.view)
                        }else{
                            debugPrint(error)
                        }
                    }
                }else{//如果服务器取不到,直接保存当前显示的图片
                    if let currentImage = self.currentImage {
                        PhotoManagerShared.saveToAlbum(currentImage) { success, error in
                            if success {
                                kSaveSuccesswShared.show(atView: self.view)
                            }else{
                                debugPrint(error)
                            }
                        }
                    }
                }
            }
//        }
    }
    
    
    @objc func clickXBtn(){
        pop()
    }
    
    func clickShare() {
        guard let currentModel = currentModel else { return }
        
//        if currentModel.modelType != 1{
//            if kPurchaseBusiness.kJudgeVip(externalBool: true,vc: self) { return }
//        }
        
        guard let response = currentModel.response else { return }
        let urlString = response.resultUrl
//        if currentModel.isVideo {
//            TSDownloadManager.getDownLoadVideo(urlString: urlString) { url, _ in
//                if let url = url {
//                    kShareContent(target: self, anyData: url)
//                }
//            }
//        }else{
            TSImageStoreTool.downloadImageWithProgress(urlString: urlString) { image in
                if let image = image{
                    kShareContent(target: self, anyData: image)
                }else{//如果服务器取不到,直接保存当前显示的图片
                    if let currentImage = self.currentImage {
                        kShareContent(target: self, anyData: currentImage)
                    }
                }
            }
//        }
    }
}


extension TSPhotoBrowseVC {
    func reloadUI() {
        guard let currentModel = currentModel else { return }
        kSetBtnVipIcon(btn: bigSaveBtn,vipImage: .btnImageBlackVip, show: currentModel.modelType == 0)
    }
}

//MARK: UICollectionViewDataSource
extension TSPhotoBrowseVC:UICollectionViewDataSource,UICollectionViewDelegate {
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        resetIndexWithOffset(scrollView)
    }

    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        resetIndexWithOffset(scrollView)
    }

    private func resetIndexWithOffset(_ scrollView: UIScrollView) {
        let item = Int((scrollView.contentOffset.x / scrollView.bounds.width).rounded())
        currentIndex = item
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataModelArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if let model = dataModelArray[safe:indexPath.item]{
//            if model.isVideo {
//                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: videoCellId, for: indexPath) as! TSAIVideoBrowseCell
//                cell.model = model.getModel()
//                return cell
//            }else{
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! TSPhotoBrowseCell
                cell.model = model.getModel()
                return cell
//            }
        }
        
        return UICollectionViewCell()
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        if let model = dataModelArray[safe:indexPath.item]{
//            if model.isVideo {
//                guard let cell = cell as? TSAIVideoBrowseCell else { return }
//                cell.model = model.getModel()
//            }else{
                guard let cell = cell as? TSPhotoBrowseCell else { return }
                cell.model = model.getModel()
//            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView,
                      didEndDisplaying cell: UICollectionViewCell,
                      forItemAt indexPath: IndexPath) {

//        if let model = dataModelArray[safe:indexPath.item]{
//            if model.isVideo {
//                guard let cell = cell as? TSAIVideoBrowseCell else { return }
//                cell.videoPlayerVC?.playPause()
//            }
//        }
    }
    
}


class TSPhotoBrowseCell : TSBaseCollectionCell{

    lazy var exampleView: UIView = {
        let exampleView = UIView()
//        exampleView.backgroundColor = "#232323".uiColor.withAlphaComponent(0.3)
        
        let textLabel = UILabel.createLabel(
            text: "Example".localized,
            font: .font(size: 12),
            textColor: .white
        )
        
        exampleView.addSubview(textLabel)
        textLabel.snp.makeConstraints { make in
            make.top.edges.equalTo(UIEdgeInsets(top: 4, left: 6, bottom: 4, right: 6))
        }
        exampleView.isHidden = true
        exampleView.cornerRadius = 10.0
        return exampleView
    }()
    
    lazy var netWorkImageView : UIImageView = {
        let netWorkImageView = UIImageView.createImageView(imageName: "",contentMode: .scaleAspectFit)
        return netWorkImageView
    }()

    lazy var vipImageView: UIImageView = {
        let vipImageView = UIImageView.createImageView(imageName:"vip_side_icon")
        vipImageView.contentMode = .scaleToFill
        vipImageView.isHidden = true
        return vipImageView
    }()

    override func creatUI() {
        let w = k_ScreenWidth
        let h = k_ScreenHeight
        bgContentView.addSubview(netWorkImageView)
        netWorkImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(w)
            make.height.equalTo(h)
        }

        netWorkImageView.addSubview(vipImageView)
        vipImageView.snp.makeConstraints { make in
            make.width.height.equalTo(40)
            make.top.equalTo(-5)
            make.trailing.equalTo(5)
        }
    }
    
    var model:TSActionInfoModel = TSActionInfoModel(){
        didSet{
            if model.modelType == .example {
                netWorkImageView.image = UIImage(named:model.response.resultUrl)
                netWorkImageView.adaptiveScale()
            }else{
                netWorkImageView.setAsyncImage(urlString: model.response.resultUrl,placeholder: .plogPlaceholder,contentMode: .scaleAspectFit, completion: { [weak self] image in
                    guard let self = self else { return }
                    netWorkImageView.adaptiveScale()
                })
            }
            
            vipImageView.isHidden = !model.response.vip
            
        }
    }
}

//class TSAIVideoBrowseCell : TSBaseCollectionCell{
//
//    var videoPlayerVC: TSAIListVideoPlayerVC?
//    override func creatUI() {
//
//    }
//    
//    var model:TSActionInfoModel = TSActionInfoModel(){
//        didSet{
//            self.videoPlayerVC?.view.removeFromSuperview()
//            self.videoPlayerVC = TSAIListVideoPlayerVC(videoURL: self.model.videoURL)
//            self.bgContentView.addSubview(self.videoPlayerVC!.view)
//            self.videoPlayerVC!.view.snp.remakeConstraints { make in
//                make.center.equalToSuperview()
//                make.width.equalTo(k_ScreenWidth)
//                make.height.equalTo(k_ScreenHeight)
//            }
//            self.videoPlayerVC?.runloppPlay()
//        }
//    }
//}
