//
//  HomeView.swift
//  PhoneManager
//
//  Created by edy on 2025/3/21.
//

import UIKit
import SnapKit

class HomeView:UIView {
    
    private var homeTabbarView:HomeTabbarView?
    private var settingBtn:UIButton!
    
    private var homeNavView:HomeNavView?
    
    private var bottomView:UIView?
    
    var homeHeader : HomeCollectionViewHeader?
    
    var dupHeadCell : HomeTitleCollectionCell?
    
    var similarHeadCell : HomeTitleCollectionCell?
    
    var titleCallBack:(HomePhotosModel?,PhotsFileType)->Void = {model,type in}
    
    var indexCallBack:callBack<Any> = {index in }
    
    var otherItemCallBack : (HomePhotosModel,Int)->Void = {data,otherCellRow in}
    
  //  var model:PhotosManagerModel?
    
   // var viewModel:HomeviewModel

    var viewModel = HomeViewModel.shared
    
    var attribet:NSAttributedString?
    
    lazy var collectionView:UICollectionView = {
        
        let cY:CGFloat = 16.RW()
        
        let layout = WaterfallMutiSectionFlowLayout()
        layout.delegate = self
        let sview:UICollectionView = UICollectionView.init(frame: CGRect(x: marginLR, y: cY, width: width - 2 * marginLR, height: height - cY),  collectionViewLayout: layout)
        
        sview.dataSource = self
        sview.delegate = self
        sview.showsVerticalScrollIndicator = false
        
        sview.register(HomeTitleCollectionCell.classForCoder(), forCellWithReuseIdentifier:"HomeTitleCollectionCell0")
        sview.register(HomeTitleCollectionCell.classForCoder(), forCellWithReuseIdentifier:"HomeTitleCollectionCell1")
        sview.register(HomeOtherCollectionCell.classForCoder(), forCellWithReuseIdentifier:HomeOtherCollectionCell.identifier)
        sview.register(HomeVideoCoverCell.classForCoder(), forCellWithReuseIdentifier: "HomeVideoCoverCell")
        sview.register(HomeCollectionViewHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HomeCollectionViewHeader")
        sview.register(UICollectionReusableView.self,forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter,withReuseIdentifier: "HomeCollectionViewFooter")
        
        if #available(iOS 11.0, *) {
            sview.contentInsetAdjustmentBehavior = .never
        }
        sview.clipsToBounds = true
        sview.backgroundColor = .clear
        return sview
        
    }()
    
    private lazy var topNaviView: UIView = {
        let backView = UIView()
        backView.backgroundColor = UIColor(hex: "#DAEAFF")
        addSubview(backView)
        return backView
    }()
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setupUI()
        
        viewModel.setupBindings()
        collectionView.reloadData()
        viewModel.homeDataChanged = {[weak self] section,row,needReloadAll in
            guard let weakSelf = self else { return }
            DispatchQueue.main.async {
                if needReloadAll{
                    weakSelf.collectionView.reloadData()
                }else{
                    if let cell = weakSelf.collectionView.cellForItem(at: IndexPath(row: row, section: section)) as? HomeTitleCollectionCell {
                        // 只更新需要改变的内容
                        let model = weakSelf.viewModel.headerGroup[row]
                        cell.reloadUIWithModel(model: model)
                    }
                    if let cell = weakSelf.collectionView.cellForItem(at: IndexPath(row: row, section: section)) as? HomeOtherCollectionCell {
                        // 只更新需要改变的内容
                        let model = weakSelf.viewModel.cardGroup[row]
                        cell.reloadUIWithModel(model: model)
                    }
                }
                weakSelf.homeHeader?.progressBar.chaoticProgress = CGFloat(weakSelf.viewModel.totalSize)
                weakSelf.reloadHeadSize()
            }
        }
        
        NotificationCenter.default.addObserver(forName: Notification.Name("applicationDidBecomeActive"), object: nil, queue: nil) {[weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.homeHeader?.progressBar.chaoticProgress = CGFloat(weakSelf.viewModel.totalSize)
            weakSelf.collectionView.reloadData()
        }
    }
    
