//
//  TSGeneralPicBrowseVC.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/5.
//


private let cellId = "TSGeneralPicBrowseCell"
private let pageBtnTop:CGFloat = 176.0
private let pageBtnH:CGFloat = 40

class TSGeneralPicBrowseVC: TSBottomAlertVC {

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

    var currentModel:TSActionInfoModel?{
        if let model = dataModelArray.safeObj(At: currentIndex){
            return model
        }
        return nil
    }
    
    lazy var contactsTool: TSContactsTool = {
        let contactsTool = TSContactsTool(targetVC: self)
        return contactsTool
    }()
    
    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(TSGeneralPicBrowseCell.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 leftPageBtn: 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 rightPageBtn: 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()
        
        saveBtn.isHidden = true
        againBtn.isHidden = true
        
        rightBtn.isHidden = false
        rightBtn.setTitle(saveBtnText, for: .normal)
        
        leftBtn.isHidden = false
        leftBtn.setTitle("Copy Text".localized, for: .normal)
        
        bottomViewH = 540
       
        diyView.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.leading.trailing.equalTo(0)
            make.top.equalTo(0)
            make.bottom.equalTo(0)
        }
        
        diyView.addSubview(leftPageBtn)
        leftPageBtn.snp.makeConstraints { make in
            make.leading.equalTo(16)
            make.top.equalTo(pageBtnTop)
            make.width.height.equalTo(pageBtnH)
        }
        
        diyView.addSubview(rightPageBtn)
        rightPageBtn.snp.makeConstraints { make in
            make.trailing.equalTo(-16)
            make.top.equalTo(pageBtnTop)
            make.width.height.equalTo(pageBtnH)
        }
        
        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
            }
        }
    }
    
    
    override func clickLeftBtn() {
//        if JudgeVip(){
//            return
//        }
  
        if let model = currentModel{
            //拷贝文字到截切板
            UIPasteboard.general.string = model.request.prompt
            kSavePhotoSuccesswShared.show(atView: self.view,text: "Copy Successfully".localized,showViewBtn:false)
        }else{
            kShowToastDataMissing()
        }
    }
    
    override func clickRightBtn() {

//        if JudgeVip(){
//            return
//        }
        
        if let image = currentImage{
            if style == .poster {
                PhotoManagerShared.saveImageToAlbum(image) { success, error in
                    if success {
                        kSavePhotoSuccesswShared.show(atView:self.view)
                    }else{
                        debugPrint(error)
                    }
                }
            }else if style == .photo {
                contactsTool.setContactsAvatar(avatarImage: image) { data, error in
                    if error == nil {
                        kSavePhotoSuccesswShared.show(atView: self.view,showViewBtn: false)
                    }
                }
            }
        }else{
            kShowToastDataMissing()
        }
    }

//    func JudgeVip() -> Bool {
//        return kJudgeVip(externalBool: currentModel?.response.vip ?? false , vc: self, closePageBlock: nil)
//    }
}


extension TSGeneralPicBrowseVC {
    
    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
        }
        
        leftPageBtn.isHidden = isHiddenLeft
        rightPageBtn.isHidden = isHiddenRight
    }
    
    var saveBtnText:String{
        if style == .photo{
            return "Set Now".localized
        }
        return "Download".localized
    }
    
    var cellImageSize:CGSize {
        if style == .photo {
            return CGSizeMake(200 , 200)
        }
        return CGSize(width: 140, height: 272)
    }
}

//MARK: UICollectionViewDataSource
extension TSGeneralPicBrowseVC: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! TSGeneralPicBrowseCell
        if let model = dataModelArray.safeObj(At: indexPath.item){
            cell.cellImageSize = cellImageSize
            cell.netWorkImageView.setAsyncImage(urlString: model.response.resultUrl,placeholder: kPlaceholderImage,contentMode: .scaleAspectFill)
            cell.vipImageView.isHidden = !model.response.vip
            cell.textLabel.isHidden =  model.request.promptSort.count < 0
            cell.textLabel.text = model.request.promptSort
        }
        return cell
    }
    
}


class TSGeneralPicBrowseCell : 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: 12.0)
        return netWorkImageView
    }()

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

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

    
    var cellImageSize:CGSize = CGSizeMake(140, 272) {
        didSet{
            netWorkImageView.snp.updateConstraints { make in
                make.top.equalTo(cellImageTop)
                make.size.equalTo(cellImageSize)
            }
            var corner = 12.0
            if cellImageSize.width == cellImageSize.height {
                corner = cellImageSize.height/2.0
            }
            netWorkImageView.cornerRadius = corner
        }
    }
    
    var cellImageTop:CGFloat{
        get {
            return (pageBtnH/2.0+pageBtnTop) - (cellImageSize.height/2.0)
        }
    }
    
    override func creatUI() {
        bgContentView.addSubview(netWorkImageView)
        netWorkImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(cellImageTop)
            make.size.equalTo(cellImageSize)
        }
        
        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(12)
            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)
        }
        
    }
}
