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

import UIKit

class MaintaiDetailTableViewCell: UITableViewCell {

    @IBOutlet weak var mainCollectionView: UICollectionView!
    @IBOutlet weak var pageCollectionView: UICollectionView!
    
    var selectAsset:[AssetModel] = []
    
    var selectCallBack:(([AssetModel]) ->Void)?
    
    enum draggViewEnum{
        case big,small,null
    }
    
    let smallW:CGFloat = 54.RW()
    let bigW:CGFloat = ScreenW-44
    
    var draggView:draggViewEnum = .null
    
    override func awakeFromNib() {
        super.awakeFromNib()
        configMain()
        configChild()

    }
    
    var source:[AssetModel] = []{
        didSet{
            mainCollectionView.reloadData()
            pageCollectionView.reloadData()
        }
    }
    
    func configMain(){
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: bigW, height: bigW)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
       // layout.sectionInset = UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 12)
        
        mainCollectionView.setCollectionViewLayout(layout, animated: false)
        mainCollectionView.dataSource = self
        mainCollectionView.delegate = self
        mainCollectionView.isPagingEnabled = true
        mainCollectionView.register(UINib(nibName: "MaintaiDetailImageCell", bundle: nil), forCellWithReuseIdentifier: "MaintaiDetailImageCell")
    }
    
    func configChild(){
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: smallW, height: smallW)
        layout.minimumLineSpacing = 12
        layout.minimumInteritemSpacing = 12
        layout.sectionInset = UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 12)
        layout.scrollDirection = .horizontal
        
        pageCollectionView.setCollectionViewLayout(layout, animated: false)
        pageCollectionView.dataSource = self
        pageCollectionView.delegate = self
        let inset = (ScreenW - 32-24) - smallW
        pageCollectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: inset)
        
        pageCollectionView.backgroundColor = UIColor(hex: "#E2EEFF")
        pageCollectionView.layer.cornerRadius = 8
        pageCollectionView.register(UINib(nibName: "MaintaiDetailImageSmallCell", bundle: nil), forCellWithReuseIdentifier: "MaintaiDetailImageSmallCell")
        
    }
    
    deinit{
        Print("释放图像cell",self)
    }
    
}

extension MaintaiDetailTableViewCell:UICollectionViewDelegate,UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return source.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == mainCollectionView{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MaintaiDetailImageCell", for: indexPath) as! MaintaiDetailImageCell
            cell.model = source[indexPath.row]
            cell.selectBtn.isSelected = selectAsset.contains(source[indexPath.row])
            cell.selectChangeBlock = {[weak self] in
                guard let weakSelf = self else { return }
                weakSelf.dealSelect(model: weakSelf.source[indexPath.row])
            }
            return cell
        }
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MaintaiDetailImageSmallCell", for: indexPath) as! MaintaiDetailImageSmallCell
        cell.model = source[indexPath.row]
        cell.selectBtn.isSelected = selectAsset.contains(source[indexPath.row])
//        cell.selectChangeBlock = {[weak self] in
//            guard let weakSelf = self else { return }
//            weakSelf.dealSelect(model: weakSelf.source[indexPath.row])
//        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        if collectionView == pageCollectionView{
            dealSelect(model: source[indexPath.row])
        }
    }
    
    
    func dealSelect(model:AssetModel){

        if let index = selectAsset.firstIndex(where: {
            $0 == model
        }) {
            // 包含：移除元素
            selectAsset.remove(at: index)
        } else {
            // 不包含：添加元素
            selectAsset.append(model)
        }
        
        mainCollectionView.reloadData()
        pageCollectionView.reloadData()
        
        selectCallBack?(selectAsset)
    }

    
}

extension MaintaiDetailTableViewCell:UIScrollViewDelegate{
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        Print("滑动距离",scrollView.contentOffset.x)
        
        if scrollView == mainCollectionView,draggView == .big{
            // 拖动主图结束
            Print("主图滑动距离",scrollView.contentOffset.x)
            let index = Int(scrollView.contentOffset.x/bigW)
            Print("小图滑动到下标\(index)")
            let space:CGFloat = (self.smallW + 12) * CGFloat(index)
            UIView.animate(withDuration: 0.3) {
                self.pageCollectionView.contentOffset = CGPoint(x:space + 2, y: 0)
            }
        }
    }

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        if scrollView == mainCollectionView{
            print("----开始拖拽----大图")
            draggView = .big
        }else{
            print("----开始拖拽----小图")
            draggView = .small
        }
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        print("----结束拖拽----")
        if !decelerate{
            if scrollView == pageCollectionView,draggView == .small{
                setPageOffetX(offsetX: scrollView.contentOffset.x)
            }
        }
    }
    

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if !scrollView.isDecelerating,!scrollView.isDragging,!scrollView.isTracking {
            if scrollView == pageCollectionView,draggView == .small{
                setPageOffetX(offsetX: scrollView.contentOffset.x)
            }
        }
    }
    
//    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
//        if scrollView == mainCollectionView{
//            let currentOffset = targetContentOffset.pointee.x
//            let page = round(currentOffset / bigW) // 计算目标页（以 Cell 宽度为基准）
//            targetContentOffset.pointee.x = page * bigW // 强制对齐到 Cell 边界
//            Print("强制对齐",targetContentOffset.pointee.x )
//        }
//      }
    
    func setPageOffetX(offsetX:CGFloat){
        print("----结束滑动----小图")
        Print("小图滑动距离",offsetX)
        let index = Int((offsetX/(smallW+12)).rounded()) //Int(offsetX/(smallW+12).rounded()) //rounded(offsetX/smallW)
        Print("大图滑动到下标\(index)")
        let space:CGFloat = (self.smallW + 12) * CGFloat(index)
        UIView.animate(withDuration: 0.3) {
            self.pageCollectionView.contentOffset = CGPoint(x: space + 2, y: 0)
        }
        self.mainCollectionView.contentOffset = CGPoint(x: index * Int(self.bigW), y: 0)
        draggView = .null
    }
    

}
