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

import UIKit

class HomeInfoView :UIView {
    
    var ids:[[AssetModel]]?
    
    var titleText : String?
    
    var isDragEnd : Bool = false
    
    var type : PhotsFileType?
    
    var models:[HomeInfoTableItem] = []
    
    var callBack:callBack<Any> = {text in}
    
    var keepAllNoDataCallBack : ()->Void = {}
    
    var deleteCallBack:callBack<[AssetModel]> = {array in }
    var titleShowHideCallBack:callBack<Bool> = {isShow in}
    
    lazy var tableView:UITableView = {
        
        let sview:UITableView = UITableView(frame: bounds, style: .grouped) //UITableView.init(frame: bounds )
        sview.backgroundColor = .clear
        sview.separatorStyle = .none
        sview.showsVerticalScrollIndicator = false
        sview.delegate = self
        sview.dataSource = self
        sview.register(HomeInfoTableViewCell.self, forCellReuseIdentifier: HomeInfoTableViewCell.identifier)
        sview.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        if #available(iOS 15.0, *) {
            
            sview.sectionHeaderTopPadding = 0
        }
        return sview
    }()
    
    lazy var headerView:HomeInfoTitleView = {
        let sview:HomeInfoTitleView = HomeInfoTitleView(frame: CGRect(x: 0, y: 0, width: width, height: 84))
        sview.titleLabel.text = self.titleText
        sview.type = self.type
        sview.filterButton.isHidden = (self.type != .similar && self.type != .SimilarVideos || (ids?.count ?? 0 <= 0))
        sview.numberLabel.isHidden = (ids?.count ?? 0 <= 0)
        return sview
    }()
    
    lazy var nextRowButton : UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "Frame_1171276289"), for: .normal)
        button.backgroundColor = .clear
        button.addTarget(self, action: #selector(nextRowButtonAction), for: .touchUpInside)
        return button
    }()
    
    lazy var deleteView:HomeInfoDeleteView = {
        
        let cH:CGFloat = 45 + 2 * marginLR + safeHeight
        
        let sview:HomeInfoDeleteView = HomeInfoDeleteView(frame: CGRect(x: 0, y: height - cH, width: width, height: cH))
        
        sview.callBack = {[weak self] status in
            
            guard let self else {return}
            
            if let operstatus = status as? OperStatus {
                
                switch operstatus {
                case .delete:
                    self.deleteCallBack(getSelectedArray())
                default:
                    break
                }
            }
        }
        
        return sview
    }()
    
    init(frame: CGRect,ids:[[AssetModel]]?,type:PhotsFileType?,titleText:String?) {
        
        self.ids = ids
        self.titleText = titleText
        self.type = type
        super.init(frame: frame)
        for array in ids ?? [] {
            
            var smodels:[ImageSeletedCollectionItem] = []
            
            for id in array {
                
                let smodel = ImageSeletedCollectionItem()
                
                smodel.id = id
                smodel.isSeleted = false
                
                smodels.append(smodel)
            }
            
            let smodel = HomeInfoTableItem()
            smodel.type = type
            smodel.smodels = smodels
            smodel.titleText = titleText
            
            models.append(smodel)
        }
        self.ids = sortData(source: ids ?? [], type: .latest)
        
        setupUI()
        
        
        self.headerView.sortViewSubmitCallBack = {[weak self] filterModel in
            PhotoManager.shared.reloadTrashAndKeep()
            guard let self else {return}
            var dataS : [[AssetModel]] = []
            if self.type == .SimilarVideos{
                dataS = PhotoManager.shared.filterSimilarVideoModels
            }else {
                dataS = PhotoManager.shared.filterSimilarModels
            }
            let tempData =  self.filterDataByDate(orgModels: dataS  , startDate: filterModel.startDate, endDate: filterModel.endDate)
            // 重新更新下数据源
            self.ids = self.sortData(source: tempData, type: filterModel.sortType)
            var tempModels : [HomeInfoTableItem] = []
            for array in self.ids ?? [] {
                var smodels:[ImageSeletedCollectionItem] = []
                for id in array {
                    let smodel = ImageSeletedCollectionItem()
                    smodel.id = id
                    smodel.isSeleted = false
                    smodels.append(smodel)
                }
                let smodel = HomeInfoTableItem()
                smodel.type = type
                smodel.smodels = smodels
                smodel.titleText = titleText
                tempModels.append(smodel)
            }
            models = tempModels
            DispatchQueue.main.async {
                self.setTitleView()
                self.tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        
        backgroundColor = .white
        
        self.setTitleView()
        
        self.addSubview(tableView)
        
        self.addSubview(deleteView)
        
        self.addSubview(self.nextRowButton)
        
        self.nextRowButton.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-safeHeight - 106)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(38)
            make.width.equalTo(24)
        }
        
        self.nextRowButton.isHidden = !self.isShowNextRowButton()
    }
    
    
    /// 是否显示下一个按钮
    /// - Returns: 是否显示
    func isShowNextRowButton() -> Bool{
        return self.ids?.count ?? 0 > 0 && (self.type == .similar || self.type == .similarScreenshots)
    }
    
    func changeValue() {
        
        var isSeleted:Bool = false
        
        for smodel in models {
            
            for smodel2 in smodel.smodels ?? [] {
                
                if (smodel2.isSeleted ?? false) {
                    
                    isSeleted = true
                }
            }
        }
        
        setTitleView()
        
        callBack(isSeleted)
    }
    
    func changeALlValue(isSeleted:Bool) {
        
        // 在这里进行数据更新
        
        for smodel in models {
            
            for (index,smodel2) in (smodel.smodels ?? []).enumerated() {
                
                if index == 0 {
                    
                    smodel2.isSeleted = false
                }else {
                    
                    smodel2.isSeleted = isSeleted
                }
            }
        }
        
        // 设置头部的统计数量
        setTitleView()
        
        for section in 0..<self.tableView.numberOfSections {
            for item in 0..<self.tableView.numberOfRows(inSection: section) {
                if let cell = self.tableView.cellForRow(at: IndexPath(row: item, section: section)) as? HomeInfoTableViewCell {
                    cell.checkSeletedAll()
                    UIView.transition(with: cell.collectionView!, duration: 0.3, options: .transitionCrossDissolve, animations: {
                        cell.collectionView?.reloadData()
                    }, completion: nil)
                }
            }
        }
    }
    
    func getSelectedArray() -> [AssetModel] {
        
        var selectedArray:[AssetModel] = []
        for smodel in models {
            for smodel2 in smodel.smodels ?? []{
                if smodel2.isSeleted ?? false {
                    selectedArray.append(smodel2.id!)
                }
            }
        }
        return selectedArray
    }
    
    func deleteModel(array:[AssetModel]) {
        
        var newModel : [HomeInfoTableItem] = []
        for i in 0..<models.count {
            // 过滤掉 isSelected 为 true 的 smodel2
            var arrayT : [ImageSeletedCollectionItem] = models[i].smodels!
            for item in array {
                arrayT = arrayT.filter { !($0.id?.localIdentifier == item.localIdentifier) }
            }
            if (arrayT.count >= 2){
                let temModel : HomeInfoTableItem = HomeInfoTableItem()
                temModel.type = models[i].type
                temModel.smodels = updateSelectToDesSelect(data: arrayT)
                temModel.titleText = models[i].titleText
                newModel.append(temModel)
            }
        }
        // 将新的数据全部改成未被选中状态
        func updateSelectToDesSelect(data:[ImageSeletedCollectionItem])->[ImageSeletedCollectionItem]{
            var dataArray : [ImageSeletedCollectionItem] = []
            for item in data {
                item.isSeleted = false
                dataArray.append(item)
            }
            return dataArray
        }
        self.models = newModel
        
        DispatchQueue.main.async {[weak self] in
            
            guard let self else {return}
            
            tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
            
            setTitleView()
        }
        
    }
    
    func setTitleView() {
        
        var number:Int = 0
        
        var seletedNumber:Int = 0
        
        for smodel in models {
            
            number += smodel.smodels?.count ?? 0
            
            for smodel2 in smodel.smodels ?? []{
                
                if smodel2.isSeleted ?? false {
                    
                    seletedNumber += 1
                }
            }
        }
        
        headerView.changeContent(title: self.type!.rawValue, allNumber: number, seletedCount: seletedNumber)
        
        deleteView.changeContent(title: self.type!.rawValue, seletedCount: seletedNumber)
        
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: deleteView.isHidden ? 12 : deleteView.height + 12 , right: 0)
        self.nextRowButton.isHidden = !self.isShowNextRowButton()
        headerView.filterButton.isHidden = (self.type != .similar && self.type != .SimilarVideos || (ids?.count ?? 0 <= 0))
        headerView.numberLabel.isHidden = (ids?.count ?? 0 <= 0)
    }
    
}

