//
//  TSPlogVC.swift
//  KittensTravelNotes
//
//  Created by 100Years on 2025/7/5.
//

import Alamofire
import UIKit
import AppTrackingTransparency

class TSPlogVC: TSBaseVC {
    
    lazy var viewModel: TSPlogVM = {
        let viewModel = TSPlogVM()
        return viewModel
    }()
    
    //###################################### 导航栏 view ######################################
//    lazy var vipBtn: UIButton = {
//        let vipBtn = UIButton.createButton(image: UIImage(named: "nav_vip")) { [weak self] in
//            guard let self = self else { return }
//            TSPurchaseVC.show(target: self) {}
//        }
//        return vipBtn
//    }()
    
    lazy var navBarView: TSBaseNavContentBarView = {
        let navBarView = TSBaseNavContentBarView()

//        let label = UILabel.createLabel(text: "CAts Plog".localized,font: .font(name: .CherryBombOneRegular, size: 30))
//        navBarView.barView.addSubview(label)
//        label.snp.makeConstraints { make in
//           make.center.equalToSuperview()
//        }
        
        let imageView = UIImageView.createImageView(image: .navTitlePlog)
        navBarView.barView.addSubview(imageView)
        imageView.snp.makeConstraints { make in
           make.center.equalToSuperview()
        }
        
//        navBarView.barView.addSubview(vipBtn)
//        vipBtn.snp.makeConstraints { make in
//            make.centerY.equalToSuperview()
//            make.trailing.equalTo(-16)
//            make.width.height.equalTo(32)
//        }

       return navBarView
    }()
    
    //###################################### 导航栏 ######################################
    lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        return layout
    }()
    lazy var collectionView:TSBaseCollectionView = {
        let collectionView = TSBaseCollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(TSPlogBaseCell.self, forCellWithReuseIdentifier: "TSPlogBaseCell")
        collectionView.register(TSPlogBannerCell.self, forCellWithReuseIdentifier: "TSPlogBannerCell")
        collectionView.register(TSPlogMoreCell.self, forCellWithReuseIdentifier: "TSPlogMoreCell")
        collectionView.register(TSAIDataHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "TSAIDataHeaderView")
        return collectionView
    }()

    override func createView() {
        addGradientColorTop()
        navBarContentView.addSubview(navBarView)
        navBarView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        contentView.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        

    }
    
    override func dealThings() {
        kPurchaseBusiness.launchPrchase()
        let networkManager = NetworkReachabilityManager.default
        networkManager?.startListening { [weak self] status in
            guard let self = self else { return }
            switch status {
            case .reachable:
                networkManager?.stopListening()
                self.collectionView.reloadData()
            default:
                break
            }
        }
        
//        NotificationCenter.default.addObserver(self, selector: #selector(updateVipView), name: .kPurchaseDidChanged, object: nil)
//        updateVipView()
    }
    
    override func viewWillAppear(_ animated: Bool) {
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        
    }
    
    @objc func updateVipView() {
        kMainAsync{
//            self.vipBtn.isHidden = PurchaseManager.default.isVip
        }
    }
}
extension TSPlogVC: UICollectionViewDataSource ,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return viewModel.listDatas.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let secModel = viewModel.listDatas.safeObj(At:section){
            return secModel.items.count
        }
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if let secModel = viewModel.listDatas.safeObj(At:indexPath.section),let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing:secModel.style.cell), for: indexPath) as? TSPlogBaseCell, let item = secModel.items.safeObj(At:indexPath.row){
            cell.items = item
            cell.clickBlock = { [weak self] model  in
                guard let self = self else { return }
                if let secModel = viewModel.listDatas.safeObj(At:indexPath.section) {
                    Self.clickCell(target: self,indexPath: indexPath, itemModel:model,secModel: secModel)
                }
            }
            return cell
        }
        return UICollectionViewCell()
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if let secModel = viewModel.listDatas.safeObj(At:indexPath.section),
           kind == UICollectionView.elementKindSectionHeader,
           let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "TSAIDataHeaderView", for: indexPath) as? TSAIDataHeaderView{
            header.sectionModel = secModel
            header.clickBlock = { [weak self] model in
                guard let self = self else { return }
                clickHeader(indexPath: indexPath,model: model)
            }
            return header
        }
        return UICollectionReusableView()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
        if let secModel = viewModel.listDatas.safeObj(At:indexPath.section) {
            return secModel.style.itemSize
        }
        return .zero
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{
        if let secModel = viewModel.listDatas.safeObj(At:section) {
            var sectionEdge = secModel.sectionEdge
//            if secModel.title.isEmpty {
//                sectionEdge = UIEdgeInsets(top: 20, left: kAIDataSection.left, bottom: 0, right: kAIDataSection.right)
//            }
            if section == viewModel.listDatas.count-1 {
                sectionEdge = UIEdgeInsets(top: sectionEdge.top, left: sectionEdge.left, bottom: sectionEdge.bottom+20+k_Height_TabBar, right: sectionEdge.right)
            }
            return sectionEdge
        }
        return .zero
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        if let secModel = viewModel.listDatas.safeObj(At:section),secModel.title.count > 0 {
            return CGSize(width: k_ScreenWidth, height: kAIDataSectionH)
        }
        return .zero
    }
}