    func reloadHeadSize(){
        self.attribet = setFileAndCount(count: viewModel.totalFilesCount, fileSize: Double(viewModel.totalSize))
        tipLabel.attributedText = attribet
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = .clear
        clipsToBounds = true
        
        homeTabbarView = HomeTabbarView(frame: CGRect(x: 0, y: 0, width: self.width, height: safeHeight + 80))
        
        self.addSubview(homeTabbarView!)
        
        homeTabbarView?.snp.makeConstraints({ make in
            
            make.centerX.width.equalToSuperview()
            make.height.equalTo(80-12)
            make.bottom.equalToSuperview().offset(-(cWindow?.safeAreaInsets.bottom ?? 10))
        })
        
        homeTabbarView?.indexCallBack = {[weak self] index in
            
            guard let self else {return}
            
            self.indexCallBack(index)
        }
        
        homeNavView = HomeNavView(frame: CGRect(x: 0, y: 0, width: width, height: statusBarHeight + 44))
        
        topNaviView.snp.makeConstraints { make in
            make.top.centerX.width.equalToSuperview()
            make.height.equalTo(44)
        }
        
        self.addSubview(homeNavView!)
        
        homeNavView?.snp.makeConstraints({ make in
            make.top.centerX.width.equalToSuperview()
            make.height.equalTo(44)
        })
        
        self.settingBtn = UIButton()
        self.settingBtn.setImage(UIImage(named: "ic_setting_com"), for: .normal)
        self.settingBtn.addTarget(self, action: #selector(settingBtnClick), for: .touchUpInside)
        self.addSubview(settingBtn)
        self.settingBtn.snp.makeConstraints { make in
            make.centerY.equalTo(self.homeNavView!.snp.centerY)
            make.right.equalTo(-marginLR)
            make.width.height.equalTo(iconWH)

        }
        
        bottomView = UIView(frame: CGRect(x: 0, y: 0, width: width, height: safeHeight + 10))
        bottomView?.backgroundColor = .clear
        
        self.addSubview(bottomView!)
        bottomView?.snp.makeConstraints({ make in
            make.centerX.width.equalToSuperview()
            make.bottom.equalToSuperview().offset(10)
            make.height.equalTo(safeHeight + 10)
        })
        self.insertSubview(collectionView, at: 0)
        collectionView.snp.makeConstraints { make in
            make.top.centerX.equalToSuperview()
            make.width.equalToSuperview().offset(-2 * marginLR)
            make.bottom.equalTo(homeTabbarView!.snp.top)//.offset( -homeTabbarView!.height - 16)
        }
        
        self.addSubview(self.tipLabel)
        self.tipLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(8+marginLR)
            make.top.equalTo(self.collectionView.snp.top).offset(44)
            make.height.equalTo(17)
        }
    }
    
    func etCell(indexPath: IndexPath) -> UICollectionViewCell {
        
        return UICollectionViewCell()
    }
    
    private lazy var tipLabel:UILabel = {
        let label = UILabel()
        label.numberOfLines = 0 // 支持多行
        label.attributedText = setFileAndCount(count:0, fileSize:0)
        return label
    }()
    
}

extension HomeView:WaterfallMutiSectionDelegate,UICollectionViewDataSource,UICollectionViewDelegate {
    

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let offsetY = scrollView.contentOffset.y
        var changeY = offsetY
        if changeY < 0 {
            changeY = 0
        }
        var cframe = self.homeNavView?.frame
        cframe?.origin.y = -changeY
        self.homeNavView?.frame = cframe ?? CGRect()
        