extension HomeInfoView:UITableViewDataSource,UITableViewDelegate {
    
    @objc func nextRowButtonAction(){
       
        self.tableScrollToNextRow()
    }
    
    /// 让表格自动滚动一行
    private func tableScrollToNextRow() {
        
        guard let indexPath = tableView.indexPathsForVisibleRows?.first else { return }
        
//        let nextRow =  self.isDragEnd == true ? indexPath.row + 1 : indexPath.row + 2
        let nextRow = indexPath.row + 2
        let nextSection = indexPath.section
        
        // 获取最后一个cell 看看是不是存在
        guard let lastIndexPath = tableView.indexPathsForVisibleRows?.last else {return}
        let lastNextRow = lastIndexPath.row + 1
        guard lastNextRow < tableView.numberOfRows(inSection: nextSection) else {
            // 滚动到最底部
            tableView.scrollToRow(at: lastIndexPath, at: .bottom, animated: true)
            return
        }
        
        // 检查下一行是否存在
        guard nextRow < tableView.numberOfRows(inSection: nextSection) else { return }
        
        let nextIndexPath = IndexPath(row: nextRow, section: nextSection)
        
        // 计算目标行的位置
        let targetRect = tableView.rectForRow(at: nextIndexPath)
        
        // 向上微调的偏移量（例如 20 点）
        let adjustedOffset = CGPoint(
            x: 0,
            y: targetRect.origin.y - 38 // 修改这里的数值调整微调量
        )
        
        // 直接滚动到调整后的位置
        tableView.setContentOffset(adjustedOffset, animated: true)
        self.isDragEnd = false
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let OffsetY = scrollView.contentOffset.y
        let top = CGRectGetMaxY(self.headerView.titleLabel.frame) + 8
        var orgy = OffsetY - top
        if orgy < 0 {
            orgy = 0
        }
        titleShowHideCallBack( OffsetY > top )
        var farme = self.headerView.frame
        farme.origin.y = orgy
        self.headerView.frame = farme
        tableView.bringSubviewToFront(self.headerView)
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        self.isDragEnd = true
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return models.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: HomeInfoTableViewCell.identifier, for: indexPath) as! HomeInfoTableViewCell
        cell.saveKeepListFinishedCallback = {[weak self] index in
            guard let self else {return}
            self.ids?.remove(at:indexPath.row)
            self.models.remove(at:indexPath.row)
            DispatchQueue.main.async {
                self.setTitleView()
            }
            // 禁用动画
            UIView.performWithoutAnimation {
//                tableView.beginUpdates()
//                tableView.deleteRows(at: [indexPath], with: .fade)
//                tableView.endUpdates()
                tableView.reloadData()
            }
           // tableView.reloadData()
            if let data = self.ids {
                if data.count <= 0 {
                    self.keepAllNoDataCallBack()
                }
            }
            if PMKeepListAlert.isHint == false {
                PMKeepListAlert.isHint = true
                let alert = PMKeepListAlert()
                self.responderViewController()?.view.showBlur()
                alert.show {
                    self.responderViewController()?.view.hideBlur()
                }
            }
        }
        cell.type = self.type
        
