//
//  YHGrabNumberInfoView.swift
//  galaxy
//
//  Created by edy on 2024/8/19.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

enum YHGrabItemViewType: Int {
    case info
    case grab
    case files
    case visit
}

class YHGrabItem {
    var type: YHGrabItemViewType = .info
    var title: String = ""
    var detail: String = ""
    var files: [String] = []
    var publicFiles: [String] = []
    var isSingleLine: Bool = true
    
    required init() {
        
    }
    
    init(type: YHGrabItemViewType, title: String, detail: String, files: [String] = [], publicFiles: [String] = [], isSingleLine: Bool = true) {
        self.type = type
        self.title = title
        self.detail = detail
        self.files = files
        self.publicFiles = publicFiles
        self.isSingleLine = isSingleLine
    }
}

class YHGrabNumberInfoItemView: UIView {
    
    let dotWidth = 4.0
    let titleMaxWidth = 112.0
    let grabNumColor = UIColor.brandMainColor
    let infoColor = UIColor.mainTextColor
    let gap = 8.0
    let fileWidth = floorl((KScreenWidth-48.0*2.0-8.0*3.0)/4.0)
    
    let viewModel = YHBaseViewModel()
    
    var item: YHGrabItem = YHGrabItem()
    
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumInteritemSpacing = 8.0
        layout.minimumLineSpacing = 16
        
        let collectView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectView.delegate = self
        collectView.dataSource = self
        collectView.backgroundColor = .clear
        // 注册自定义单元格
        collectView.register(YHGrabFileCell.self, forCellWithReuseIdentifier: YHGrabFileCell.cellReuseIdentifier)
        return collectView
    }()
    
    func updateItem(_ item: YHGrabItem) {
        
        self.item = item
        
        titleLabel.text = item.title
        detailLabel.text = item.detail

        if item.isSingleLine {
            detailLabel.textAlignment = .right
        } else { // 需要显示多行
            // 当文字只有一行时右对齐，当文字有多行时左对齐
           let detaiLabelMaxWidth = KScreenWidth-(34.0+14.0)*2.0-titleMaxWidth
           let detailHeight = self.getHeight(text: item.detail, font: detailLabel.font, width: detaiLabelMaxWidth)
           detailLabel.textAlignment = detailHeight > 20.0 ? .left : .right
        }
        
        if item.type == .grab {
            detailLabel.textColor = grabNumColor
        } else {
            detailLabel.textColor = infoColor
        }
        
        detailLabel.snp.updateConstraints { make in
            make.left.greaterThanOrEqualTo(titleLabel.snp.right).offset(item.isSingleLine ? -20 : 0)
        }
        
        dotView.isHidden = (item.type != .grab)
        collectionView.isHidden = item.type != .files
        collectionView.reloadData()
        var rowCount = item.files.count/4
        if item.files.count%4 != 0 {
            rowCount += 1
        }
        
        collectionView.snp.remakeConstraints { make in
            make.left.right.bottom.equalTo(0)
            if item.type == .visit {
                make.top.equalTo(titleLabel.snp.bottom).offset(16)
            } else {
                make.top.equalTo(detailLabel.snp.bottom).offset(16)
            }
            if item.type == .files {
                make.height.equalTo((fileWidth+16.0)*Double(rowCount))

            } else {
                make.height.equalTo(0)
            }
        }
        
        self.setNeedsLayout()
        self.layoutIfNeeded()
        
    }
    
    lazy var dotView: UIView = {
        let view = UIView()
        view.backgroundColor = .brandMainColor
        view.layer.cornerRadius = self.dotWidth/2.0
        return view
    }()
        
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.textColor = .mainTextColor(alpha: 0.5)
        return label
    }()
    
    lazy var detailLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.textAlignment = .right
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.textColor = self.infoColor
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func createUI() {
                
        self.addSubview(titleLabel)
        self.addSubview(detailLabel)
        self.addSubview(dotView)
        self.addSubview(collectionView)
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.top.equalTo(0)
            make.width.equalTo(titleMaxWidth)
        }
        
        detailLabel.snp.makeConstraints { make in
            make.right.equalTo(0)
            make.top.equalTo(0)
            make.height.greaterThanOrEqualTo(20.0)
            make.left.greaterThanOrEqualTo(titleLabel.snp.right).offset(0)
        }
        
        dotView.snp.makeConstraints { make in
            make.width.height.equalTo(dotWidth)
            make.centerY.equalTo(detailLabel)
            make.right.equalTo(detailLabel.snp.left).offset(-4)
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.top.equalTo(detailLabel.snp.bottom).offset(16)
            make.height.equalTo(fileWidth)
            make.bottom.equalTo(0)
        }
    }
    
    func getHeight(text: String, font: UIFont, width: CGFloat) -> CGFloat {
        let size = CGSize.init(width: width, height: CGFloat(MAXFLOAT))
        let dic = [NSAttributedString.Key.font: font]
        let strSize = text.boundingRect(with: size, options: [.usesLineFragmentOrigin], attributes: dic, context: nil).size
        return CGSize(width: strSize.width, height: ceil(strSize.height)).height
    }
}

