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

import UIKit

class MaintaiDetailViewController: BaseViewController {
    

    var viewModel:MaintaiViewModel = MaintaiViewModel()
    var selectAsset:[[AssetModel]] = []
    var needReloadBlock:(([[AssetModel]]) ->Void)?
    
    var scrollIndex = 0
    var isFirstLoad = true
    
    var removeBtn:UIButton!
    
    var isSelectAll = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configUI()
        getData()
        
        dealBottomView()
    }

    
    func configUI(){
        
        view.addSubview(tableView)
        tableView.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.view.showBlur()
            weakSelf.maintaiTipsAlertView.show()
        }
        
        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){
                selectAsset.removeAll()
                self.navigationController?.popViewController(animated: true)
            }
            isSelectAll = false
        }else{
            let ids = selectAsset.flatMap{$0}.compactMap{$0.localIdentifier}

            if GroupDatabase.shared.batchDelete(localIdentifiers: ids){
                getData()
                selectAsset.removeAll()
            }
        }
    }
    
    func dealBottomView(){
        if selectAsset.count > 0{
            let count = selectAsset.flatMap{$0}.count
            maintaiBottomView.numberL.text = "\(count)"
            view.addSubview(maintaiBottomView)
            maintaiBottomView.show()
        }else{
            maintaiBottomView.disMiss()
        }
    }
    
    func getData(){
        viewModel.refreshData {[weak self] in
            guard let self = self else { return }
            self.removeBtn.isHidden = viewModel.souces.count == 0
            self.tableView.reloadData()
            if self.isFirstLoad{
                self.tableView.layoutIfNeeded()
                self.isFirstLoad = false
                
                // 异步执行滚动，确保布局已稳定
                DispatchQueue.main.async {
                    self.tableView.scrollToRow(at: IndexPath.init(row: self.scrollIndex, section: 0), at: .middle, animated: true)
                }
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        needReloadBlock?(selectAsset)
    }
    
    lazy var tableView:UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom:78+kSafeAreaInsets.bottom, right: 0)
        tableView.register(UINib(nibName: "MaintaiDetailTableViewCell", bundle: nil), forCellReuseIdentifier: "MaintaiDetailTableViewCell")
        tableView.register(UINib(nibName: "MaintaiDetailPicCell", bundle: nil), forCellReuseIdentifier: "MaintaiDetailPicCell")
        tableView.register(UINib(nibName: "MaintaiDetialVideoCell", bundle: nil), forCellReuseIdentifier: "MaintaiDetialVideoCell")
        return tableView
    }()
  
    
    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
    }()

}

extension MaintaiDetailViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.souces.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return (ScreenW-14) + 74.RW() + 30 // 360.RW()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if viewModel.souces[indexPath.row].first?.mediaType == 1{
            let cell = tableView.dequeueReusableCell(withIdentifier: "MaintaiDetailTableViewCell") as! MaintaiDetailTableViewCell


            if let groupIndex = selectAsset.matches(containingAny: viewModel.souces[indexPath.row]).first?.groupIndex{
                cell.selectAsset = selectAsset[groupIndex]
            }else{
                cell.selectAsset = []
            }
            
            // 拿到当前在选中数据的下标
             var selectIndex = selectAsset.firstIndex(where: {
                 $0 == cell.selectAsset
             })
            
           // cell.selectAsset =
            cell.source = viewModel.souces[indexPath.row]
            cell.selectCallBack = {[weak self] selects in
                guard let weakSelf = self else { return }
                weakSelf.vibrate()
                if let sIndex = selectIndex{
                    //已经有选中状态
                    Print("已经有选中数据",sIndex)
                    if selects.count > 0{
                        weakSelf.selectAsset[sIndex] = selects
                    }else{
                        weakSelf.selectAsset.remove(at: sIndex)
                        selectIndex = nil
                    }
                    
                }else{
                    Print("没有任何选中数据")
                    weakSelf.selectAsset.append(selects)
                    selectIndex = weakSelf.selectAsset.firstIndex(where: {
                        $0 == selects
                    })
                }
                weakSelf.dealMutilImagePick()
            }
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "MaintaiDetialVideoCell") as! MaintaiDetialVideoCell
        cell.model = viewModel.souces[indexPath.row].first
        cell.selectBtn.isSelected = selectAsset.contains(viewModel.souces[indexPath.row])
        cell.selectChangeBlock = {[weak self] in
            guard let weakSelf = self else { return }
            weakSelf.dealPickAssetModel(index: indexPath.row)
            // 不要刷新整个cell，只更新选中状态
            if let current = tableView.cellForRow(at: indexPath) as? MaintaiDetialVideoCell{
                current.selectBtn.isSelected = weakSelf.selectAsset.contains(weakSelf.viewModel.souces[indexPath.row])
            }
        }
        return cell


    }
    
    
    func dealMutilImagePick(){
        
        if selectAsset.count > 0{
            let count = selectAsset.flatMap{$0}.count
            maintaiBottomView.numberL.text = "\(count)"
            view.addSubview(maintaiBottomView)
            maintaiBottomView.show()
        }else{
            maintaiBottomView.disMiss()
        }
       // tableView.reloadData()
//        UIView.performWithoutAnimation {
//            self.tableView.reloadData()
//        }
    }
    
    func dealPickAssetModel(index:Int){
        
        if let index = selectAsset.firstIndex(where: {
            $0 == viewModel.souces[index]
        }) {
            // 包含：移除元素
            selectAsset.remove(at: index)
        } else {
            // 不包含：添加元素
            selectAsset.append(viewModel.souces[index])
        }
        
        if selectAsset.count > 0{
            let count = selectAsset.flatMap{$0}.count
            maintaiBottomView.numberL.text = "\(count)"
            view.addSubview(maintaiBottomView)
            maintaiBottomView.show()
        }else{
            maintaiBottomView.disMiss()
        }
    }
    
}
