//
//  MaintainViewListController.swift
//  PhoneManager
//
//  Created by edy on 2025/5/13.
//

import UIKit

class MaintainViewListController: BaseViewController {
    
    var selectAsset:[[AssetModel]] = []
    
    var selectAssetDic:[String:[[AssetModel]]] = [:]
    
    var viewModel:MaintaiViewModel = MaintaiViewModel()
    
    var removeBtn:UIButton!
    
    var isSelectAll = false

    override func viewDidLoad() {
        super.viewDidLoad()
        titleView.model.title = "Keep List"
        configUI()
        getData()
    }
    
    
    func configUI(){
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(titleView.snp.bottom)
        }
        
        maintaiTipsAlertView.confirmBlock = {[weak self] in
            guard let weakSelf = self else { return }
            weakSelf.removeFromKeep()
            weakSelf.maintaiTipsAlertView.disMiss()
            weakSelf.view.hideBlur()
        }
        
        maintaiTipsAlertView.cancelBlock = {[weak self] in
            guard let weakSelf = self else { return }
            weakSelf.isSelectAll = false
            weakSelf.view.hideBlur()
        }
        
        maintaiBottomView.removeMaintaiBlock = {[weak self] in
            guard let weakSelf = self else { return }
            weakSelf.maintaiTipsAlertView.show()
            weakSelf.view.showBlur()
        }
        
        removeBtn = UIButton()
        removeBtn.setTitle("Not keep All", for: .normal)
        removeBtn.addTarget(self, action: #selector(removeAll), for: .touchUpInside)
        removeBtn.setTitleColor(.black, for: .normal)
        removeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
        removeBtn.isHidden = true
        titleView.addSubview(removeBtn)
        
        removeBtn.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.centerY.equalTo(titleView.titleLabel)
        }
    }
    
    // 移除所有
    @objc func removeAll(){
        isSelectAll = true
        maintaiTipsAlertView.show()
        self.view.showBlur()
    }
    
    
    func removeFromKeep(){
        if isSelectAll{
            let ids = viewModel.souces.flatMap{$0}.compactMap{$0.localIdentifier}
            if GroupDatabase.shared.batchDelete(localIdentifiers: ids){
                getData()
                selectAsset.removeAll()
                dealBottomView()
            }
            isSelectAll = false
        }else{
            let ids = selectAsset.flatMap{$0}.compactMap{$0.localIdentifier}

            if GroupDatabase.shared.batchDelete(localIdentifiers: ids){
                getData()
                selectAsset.removeAll()
                dealBottomView()
            }
        }
        
        
    }
    
    func getData(){
        viewModel.refreshData {[weak self] in
            guard let self = self else { return }
            if self.viewModel.souces.isEmpty {
                self.view.addSubview(self.maintaiEmptyView)
            } else {
                self.maintaiEmptyView.removeFromSuperview()
            }
            self.removeBtn.isHidden = viewModel.souces.count == 0
            self.collectionView.reloadData()
        }
    }
    
    
    lazy var collectionView:UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: (ScreenW-35)/2.0, height: (ScreenW-35)/2.0)
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsets(top: 22, left: 16, bottom: 20, right: 16)
        layout.minimumInteritemSpacing = 3
        layout.minimumLineSpacing = 10
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: view.width, height: view.height), collectionViewLayout:layout)

        collectionView.delegate = self
        collectionView.backgroundColor = .white
        collectionView.dataSource = self
        collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom:78+kSafeAreaInsets.bottom, right: 0)
        collectionView.register(UINib(nibName: "MaintainViewListCell", bundle: nil), forCellWithReuseIdentifier: "MaintainViewListCell")

        return collectionView
    }()
    
    lazy var maintaiBottomView:MaintaiBottomView = {
        let maintaiBottomView = Bundle.main.loadNibNamed("MaintaiBottomView", owner: nil)?.last as! MaintaiBottomView
        maintaiBottomView.frame = CGRect(x: 0, y: ScreenH, width: ScreenW, height: 78+kSafeAreaInsets.bottom)
        return maintaiBottomView
    }()

    lazy var maintaiTipsAlertView:MaintaiTipsAlertView = {
        let maintaiTipsAlertView = Bundle.main.loadNibNamed("MaintaiTipsAlertView", owner: nil)?.last as! MaintaiTipsAlertView
        return maintaiTipsAlertView
    }()
    
    lazy var maintaiEmptyView:MaintaiEmptyView = {
        let maintaiEmptyView = Bundle.main.loadNibNamed("MaintaiEmptyView", owner: nil)?.last as! MaintaiEmptyView
        maintaiEmptyView.frame = CGRectMake(0, 140, ScreenW, 330)
        return maintaiEmptyView
    }()
    
    func dealBottomView(){
        
        if selectAsset.count > 0{
            let count = selectAsset.flatMap{$0}.count
            maintaiBottomView.numberL.text = "\(count)"
            view.addSubview(maintaiBottomView)
            maintaiBottomView.show()
        }else{
            maintaiBottomView.disMiss()
        }
    }

}

extension MaintainViewListController:UICollectionViewDataSource,UICollectionViewDelegate{
    
   func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
       return viewModel.souces.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MaintainViewListCell", for: indexPath) as! MaintainViewListCell
        let isSelect = selectAsset.containsGroup(matching: viewModel.souces[indexPath.row])
        cell.reloadData(viewModel.souces[indexPath.row], isSelect:isSelect)
        cell.selectBlock = {[weak self] in
            guard let weakSelf = self else { return }
            weakSelf.vibrate()
            weakSelf.dealPickAssetModel(row: indexPath.row,isSelect: isSelect)
            weakSelf.collectionView.reloadData()
        }

        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        let vc = MaintaiDetailViewController()
        vc.selectAsset = selectAsset
        vc.scrollIndex = indexPath.row
        vc.needReloadBlock = {[weak self] selects in
            guard let weakSelf = self else { return }
            weakSelf.selectAsset = selects
            weakSelf.getData()
            weakSelf.dealBottomView()
        }
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func dealPickAssetModel(row:Int,isSelect:Bool){

        if let group = selectAsset.matches(containingAny: viewModel.souces[row]).first{
            if group.matchedElements.count == viewModel.souces[row].count{
                // 如果数量一致 说明选中了 取消全选
                selectAsset.remove(at: group.groupIndex)
            }else{
                // 如果不一致 说明选中了部分 直接顶掉
                selectAsset.remove(at: group.groupIndex)
                selectAsset.append(viewModel.souces[row])
            }
        }else{
            selectAsset.append(viewModel.souces[row])
        }

        
        dealBottomView()
    }
    
}
