//
//  TrashContenView.swift
//  PhoneManager
//
//  Created by edy on 2025/5/11.
//

import UIKit

class TrashContenView: UIView {
    
    var collectionView: UICollectionView!
    
    var mediaType : TrashTypeEnum?
    
    var defaultView : TrashDefaultView = {
        let view = TrashDefaultView()
        return view
    }()
    
    var typeLabel:UILabel!
    var sizeLabel:UILabel!
    
    var lineOne: UIView!
//    var lineTwo: UIView!
//    var lineThree: UIView!
//    var lineFour: UIView!
    
    var deleteButton : UIButton?
    
//    var scrollLine:UIView!
    let lineW:CGFloat = (ScreenW - 62) / 3.0
    
    var dataSource:[AssetModel] = [] {
        didSet{
            self.resetContenViewUI()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        configUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func getData(){
        collectionView.reloadData()
    }
    
    private lazy var stack: UIStackView = {
        let st = UIStackView()
        st.alignment = .fill
        st.Radius = 12
        st.backgroundColor = UIColor.colorWithHex(hexStr: "#F2F6FC")
        st.distribution = .fillEqually
        self.addSubview(st)
        return st
    }()
    
    /// 当数据为空的时候显示默认页面
    func setDefauleUI(){
        self.collectionView.removeFromSuperview()
        self.defaultView.mediaType = self.mediaType
        self.addSubview(self.defaultView)
        self.defaultView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(stack.snp.bottom)
        }
    }
    
    var callback:((Int)->Void) = {idx in}
    
    @objc func touch(_ sender:UIButton) -> Void {
        callback(sender.tag)
    }
    
    
    var buttonTL : [String] = ["Video" , "Other" , "Screenshot"]
    
    func configUI(){
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 12
        layout.minimumLineSpacing = 12
        layout.sectionInset = UIEdgeInsets(top: 20, left: 16, bottom: 0, right: 16)
        layout.itemSize = CGSize(width: Int((ScreenW-56)/3), height: Int((ScreenW-56)/3))
        collectionView = UICollectionView.init(frame: CGRect.zero,collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.backgroundColor = UIColor.colorWithHex(hexStr: "#F2F6FC")
        collectionView.dataSource = self
        collectionView.register(UINib(nibName: "TrashContenAssetCell", bundle: nil), forCellWithReuseIdentifier: "TrashContenAssetCell")
        addSubview(collectionView)
        
        
        let topView = UIView()
        topView.backgroundColor = .white
        addSubview(topView)
        
        topView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(82)
        }
        
        typeLabel = UILabel()
        typeLabel.text = "Trash Can · Video"
        typeLabel.textColor = .black
        typeLabel.font = UIFont.systemFont(ofSize: 20, weight: .medium)
        topView.addSubview(typeLabel)
        
        sizeLabel = UILabel()
        sizeLabel.text = "1 video · 156.9MB"
        sizeLabel.textColor = UIColor.colorWithHex(hexStr: "#666666")
        sizeLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        topView.addSubview(sizeLabel)
        
        
        typeLabel.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(0)
        }
        
        sizeLabel.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(30)
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(stack.snp.bottom).offset(20)
        }
        
        lineOne = UIView()
        lineOne.backgroundColor = UIColor.colorWithHex(hexStr: "#E5E5E5")
        topView.addSubview(lineOne)
        lineOne.isHidden = true
        stack.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(marginLR)
            make.top.equalTo(sizeLabel.snp.bottom).offset(14)
            make.height.equalTo(42)
        }
//        lineTwo = UIView()
//        lineTwo.backgroundColor = UIColor.colorWithHex(hexStr: "#E5E5E5")
//        topView.addSubview(lineTwo)
//        
//        lineThree = UIView()
//        lineThree.backgroundColor = UIColor.colorWithHex(hexStr: "#E5E5E5")
//        topView.addSubview(lineThree)
//        
//        lineOne.frame = CGRect(x: 16, y: 62, width: lineW, height: 6)
//        lineTwo.frame = CGRect(x: 10+lineOne.rightX, y: 62, width: lineW, height: 6)
//        lineThree.frame = CGRect(x: 10+lineTwo.rightX, y: 62, width: lineW, height: 6)
        