class YHGrabNumberInfoView: UIView {

    var items: [YHGrabItem] = []
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.PFSC_M(ofSize: 14)
        label.textColor = .mainTextColor
        return label
    }()
    
    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = .separatorColor
        return view
    }()
    
    lazy var listView: UIView = {
        let view = UIView()
        return view
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func createUI() {
        
        self.backgroundColor = UIColor.init(hex: 0xF8F9FB)
        self.layer.cornerRadius = kCornerRadius4
        self.clipsToBounds = true
        
        self.addSubview(titleLabel)
        self.addSubview(lineView)
        self.addSubview(listView)
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.top.equalTo(16)
        }
        
        lineView.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.height.equalTo(0.5)
            make.top.equalTo(titleLabel.snp.bottom).offset(10)
        }
        
        listView.snp.makeConstraints { make in
            make.top.equalTo(lineView.snp.bottom).offset(12)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(0)
        }
    }
    
    func updateItems(_ items: [YHGrabItem]) {
        self.items = items
        listView.removeSubviews()
        
        var lastView: YHGrabNumberInfoItemView?
        for (index, item) in items.enumerated() {
            let itemView = YHGrabNumberInfoItemView(frame: .zero)
            listView.addSubview(itemView)
            itemView.updateItem(item)
            itemView.snp.makeConstraints { make in
                make.left.equalTo(14)
                make.right.equalTo(-14)
                if let last = lastView {
                    make.top.equalTo(last.snp.bottom).offset(0)
                } else {
                    make.top.equalTo(listView.snp.top).offset(0)
                }
                
                if index == items.count-1 {
                    make.bottom.equalTo(0)
                }
            }
            lastView = itemView
        }
    }
}

extension YHGrabNumberInfoItemView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
        // 返回单元格数量
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            
            return item.files.count
        }
        
        // 返回每个单元格的大小
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            
            return CGSize(width: fileWidth, height: fileWidth)
        }
        
        // 返回自定义单元格
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHGrabFileCell.cellReuseIdentifier, for: indexPath) as? YHGrabFileCell else { return UICollectionViewCell() }
            if 0 <= indexPath.item && indexPath.item < item.files.count {
                let url = item.files[indexPath.item]
                if item.publicFiles.count == item.files.count {
                    // 公链组和私链组数量一致
                    let publicUrl = item.publicFiles[indexPath.item]
                    cell.fileUrl = publicUrl
                } else {
                    cell.fileUrl = ""
                }
            }
            return cell
        }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if 0 <= indexPath.item && indexPath.item < item.files.count {
            let privateUrl = item.files[indexPath.item]
            if item.publicFiles.count == item.files.count {
                // 公链组和私链组数量一致
                let publicUrl = item.publicFiles[indexPath.item]
                if !publicUrl.isEmpty {
                   YHPictureReviewManager.shared.showNetWorkPicturs(curIndex: indexPath.item, arrPicturs: item.publicFiles)
                } else { // 当前公链为空 仅请求当前点击文件公链
                    YHHUD.show(.progress(message: "加载中..."))
                    self.viewModel.getPublicImageUrl(privateUrl) { success, _ in
                        YHHUD.hide()
                        if let success = success {
                            self.item.publicFiles[indexPath.item] = success
                        }
                        self.collectionView.reloadData()
                        YHPictureReviewManager.shared.showNetWorkPicturs(curIndex: indexPath.item, arrPicturs: self.item.publicFiles)

                    }
                }
            }
        }
    }
}