        cell.model = models[indexPath.row]
        
        cell.callBack = {[weak self] text in
            
            guard let self else {return}
            
            changeValue()
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let models = ids?[indexPath.row]
        
        return ((models?.count ?? 0) > 2 ? 205 : 229) + 8
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return headerView.height
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
        
    }
    
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        tableView.addSubview(self.headerView)
        tableView.bringSubviewToFront(self.headerView)
    }
    
    func filterDataByDate(orgModels : [[AssetModel]], startDate:Date? ,endDate : Date?)->[[AssetModel]]{
        var tempArray : [[AssetModel]] = []
        for item in orgModels {
            var array = item
            if startDate != nil {
                array = array.filter({$0.createDate >= startDate!})
            }
            if endDate != nil {
                array = array.filter({$0.createDate <= endDate!})
            }
            
            if array.count >= 2 {
                tempArray.append(item)
            }
        }
        return tempArray
    }
    
    func sortData(source: [[AssetModel]], type: ResouceSortType) -> [[AssetModel]] {
        switch type {
        case .largest:
            return source.sorted { subArray1, subArray2 in
                let sum1 = subArray1.reduce(0) { $0 + $1.assetSize }
                let sum2 = subArray2.reduce(0) { $0 + $1.assetSize }
                return sum1 > sum2
            }
            
        case .smallest:
            return source.sorted { subArray1, subArray2 in
                let sum1 = subArray1.reduce(0) { $0 + $1.assetSize }
                let sum2 = subArray2.reduce(0) { $0 + $1.assetSize }
                return sum1 < sum2
            }
            
        case .latest:
            return source.sorted { subArray1, subArray2 in
                guard let max1 = subArray1.max(by: { $0.createDate < $1.createDate })?.createDate else { return false }
                guard let max2 = subArray2.max(by: { $0.createDate < $1.createDate })?.createDate else { return true }
                return max1 > max2
            }
            
        case .oldest:
            return source.sorted { subArray1, subArray2 in
                guard let min1 = subArray1.min(by: { $0.createDate < $1.createDate })?.createDate else { return false }
                guard let min2 = subArray2.min(by: { $0.createDate < $1.createDate })?.createDate else { return true }
                return min1 < min2
            }
        }
    }
    
}