func kShowGenerateBusyView(view:UIView) ->Bool{
    if TSGenerateBasePhotoOperationQueue.shared.isAvailability == false {
        kTextToastShared.show(atView: view,text: "1 task is processing"){
            TSRecollectionVC.showPosition()
        }
        return true
    }
    return false
}
extension TSPlogVC {
    
    func clickHeader(indexPath:IndexPath,model:TSAIDataSectionModel) {
        kPushVC(target: self, modelVC: TSPlogMoreVC(sectionModel: model))
    }

    static func clickCell(target:UIViewController,indexPath:IndexPath,itemModel:TSAIDataItemModel,secModel:TSAIDataSectionModel) {
        if kShowGenerateBusyView(view: target.view) { return }
        if secModel.style == .banner {
            Self.enterSelectPhotos(target: target,style: itemModel.style) { image in
                kPushVC(target: target, modelVC: TSPlogUploadPhotoVC(upLoadImage:image, generatorStyle: .ptp))
            }
        }else{
        
            if let dataModelArray = secModel.items.first as? [TSAIDataItemModel]{
                let currentIndex = dataModelArray.firstIndex { model in  model === itemModel }
                kPushVC(target: target, modelVC: TSPlogImageBrowseVC(dataModelArray: dataModelArray,currentIndex: currentIndex ?? 0))
            }

//            Self.enterSelectPhotos(target: target,style: itemModel.style) { image in
//                kPushVC(target: target, modelVC: TSPlogUploadPhotoVC(upLoadImage:image, generatorStyle: itemModel.style,dataModel: itemModel.generateModel))
//            }
        }
    }
}

extension TSPlogVC{
    static func enterSelectPhotos(target:UIViewController,style:TSGeneratorStyle,complete: @escaping (UIImage)->Void){
        if style.userDefaultsKey.count == 0 {
            self.pickSinglePhoto(target:target,complete:complete)
        }else{
            TSPlogUploadHintVC.userDefaultsKey = style.userDefaultsKey
            if TSPlogUploadHintVC.isShowUploadImageHint{
                TSPlogUploadHintVC.isShowUploadImageHint = false
                self.presentModalHintVC(target:target,config:style.config,complete:complete)
            }else {
                self.pickSinglePhoto(target:target,complete:complete)
            }
        }
    }

    static func presentModalHintVC(target:UIViewController,config:TSPlogUploadHintVC.Config,complete:@escaping (UIImage)->Void){
        let hintBaseVC = TSPlogUploadHintVC(config: config)
        hintBaseVC.clickUpImageHandle = { image in
            if let image = image {
                complete(image)
            }else{
                dePrint("图片异常")
            }
            kMainShort {
                hintBaseVC.dismissPageVC()
            }
        }
        kPresentModalVC(target: target, modelVC: hintBaseVC,transitionStyle: .crossDissolve)
    }
    
    static func pickSinglePhoto(target:UIViewController,complete: @escaping (UIImage)->Void)  {
        let photoPickerManager = TSPhotoPickerManager(viewController: target)
        photoPickerManager.pickCustomSinglePhoto() { image, errorString in
            if let errorString = errorString {
                TSToastShared.showToast(text: errorString)
            }else if let image = image {
                complete(image)
            }else{
                dePrint("图片异常")
            }
            kMainShort {
                photoPickerManager.dismissPageVC()
            }
            
        }
    }
}