//        scrollLine = UIView()
//        scrollLine.backgroundColor = UIColor.colorWithHex(hexStr: "#0082FF")
//        scrollLine.frame = lineOne.frame
//        topView.addSubview(scrollLine)
        var i = 0
        for tl in buttonTL {
            let b = UIButton(type: .custom)
            b.setTitle(tl, for: .normal)
            b.setTitleColor(UIColor.colorWithHex(hexStr: "#111111"), for: .normal)
            b.setTitleColor(UIColor.white, for: .selected)
            b.setBackgroundImage(UIColor.clear.generateImage() ?? UIImage(), for: .normal)
            b.setBackgroundImage(UIColor.colorWithHex(hexStr: "#0082FF").generateImage(), for: .selected)
            b.tag = i
            b.addTarget(self, action: #selector(touch(_:)), for: .touchUpInside)
            stack.addArrangedSubview(b)
            b.Radius = 12
            i += 1
        }
        
        NotificationCenter.default.addObserver(forName: .trashPageScroll, object: nil, queue: nil) {[weak self] notif in
            guard let weakSelf = self else { return }
            guard let model = notif.object as? TrashPageScrollModel else{
                return
            }
            let offset = model.offset
            let page = model.page
            switch weakSelf.trashType {
            case .video:
                break
//                if page == 1{
//                    if offset > 0{
//                        UIView.animate(withDuration: 0.2) {
//                            weakSelf.scrollLine.frame = weakSelf.lineTwo.frame
//                        }
//                    }else{
//                        UIView.animate(withDuration: 0.2) {
//                            weakSelf.scrollLine.frame = weakSelf.lineOne.frame
//                        }
//                    }
//                }else{
//                    weakSelf.scrollLine.frame = weakSelf.lineOne.frame
//                }
                
            case .other:
                break
//                if page == 2{
//                    if offset > ScreenW{
//                        UIView.animate(withDuration: 0.2) {
//                            weakSelf.scrollLine.frame = weakSelf.lineThree.frame
//                        }
//                    }
//                    else if offset == ScreenW{
//                        UIView.animate(withDuration: 0.2) {
//                            weakSelf.scrollLine.frame = weakSelf.lineTwo.frame
//                        }
//                    }
//                    else{
//                        UIView.animate(withDuration: 0.2) {
//                            weakSelf.scrollLine.frame = weakSelf.lineOne.frame
//                        }
//                    }
//                }else{
//                    weakSelf.scrollLine.frame = weakSelf.lineTwo.frame
//                }
                
                
            case .shot:
                break
//                if page == 3{
//                    if offset > ScreenW * 2{
//                        UIView.animate(withDuration: 0.2) {
//                            weakSelf.scrollLine.frame = weakSelf.lineFour.frame
//                        }
//                    }
//                    else if offset == ScreenW * 2{
//                        UIView.animate(withDuration: 0.2) {
//                            weakSelf.scrollLine.frame = weakSelf.lineThree.frame
//                        }
//                    }
//                    else{
//                        UIView.animate(withDuration: 0.2) {
//                            weakSelf.scrollLine.frame = weakSelf.lineTwo.frame
//                        }
//                    }
//                }else{
//                    weakSelf.scrollLine.frame = weakSelf.lineThree.frame
//                }
            }
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
//        scrollLine.cornerCut(radius: 2, corner: .allCorners)
//        lineOne.cornerCut(radius: 2, corner: .allCorners)
//        lineTwo.cornerCut(radius: 2, corner: .allCorners)
//        lineThree.cornerCut(radius: 2, corner: .allCorners)
    }
    
    var trashType:TrashTypeEnum = .video{
        didSet{
            
//            DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
//                if self.trashType == .video {
//                    b.isSelected = true
//                }else if self.trashType == .other {
//                    b.isSelected = true
//                }else{
//                    b.isSelected = true
//                }
//            }
            
            
            switch trashType {
            case .video:
                for b in stack.subviews {
                    guard let btn:UIButton = b as? UIButton else { return }
                    if b.tag == 0 {
                        btn.isSelected = true
                    }else{
                        btn.isSelected = false
                    }
                }
                break
            case .other:
                for b in stack.subviews {
                    guard let btn:UIButton = b as? UIButton else { return }
                    if b.tag == 1 {
                        btn.isSelected = true
                    }else{
                        btn.isSelected = false
                    }
                }
                break
            case .shot:
                for b in stack.subviews {
                    guard let btn:UIButton = b as? UIButton else { return }
                    if b.tag == 2 {
                        btn.isSelected = true
                    }else{
                        btn.isSelected = false
                    }
                }
                break
            }
            getData()
        }
    }
}


extension TrashContenView:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int{
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TrashContenAssetCell", for: indexPath) as! TrashContenAssetCell
        // 设置image
        cell.mediaType = self.trashType
        cell.model = self.dataSource[indexPath.item]
        
        cell.revokeCallBack = {
            // 重新设置数据源
            self.dataSource = TrashDataManager.getCurrentMediaTypeTrashData(mediaType: self.mediaType)
        }
        return cell
    }
    
    

    /// 重新刷新页面UI
    private func resetContenViewUI(){
        DispatchQueue.main.async {
            // 设置数量
            if self.trashType == .video{
                self.sizeLabel.text = "\(self.dataSource.count) \(self.getUnits()) · \(self.getDataSize(array: self.dataSource))"
            }else{
                self.sizeLabel.text = "\(self.dataSource.count) \(self.getUnits()) · \(self.getDataSize(array: self.dataSource))"
            }
            // 设置标题
            self.typeLabel.text = "Trash Can · \(self.trashType.rawValue)"
            
            // 设置button的文字和样式
            self.setDeleteButtonUI()
            self.deleteButton?.isHidden = !(self.dataSource.count > 0)
            if self.dataSource.count > 0 {
                self.collectionView.reloadData()
            }else {
                self.setDefauleUI()
            }
        }
    }
    /// 获取资源总大小
    /// - Parameter array: 资源数组
    /// - Returns: 格式化后的总大小
    func getDataSize(array : [AssetModel]) -> String{
        var size : Double = 0.0
        for item in array {
            size = size + item.assetSize
        }
        return formatFileSize(size)
    }
    
    private func setDeleteButtonUI(){
        if let deleteButton = self.deleteButton {
            if self.dataSource.count <= 0{
                deleteButton.setTitle("Delete", for: .normal)
                deleteButton.backgroundColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
                return
            }
            deleteButton.backgroundColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 1)
            if self.trashType == .video{
                deleteButton.setTitle("Delete \(self.dataSource.count) \(self.getUnits())", for: .normal)
            }else {
                deleteButton.setTitle("Delete \(self.dataSource.count) \(self.getUnits())", for: .normal)
            }
        }
    }
    
    // 获取单位复数
    private func getUnits()->String{
        if self.dataSource.count > 1 {
            return self.trashType == .video ? "videos" : "photos"
        }else {
            return self.trashType == .video ? "video" : "photo"
        }
    }
    
}
