//
//  TSPTPBrowseVC.swift
//  AIEmoji
//
//  Created by 100Years on 2025/2/26.
//

private let cellId = "TSPTPBrowseCell"
class TSPTPBrowseVC: TSBottomAlertVC {

    
    var dataModelArray = [TSGenmojiModel]()
    var currentImage:UIImage?{
        let cell = collectionView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? TSPTPBrowseCell
        var image = cell?.netWorkImageView.image
        image = image?.pngImage
        return image
    }

    var currentModel:TSGenmojiModel?{
        if let model = dataModelArray.safeObj(At: currentIndex){
            return model
        }
        return nil
    }
    
    
    var currentIndex:Int = 0 {
        didSet{
            reloadUI()
        }
    }
    
    lazy var collectionView: UICollectionView = {

        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.backgroundColor = .clear
        if #available(iOS 11.0, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        }
        collectionView.register(TSPTPBrowseCell.self, forCellWithReuseIdentifier: cellId)
        collectionView.isPagingEnabled = true
        collectionView.isHidden = true
        if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            flowLayout.minimumInteritemSpacing = 0
            flowLayout.minimumLineSpacing = 0
            flowLayout.scrollDirection = .horizontal
            flowLayout.itemSize = CGSize(width: k_ScreenWidth, height: 490*kDesignScale)
        }
        return collectionView
    }()
    
    
    lazy var leftBtn: UIButton = {
        let leftBtn = UIButton.createButton(image: UIImage(named: "page_left")){ [weak self]  in
            guard let self = self else { return }
            self.collectionView.scrollToItem(at:  IndexPath(item: self.currentIndex-1, section: 0), at: .left, animated: true)
        }
        return leftBtn
    }()
    
    lazy var rightBtn: UIButton = {
        let rightBtn = UIButton.createButton(image: UIImage(named: "page_right")){ [weak self]  in
            guard let self = self else { return }
            self.collectionView.scrollToItem(at: IndexPath(item: self.currentIndex+1, section: 0), at: .left, animated: true)
        }
        return rightBtn
    }()
        
    override func createView() {
        super.createView()
        
        submitBtn.isHidden = false
        submitBtn.setTitle("Save".localized, for: .normal)
        cancelBtn.isHidden = true
        confirmBtn.isHidden = true
        
        bottomView.frame = CGRectMake(0, 92, k_ScreenWidth, k_ScreenHeight-92)

        bottomView.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.leading.trailing.equalTo(0)
            make.top.equalTo(36)
            make.bottom.equalTo(confirmBtn.snp.top).offset(-30)
        }
        
        bottomView.addSubview(leftBtn)
        leftBtn.snp.makeConstraints { make in
            make.leading.equalTo(17)
            make.top.equalTo(244)
            make.width.height.equalTo(40)
        }
        
        bottomView.addSubview(rightBtn)
        rightBtn.snp.makeConstraints { make in
            make.trailing.equalTo(-18)
            make.top.equalTo(244)
            make.width.height.equalTo(40)
        }
        
        kDelayMainShort {
            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
            }
        }
    }
    
    @objc override func clickSubmitBtn(){
        
        if JudgeVip(){
            return
        }
        
        if let image = currentImage{
            PhotoManagerShared.saveImageToAlbum(image) { success, error in
                if success {
                    kSavePhotoSuccesswShared.show(atView: self.view)
                }else{
                    debugPrint(error)
                }
            }
        }else{
            kShowToastDataMissing()
        }
    }
    
    
    func JudgeVip() -> Bool {
        return kJudgeVip(externalBool: currentModel?.response.vip ?? false , vc: self, closePageBlock: nil)
    }
}


extension TSPTPBrowseVC {
    
    func reloadUI() {
        //判断前后是否还有,以此来确定左右翻页按钮
        var isHiddenLeft = false
        var isHiddenRight = false
        if dataModelArray.count == 1{
            isHiddenLeft = true
            isHiddenRight = true
        }else if currentIndex == 0 {
            isHiddenLeft = true
        }else if currentIndex+1 >= dataModelArray.count {
            isHiddenRight = true
        }
        
        leftBtn.isHidden = isHiddenLeft
        rightBtn.isHidden = isHiddenRight
    }
}

//MARK: UICollectionViewDataSource
extension TSPTPBrowseVC: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 {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! TSPTPBrowseCell
        if let model = dataModelArray.safeObj(At: indexPath.item){

            if model.modelType == .example {
//                cell.exampleView.isHidden = false
                cell.netWorkImageView.image = UIImage(named:model.response.resultUrl)
            }else{
//                cell.exampleView.isHidden = true
                cell.netWorkImageView.setAsyncImage(urlString: model.response.resultUrl,placeholder: kPlaceholderImage,contentMode: .scaleAspectFit)
            }

            cell.vipImageView.isHidden = !model.response.vip
            cell.textLabel.text = model.request.promptSort
        }
        return cell
    }
    
}


class TSPTPBrowseCell : 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
        return exampleView
    }()
    
    lazy var netWorkImageView : UIImageView = {
        let netWorkImageView = UIImageView.createImageView(imageName: "",contentMode: .scaleAspectFit,corner: 24.0)
        return netWorkImageView
    }()

    lazy var textLabel: UILabel = {
        let textLabel = UILabel.createLabel(
            font: .font(size: 12),
            textColor: .themeColor,
            numberOfLines: 0
        )
        return textLabel
    }()
    

    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 - 120
        let h = w/kTextWHScale
        bgContentView.addSubview(netWorkImageView)
        netWorkImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(0)
            make.width.equalTo(w)
            make.height.equalTo(h)
        }
        
        let labelBgView = UIView()
        labelBgView.backgroundColor = "#333333".uiColor
        labelBgView.cornerRadius = 16.0
        labelBgView.addSubview(textLabel)
        textLabel.snp.makeConstraints { make in
            make.top.leading.equalTo(12)
            make.trailing.bottom.equalTo(-12)
        }
        
        bgContentView.addSubview(labelBgView)
        labelBgView.snp.makeConstraints { make in
            make.top.equalTo(netWorkImageView.snp.bottom).offset(20)
            make.centerX.equalToSuperview()
            make.leading.greaterThanOrEqualTo(16)
            make.trailing.lessThanOrEqualTo(-16)
            make.bottom.lessThanOrEqualTo(0)
        }
        
        netWorkImageView.addSubview(vipImageView)
        vipImageView.snp.makeConstraints { make in
            make.width.height.equalTo(40)
            make.top.equalTo(-5)
            make.trailing.equalTo(5)
        }
        
        contentView.addSubview(exampleView)
        exampleView.snp.makeConstraints { make in
            make.top.equalTo(8)
            make.leading.equalTo(8)
        }
        
    }
}
