//
//  HomeInfoTableViewCell.swift
//  PhoneManager
//
//  Created by edy on 2025/3/25.
//

import UIKit
import SnapKit

class HomeInfoTableViewCell:UITableViewCell {
    
    static let identifier = "HomeInfoTableViewCellID"
    
    private var backView:UIView?
    
    var collectionView: UICollectionView?
    
    private var numberLabel:UILabel?
    
    private var seletedAllBtn:UIButton?
    
    var type : PhotsFileType?
    
    var callBack:callBack<Any> = {text in}
    
    var saveKeepListFinishedCallback : (IndexPath)->Void = {index in}
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        setupUI()
        addSubview1()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setupUI() {
        
        self.selectionStyle = .none
        
        backView = UIView()
        backView?.backgroundColor = UIColor.colorWithHex(hexStr: "#F2F6FC")
        backView?.layer.cornerRadius = 12
        backView?.layer.masksToBounds = true
        backView?.x = marginLR
        backView?.y = marginLR
        backView?.isUserInteractionEnabled = true
        
        numberLabel = UILabel()
        numberLabel?.textColor = UIColor.colorWithHex(hexStr: "#111111")
        numberLabel?.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
        
        seletedAllBtn = UIButton()
        seletedAllBtn?.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
        seletedAllBtn?.setTitle("Select All", for: .normal)
        seletedAllBtn?.setTitle("Deselect all", for: .selected)
        
        seletedAllBtn?.setTitleColor(UIColor.colorWithHex(hexStr: mColor), for: .normal)
        seletedAllBtn?.sizeToFit()
        seletedAllBtn?.addTarget(self, action: #selector(seletedAllBtnClick), for: .touchUpInside)
        
        let flowlayout:UICollectionViewFlowLayout =  UICollectionViewFlowLayout()
        flowlayout.scrollDirection = .horizontal
        flowlayout.minimumLineSpacing = 6
        
        collectionView = UICollectionView.init(frame: CGRectMake(0, 0 , ScreenW , ScreenH), collectionViewLayout: flowlayout)
        collectionView?.backgroundColor = .clear
        
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
        
        collectionView?.register(ImageSeletedCollectionCell.self, forCellWithReuseIdentifier: ImageSeletedCollectionCell.identifiers)
        collectionView?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: marginLR)
        
        collectionView?.dataSource = self
        collectionView?.delegate = self
    }
    
    func addSubview1() {
        
        contentView.addSubview(backView!)
        contentView.addSubview(numberLabel!)
        contentView.addSubview(seletedAllBtn!)
        contentView.addSubview(collectionView!)
    }
    
    var model:HomeInfoTableItem? {
        
        didSet {
            
            guard let model else {return}
            
            let cH = ((model.smodels?.count ?? 0) > 2 ? 205 : 229) + 8
            
            backView?.height = CGFloat(cH - 8)
            backView?.width  = ScreenW - 8 * 2
            backView?.centerY = CGFloat(cH / 2)
            backView?.centerX = ScreenW / 2
            
            numberLabel?.text = "\(model.smodels?.count ?? 0) \(String(model.titleText!))"
            numberLabel?.sizeToFit()
            numberLabel?.x = (backView?.x ?? 0) + 8
            numberLabel?.y = (backView?.y ?? 0) + 8
            
            seletedAllBtn?.centerY = numberLabel?.centerY ?? 0
            seletedAllBtn?.x = (backView?.x ?? 0) + (backView?.width ?? 0) - 12 - (seletedAllBtn?.width ?? 0)
            checkSeletedAll()
            
            collectionView?.height = CGFloat(cH - Int(CGRectGetMaxY(numberLabel?.frame ?? CGRect())) - 16)
            collectionView?.width = (backView?.width ?? 0) - 16
            collectionView?.x = (backView?.x ?? 0) + 8
            collectionView?.y = (backView?.y ?? 0) + (backView?.height ?? 0) - (collectionView?.height ?? 0) - 8
            
            self.collectionView?.reloadData()
            
//            UIView.transition(with: collectionView!, duration: 0.3, options: .transitionCrossDissolve, animations: {
//                self.collectionView?.reloadData()
//            }, completion: nil)
        }
    }
    
    // 重新刷新下集合
    func reloadCollectionView(){
        DispatchQueue.main.async {
            if let collectionView = self.collectionView {
                for section in 0..<collectionView.numberOfSections {
                    for item in 0..<collectionView.numberOfItems(inSection: section) {
                        UIView.transition(with:collectionView, duration: 0.3, options: .transitionCrossDissolve, animations: {
                            collectionView.reloadItems(at: [IndexPath(row: item, section: section)])
                        }, completion: nil)
                    }
                }
            }
        }
        
    }
    