        var centerY = 22 + iconWH - offsetY
        let setCenterY = settingBtn.center.y
        if centerY < setCenterY {
            centerY = setCenterY
        }
        tipLabel.centerY = centerY
    }

    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        return 2
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        switch section {
        case 0:
            return viewModel.headerGroup.count// model?.titleModelArray.count ?? 0
        case 1:
            
            return viewModel.cardGroup.count//model?.otherModelArray.count ?? 0
            
        default:
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        let section = indexPath.section
        
        switch section {
        case 0:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier:"HomeTitleCollectionCell\(indexPath.row)", for: indexPath) as! HomeTitleCollectionCell
            let model = viewModel.headerGroup[indexPath.row]
            cell.reloadUIWithModel(model: model)
            cell.reloadCoverData(viewModel.coverAssets[indexPath.row])
            cell.homeTititlAction = {[weak self] idx in
                guard let self = self else { return }
                if indexPath.row == 0 {
                    self.titleCallBack(model,.duplicates)
                }else{
                    self.titleCallBack(model,.similar)
                }
            }
            
            if cell.model?.assets.count ?? 0 > 0 {
                cell.fileLabel?.isHidden = false
            }else{
                cell.fileLabel?.isHidden = true
            }
            
            return cell
        case 1:
            if viewModel.cardGroup[indexPath.row].folderName == HomeUIEnum.SimilarVideos.title ||  viewModel.cardGroup[indexPath.row].folderName ==  HomeUIEnum.Videos.title{
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeVideoCoverCell", for: indexPath) as! HomeVideoCoverCell
               let model = viewModel.cardGroup[indexPath.row]
                cell.reloadUIWithModel(model: model)
                return cell
            }else{
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeOtherCollectionCell.identifier, for: indexPath) as! HomeOtherCollectionCell
                cell.dealMediaType(indexPath.row)
               let model = viewModel.cardGroup[indexPath.row]
                cell.reloadUIWithModel(model: model)
                return cell
            }
   
        default:
            return UICollectionViewCell()
        }
        
    }
    
    func heightForRowAtIndexPath(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, indexPath: IndexPath, itemWidth: CGFloat) -> CGFloat {
        
        if indexPath.section == 0 {
            
            let model = viewModel.headerGroup[indexPath.row] //model?.titleModelArray[indexPath.row]
            if model.assets.count > 0 {
                return (model.assets.first?.count ?? 0) > 2 ? ((collection.width - marginLR - 20) / 2.2) + 50 :  ((collection.width - 2 * marginLR - 4) / 2.0) + 50
                
            }else{
               return 40
            }
            
            
        }else {
            let model = viewModel.cardGroup[indexPath.row]  //model?.otherModelArray[indexPath.row]
            return itemWidth + 12 + UILabel.getSizeWith(font: UIFont.systemFont(ofSize: 16, weight: .bold),lineSpacing: 5, width: itemWidth - 32, numberOfLines: 0, content: model.folderName).height
        }
    }
    
    func columnNumber(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> Int {
        
        switch section {
        case 0:
            return 1
        case 1:
            return 2
            
        default:
            return 0
        }
    }
    
    func lineSpacing(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGFloat {
        
        return 8
    }
    
    func interitemSpacing(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGFloat {
        
        switch section {
    
        case 1:
            return 5
            
        default:
            return 0
        }
    }
    func spacingWithLastSection(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGFloat {
        
        switch section {
    
        case 1:
            return 8
            
        default:
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
       
        if (indexPath.section == 0) {
            let smodel = viewModel.headerGroup[indexPath.row]  //model?.titleModelArray[indexPath.row]
            if indexPath.row == 0 {
                titleCallBack(smodel,.duplicates)
            }else{
                titleCallBack(smodel,.similar)
            }
           
        }else{
            //guard let smodel = viewModel.cardGroup[indexPath.row] else {  return } //model?.otherModelArray[indexPath.row]
            let smodel = viewModel.cardGroup[indexPath.row]
            otherItemCallBack(smodel,indexPath.row)
        }
    }
    
    // 返回头部视图
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HomeCollectionViewHeader", for: indexPath) as! HomeCollectionViewHeader
            if indexPath.section == 0{
                // 取第 0 个header
                self.homeHeader = header
                print("Header view cached: \(self.homeHeader != nil)")
            }
            header.cleanNowButtonCallback = {[weak self] in
                guard let self = self else {return}
                let smodel =  self.viewModel.headerGroup[0]
                let vc = HomeInfoViewController(ids: smodel.assets , type: .duplicates,titleText: smodel.folderName)
                self.responderViewController()?.navigationController?.pushViewController(vc, animated: true)
            }
            if indexPath.section != 0 {
                header.isHidden = true
            }else{
                header.isHidden = false
            }
            
            return header
        } else if kind == UICollectionView.elementKindSectionFooter {
            let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HomeCollectionViewFooter", for: indexPath)
            return footer
        }
        return UICollectionReusableView(frame: .zero)
    }
    
    // 设置头部视图的大小
    func referenceSizeForHeader(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGSize {
        if section == 0 {
            if PhotoManager.shared.permissionStatus == .denied{
                return CGSize(width:ScreenW-(marginLR*2), height: 450)
            }else{
                return CGSize(width:ScreenW-(marginLR*2), height: 76 + (self.homeNavView?.height ?? 0))
            }
        }
        return CGSize.zero
    }
    
    func referenceSizeForFooter(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGSize {
        if section == 0 {
            return CGSize(width: ScreenW, height: 0)
        }
        return CGSize(width: ScreenW, height: 20)
    }
    
    func getOuterCollectionViewHeader() -> UICollectionReusableView? {
        let indexPath = IndexPath(item: 0, section: 0)
        return self.collectionView.supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader, at: indexPath)
    }
    
    
    @objc private func settingBtnClick() {
        let homeNavViewModel = HomeNavViewModel()
        let settingViewController = SettingViewController()
        homeNavViewModel.pushToDetailController(currentView: self, destnationController: settingViewController)
    }
    
}


extension HomeView{
    
    func setFileAndCount(count:Int,fileSize:Double) -> NSMutableAttributedString {
        
        let countString = "\(count)"
        let fileSizeString = formatFileSize(fileSize)
        
        let text = countString + " files · " + fileSizeString + " of storage to clean up"
        let attributedText = NSMutableAttributedString(string: text)
        
        // 设置整体文本样式
        let fullTextAttributes: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: 14, weight: .regular),
            .foregroundColor: UIColor(red: 0.4, green: 0.4, blue: 0.4,alpha:1)
        ]
        attributedText.addAttributes(fullTextAttributes, range: NSRange(location: 0, length: text.count))
        
        // 设置 "202" 为蓝色
        if let range1 = text.range(of: countString) {
            let nsRange1 = NSRange(range1, in: text)
            attributedText.addAttributes([
                .foregroundColor: UIColor.colorWithHex(hexStr: mColor),
                .font:UIFont.systemFont(ofSize: 14, weight: .regular)
            ], range: nsRange1)
        }
        
        // 设置 "1.15 GB" 为蓝色
        if let range2 = text.range(of: fileSizeString) {
            let nsRange2 = NSRange(range2, in: text)
            attributedText.addAttributes([
                .font:UIFont.systemFont(ofSize: 14, weight: .regular),
                .foregroundColor: UIColor.colorWithHex(hexStr: mColor)
            ], range: nsRange2)
        }
        return attributedText
        // 将 attributedText 赋值给 UILabel
//        self.tipLabel.attributedText = attributedText
    }
}
