//
//  TSRecollectionVC.swift
//  KittensTravelNotes
//
//  Created by 100Years on 2025/7/7.
//

import RealmSwift
class TSRecollectionVC: TSBaseVC {
    
    var listModelArray:[(date: Date, models: Results<TSDBActionInfoModel>)] = []
    //###################################### 导航栏 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: "Recollection".localized,font: .font(name: .CherryBombOneRegular, size: 30))
        navBarView.barView.addSubview(label)
        label.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 pageNullView: TSRecollectionNullView = {
        let pageNullView = TSRecollectionNullView()
        pageNullView.isHidden = true
        pageNullView.clickBlock = { [weak self]  in
            guard let self = self else { return }
            TSPlogVC.enterSelectPhotos(target: self,style: .ptp) { image in
                kPushVC(target: self, modelVC: TSPlogUploadPhotoVC(upLoadImage:image, generatorStyle: .ptp))
            }
        }
        return pageNullView
    }()
    
    lazy var itemSize: CGSize = {
        let itemW = (k_ScreenWidth-32.0-16.0-2.0)/2.0
        let itemH = kGetScaleHeight(originalSize: CGSize(width: 163.0, height: 290.0), width: itemW)
        return CGSize(width: itemW, height: itemH)
    }()
    let sectionInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
    
    lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.itemSize = itemSize
        layout.minimumInteritemSpacing = 16
        layout.minimumLineSpacing = 16
        layout.sectionInset = sectionInset
        return layout
    }()
    
    lazy var collectionView:TSBaseCollectionView = {
        let collectionView = TSBaseCollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(TSRecollectionCell.self, forCellWithReuseIdentifier: "TSRecollectionCell")
        collectionView.register(TSRecollectionSectionHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "TSRecollectionSectionHeader")
        return collectionView
    }()
    
    
    override func createView() {
        addGradientColorTop(alpha: 0.8)
        navBarContentView.addSubview(navBarView)
        navBarView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        contentView.addSubview(pageNullView)
        pageNullView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        contentView.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    override func dealThings() {
        updateDataView()
        NotificationCenter.default.addObserver(self, selector: #selector(operationChanged(_:)), name: .kGenerateBasePhotoOperation, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(updateDataView), name: .kAIPhotoDataChanged, object: nil)
//        NotificationCenter.default.addObserver(self, selector: #selector(updateVipView), name: .kPurchaseDidChanged, object: nil)
//        updateVipView()
    }
    
    override func viewWillAppear(_ animated: Bool) {
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        
    }
    
    @objc func operationChanged(_ notification: Notification) {
        if let userInfo = notification.userInfo as? [String: Any],let state = userInfo["state"] as? TSProgressState {
            if state.reloadNewData {
                self.updateDataView()
            }
        }
    }
    
    @objc func updateDataView(){
        listModelArray = TSDBHistory.getGroupedModelsLazily()//惰性加载特性
        updateView()
        
//        TSDBHistory.getGroupedModelsLazily(completion: { [weak self] dbDatas in
//            guard let self = self else { return }
//            listModelArray = dbDatas
//            updateView()
//        })

    }
    
    func updateView() {
        collectionView.reloadData()
        pageNullView.isHidden = listModelArray.count > 0
        collectionView.isHidden = !pageNullView.isHidden
    }
    
    @objc func updateVipView() {
        kMainAsync{
//            self.vipBtn.isHidden = PurchaseManager.default.isVip
        }
    }
}

extension TSRecollectionVC: UICollectionViewDataSource ,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return listModelArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let datas = listModelArray.safeObj(At: section)
        return datas?.1.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if let datas = listModelArray.safeObj(At: indexPath.section),
           let item = datas.1[safe: indexPath.item],
           let cell = collectionView.dequeueReusableCell(withReuseIdentifier:"TSRecollectionCell", for: indexPath) as? TSRecollectionCell {
            cell.dataModel = item.getModel()
            cell.buttonTapped = { [weak self] cmd in
                self?.handelCellCmd(cmd: cmd,indexPath: indexPath)
            }
            return cell
        }
        return UICollectionViewCell()
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if let datas = listModelArray.safeObj(At: indexPath.section),
           kind == UICollectionView.elementKindSectionHeader,
           let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "TSRecollectionSectionHeader", for: indexPath) as? TSRecollectionSectionHeader{
            header.date = datas.0
            header.clickBlock = { [weak self] in
                guard let self = self else { return }
                deleteSection(indexPath: indexPath)
            }
            return header
        }
        return UICollectionReusableView()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
        return itemSize
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{
        if section == listModelArray.count-1 {
            return UIEdgeInsets(top: sectionInset.top, left: sectionInset.left, bottom: sectionInset.bottom+20+k_Height_TabBar, right: sectionInset.right)
        }
        return sectionInset
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: k_ScreenWidth, height: 56)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if let datas = listModelArray.safeObj(At: indexPath.section),
           let item = datas.1[safe: indexPath.item]{
            if item.status != "success" {
                return
            }
            
            let results = TSDBHistory.getAllSunccessData()
            let index = results.firstIndex(where: { $0.primaryKey == item.primaryKey })
            let browseVC = TSPhotoBrowseVC(dataModelArray: results, currentIndex: index ?? 0) { [weak self] deleteModel in
                guard let self = self else { return }
                deleteItem(model:deleteModel)
            }
            kPresentModalVC(target: self, modelVC: browseVC,transitionStyle: .crossDissolve)
            
//            let gennerateVC = TSAIPhotoGeneratorVC(generatorModel: TSAIListPhotoGeneratorModel(upLoadImage: UIImage(), generatorStyle:.ptp),infoModel: item.getModel()) { model in }
//            gennerateVC.modalPresentationStyle = .overFullScreen
//            gennerateVC.modalTransitionStyle = .crossDissolve
//            self.present(gennerateVC, animated: true)
        }
           
    }
}

extension TSRecollectionVC{
    
    func deleteSection(indexPath: IndexPath){
        if let datas = listModelArray.safeObj(At: indexPath.section){
            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 }
                    TSRMShared.writeThread { realm in
                        let objectsToDelete = datas.1 //.filter { $0.status != "running" && $0.status != "pending"}
                        objectsToDelete.forEach { object in
                           object.deleteResources()//删除资源
                        }
                        realm.delete(objectsToDelete)
                    }
                    updateDataView()
                }
            ))
        }
    }
    
    func handelCellCmd(cmd:String,indexPath: IndexPath){
        if let datas = listModelArray.safeObj(At: indexPath.section),
           let model = datas.1[safe: indexPath.item]{

            if cmd == "cancel" {
                TSCustomAlertController.show(in: self, config: TSCustomAlertController.AlertConfig(
                    message: "After cancellation, your task will be interrupted and no results".localized,
                    messageColor: .white,
                    messageFont: .systemFont(ofSize: 16),
                    cancelTitle: "Cancel".localized,
                    cancelColor: .white,
                    confirmTitle: "Wait".localized,
                    confirmColor: .themeColor,
                    cancelAction: { [weak self]  in
                        guard let self = self else { return }
                        deleteItem(model:model)
                    }
                ))
            }else if cmd == "delete" {
                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 }
                        deleteItem(model:model)
                    }
                ))
            }
        }
    }
    
    func deleteItem(model:TSDBActionInfoModel){
        TSRMShared.writeThread { realm in
            model.deleteResources()//删除资源
            realm.delete(model)
        }
        updateDataView()
    }
}
extension TSRecollectionVC{
    static func showPosition(){
        AppDelegate.tabbar?.changeSelectedIndex(index: 1)
    }
    
}