    @objc func seletedAllBtnClick() {
        
        DispatchQueue.main.async {[weak self] in
            
            guard let self else {return}
            
            seletedAllBtn?.isSelected = !(seletedAllBtn?.isSelected ?? true)
            
            seletedAllBtn?.sizeToFit()
            seletedAllBtn?.centerY = numberLabel?.centerY ?? 0
            seletedAllBtn?.x = (backView?.x ?? 0) + (backView?.width ?? 0) - 12 - (seletedAllBtn?.width ?? 0)
        }
        
        
        for (index,smodel) in (model?.smodels ?? []).enumerated() {
            
            if index == 0 {
                
                smodel.isSeleted = false
            }else {
                
                smodel.isSeleted = !(seletedAllBtn?.isSelected ?? false)
            }
            
        }
        if collectionView != nil {
            UIView.transition(with: collectionView!, duration: 0.3, options: .transitionCrossDissolve, animations: {
                self.collectionView?.reloadData()
            }, completion: nil)
        }
        callBack("changgeSeleted")
    }
    
    func checkSeletedAll() {
        
        var isSeletedAll:Bool = false
        
        for smodel in model?.smodels ?? [] {
            
            if (smodel.isSeleted ?? false) {
                
                isSeletedAll = true
            }
        }
        
        seletedAllBtn?.isSelected = isSeletedAll
        
        callBack("changgeSeleted")
        
        DispatchQueue.main.async {[weak self] in
            
            guard let self else {return}
            
            seletedAllBtn?.sizeToFit()
            seletedAllBtn?.centerY = numberLabel?.centerY ?? 0
            seletedAllBtn?.x = (backView?.x ?? 0) + (backView?.width ?? 0) - 12 - (seletedAllBtn?.width ?? 0)
        }
    }
    
    override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
    
}

extension HomeInfoTableViewCell:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return model?.smodels?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageSeletedCollectionCell.identifiers, for: indexPath) as! ImageSeletedCollectionCell
        
        // 显示保留按钮或者最佳匹配结果按钮
        cell.allKeepButton.isHidden = indexPath.item != 0 || self.type == .duplicates
        cell.bestResultButton.isHidden = indexPath.item != 0 || self.type == .duplicates
        cell.model = model?.smodels?[indexPath.row]
        cell.photsFileType = model?.type
        cell.keepAllCallBack = {
            //存到保留列表
            saveAllDataToKeepList()
            self.saveKeepListFinishedCallback(indexPath)
        }
        // 存全部数据到保留列表
        func saveAllDataToKeepList(){
            let uniqueId = UUID().uuidString
            if let tempModel = self.model?.smodels {
                for item in tempModel {
                    if let assetModel = item.id {
                        let success = GroupDatabase.shared.insert(localIdentifier: assetModel.localIdentifier, assetSize: assetModel.assetSize, createDate: assetModel.createDate, mediaType: self.type == .SimilarVideos ? 2 : 1  , groupId: uniqueId)
                        if success == false {
                            Print("存入当前数据到保留列表失败")
                        }
                    }
                }
            }
        }
        
        cell.callBack = {[weak self] _ in
            
            guard let self else {return}
            vibrate()
            self.checkSeletedAll()
            
            self.callBack("changgeSeleted")
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        // 计算 cell 宽度
        /*return CGSize(width:collectionView.height, height: collectionView.height) */ // 宽高相等，形成网格
        
        return CGSize(width:collectionView.height, height: collectionView.height)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 10  // 设置列间距
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // 点击之后跳转详情页面
        let vc = PMShowImgVideoController()
        if model?.type == .SimilarVideos || model?.type == .videos {
            vc.state = .similarVideos
        }else if model?.type == .duplicates {
            vc.state = .duplicates
        }else{
            vc.state = .similarPhotos
        }
        vc.oldPageIndexPath = indexPath
        vc.currentIdx = indexPath.row
        vc.homeDataSource = self.model?.smodels
        self.responderViewController()?.navigationController?.pushViewController(vc, animated: true)
        vc.backOrgPageCallBack = {[weak self]index,data in
            guard let self else {return}
            self.model?.smodels = data
            DispatchQueue.main.async{
                if let view = self.collectionView{
                    UIView.transition(with: view, duration: 0.3, options: .transitionCrossDissolve, animations: {
                        view.reloadData()
                    }, completion: nil)
                }
                
            }
        }
    }
}


struct HomeInfoTableViewModel {
    
    var ids:[String]?
    var height:CGFloat?
}