class HomeInfoTitleView:UIView {
    
    var filterBoxModel : ResourceFilterBoxModel?
    
    var sortViewSubmitCallBack : (ResourceFilterBoxModel)->Void = {model in}
    
    var type : PhotsFileType?
    
    lazy var titleLabel:UILabel = {
        
        let sview:UILabel = UILabel()
        
        sview.font = .systemFont(ofSize: 22, weight: .bold)
        sview.textColor = UIColor.colorWithHex(hexStr: black3Color)
        sview.x = 15
        sview.y = 14
        
        return sview
    }()
    
    lazy var numberLabel:UILabel = {
        
        let sview:UILabel = UILabel()
        
        sview.font = .systemFont(ofSize: 14, weight: .regular)
        sview.textColor = UIColor.colorWithHex(hexStr: black6Color)
        sview.x = 15
        sview.y = 40
        sview.width = width - 2 * marginLR
        sview.height = 20
        
        return sview
    }()
    
    // 筛选按钮
    lazy var filterButton :  UIButton =  {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "Frame 1"), for: .normal)
        button.setTitle("latest", for: .normal)
        button.layer.cornerRadius = 14
        button.clipsToBounds = true
        button.backgroundColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 0.1000)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
        button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0)
        button.setTitleColor(UIColor(red: 0.07, green: 0.07, blue: 0.07, alpha: 1), for: .normal)
        button.addTarget(self, action: #selector(filterButtonAction), for: .touchUpInside)
        button.isHidden = true
        return button
    }()
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        
        backgroundColor = .white
        addSubview(titleLabel)
        addSubview(numberLabel)
        addSubview(self.filterButton)
        
        
        self.filterButton.snp.makeConstraints { make in
            make.centerY.equalTo(self.titleLabel.snp.centerY)
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(28)
            make.width.equalTo(98)
        }
    }
    
    func changeContent(title:String,allNumber:Int,seletedCount:Int) {
        
        titleLabel.text = title
        titleLabel.sizeToFit()
        
        
        let allNumberStr = "\(allNumber)"
        let seletedCountStr = "\(seletedCount)"
        var fullText = "0 photos · 0 selected"
        if self.type == .SimilarVideos {
            fullText = allNumberStr + " videos · \(seletedCountStr) selected"
        }else {
            fullText = allNumberStr + " photos · \(seletedCountStr) selected"
        }
        
        
        let attributedString2 = NSMutableAttributedString(string: fullText, attributes: [
            .font: UIFont.systemFont(ofSize: 14,weight: .semibold),
            .foregroundColor: UIColor.colorWithHex(hexStr: "#666666")
        ])
        
        let termsRange = (fullText as NSString).range(of: allNumberStr)
        let privacyRange = (fullText as NSString).range(of: seletedCountStr)
        
        attributedString2.addAttributes([
            .foregroundColor: UIColor.colorWithHex(hexStr: "#0082FF"),
        ], range: termsRange)
        
        attributedString2.addAttributes([
            .foregroundColor: UIColor.colorWithHex(hexStr: "#0082FF"),
        ], range: privacyRange)
        
        
        numberLabel.attributedText = attributedString2
        numberLabel.y = height - numberLabel.height - 8
    }
    
    
    @objc func filterButtonAction(){
        if let cWindow = cWindow {
            let filterView : ResourceFilterBoxView = ResourceFilterBoxView.init(frame: cWindow.bounds,startDate: self.filterBoxModel?.startDate,endDate: self.filterBoxModel?.endDate,sortType: self.filterBoxModel?.sortType)
            // 添加毛玻璃效果
            cWindow.showBlur()
            
            cWindow.addSubview(filterView)
            filterView.submitCallBack = {model in
                self.filterBoxModel = model
                DispatchQueue.main.async {
                    self.filterButton.setTitle(model.sortType.rawValue, for: .normal)
                }
                self.sortViewSubmitCallBack(model)
            }
        }
    }
}


class HomeInfoDeleteView:UIView {
    
    var callBack:callBack<Any> = {text in}
    
    lazy var deleteBtn:UIButton = {
        
        let sview:UIButton = UIButton()
        
        sview.titleLabel?.font = .systemFont(ofSize: 16, weight: .semibold)
        sview.addTarget(self, action: #selector(deleteBtnClick), for: .touchUpInside)
        sview.backgroundColor = UIColor.colorWithHex(hexStr: mColor)
        sview.setImage(UIImage(named: "pm-home-Frame-del"), for: .normal)
        sview.width = width - 2 * 39
        sview.height = 45
        sview.titleEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)
        sview.centerX = width / 2
        sview.y = marginLR
        sview.layer.cornerRadius = 12
        sview.layer.masksToBounds = true
        
        return sview
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .clear
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        
//        self.setShadow()
        
        backgroundColor = .clear
        addSubview(deleteBtn)
        
    }
    
    func changeContent(title:String,seletedCount:Int) {
        
        deleteBtn.setTitle("Delete \(seletedCount) \(title)", for: .normal)
        
        self.isHidden = seletedCount > 0 ? false : true
        
    }
    
    @objc func deleteBtnClick() {
        
        callBack(OperStatus.delete)
    }
    
    
}

