//
//  YHResourceDetailDocumentsCell.swift
//  galaxy
//
//  Created by alexzzw on 2025/9/30.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHResourceDetailDocumentsCell: UITableViewCell {
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.PFSC_B(ofSize: 17)
        label.textColor = UIColor.brandGrayColor8
        label.text = "企业相关资料"
        return label
    }()
    
    private lazy var noDataView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        view.clipsToBounds = true
        view.isHidden = true
        let imageView = UIImageView(image: UIImage(named: "no_data_bg_common"))
        let label = UILabel()
        label.text = "暂无企业相关资料"
        label.textColor = UIColor.brandGrayColor6
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.textAlignment = .center
        view.addSubview(imageView)
        view.addSubview(label)
        imageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview()
            make.width.height.equalTo(128)
        }
        label.snp.makeConstraints { make in
            make.top.equalTo(imageView.snp.bottom).offset(16)
            make.left.right.bottom.equalToSuperview()
        }
        return view
    }()
    
    private lazy var imagesStackView: UIStackView = {
        let stack = UIStackView()
        stack.axis = .vertical
        stack.spacing = 12
        stack.distribution = .fill
        return stack
    }()
    
    private var images: [String] = []
    var onImageTapped: ((Int) -> Void)?
    var onImageHeightChanged: (() -> Void)?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        selectionStyle = .none
        backgroundColor = .white
        contentView.backgroundColor = .white
        
        contentView.addSubview(titleLabel)
        contentView.addSubview(noDataView)
        contentView.addSubview(imagesStackView)
        titleLabel.setContentCompressionResistancePriority(.required, for: .vertical)
        titleLabel.setContentHuggingPriority(.required, for: .vertical)
        imagesStackView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
        imagesStackView.setContentHuggingPriority(.defaultLow, for: .vertical)
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalToSuperview().offset(24)
        }
        
        noDataView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(24)
            make.left.right.equalToSuperview()
            make.height.equalTo(0)
            // make.bottom.equalToSuperview().offset(-24)
        }
        
        imagesStackView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalTo(titleLabel.snp.bottom).offset(16)
            make.bottom.equalToSuperview().offset(-24)
        }
    }
    
    func configure(with images: [String]) {
        self.images = images
        // 清空之前的图片
        imagesStackView.arrangedSubviews.forEach { $0.removeFromSuperview() }
        guard images.count > 0 else {
            noDataView.isHidden = false
            imagesStackView.isHidden = true
            noDataView.snp.remakeConstraints { make in
                make.top.equalTo(titleLabel.snp.bottom).offset(24)
                make.left.right.equalToSuperview()
                make.bottom.equalToSuperview().offset(-24)
            }
            imagesStackView.snp.remakeConstraints { make in
                make.left.equalToSuperview().offset(20)
                make.right.equalToSuperview().offset(-20)
                make.top.equalTo(titleLabel.snp.bottom).offset(16)
                make.height.equalTo(0)
            }
            return
        }
        imagesStackView.isHidden = false
        noDataView.snp.remakeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(24)
            make.left.right.equalToSuperview()
            make.height.equalTo(0)
        }
        
        imagesStackView.snp.remakeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalTo(titleLabel.snp.bottom).offset(16)
            make.bottom.equalToSuperview().offset(-24)
        }
        
        let imageWidth = KScreenWidth - 20 * 2 // 左右各16的padding
        let imageHeight = imageWidth * 1.0 // A4纸张比例
        
        for (index, imageUrl) in images.enumerated() {
            let imageView = UIImageView()
            imageView.contentMode = .scaleAspectFit
            imageView.isUserInteractionEnabled = true
            
            if let url = URL(string: imageUrl) {
                // 设置图片视图的高度
                imageView.snp.makeConstraints { make in
                    make.height.equalTo(imageHeight)
                }
                imageView.sd_setImage(with: url, placeholderImage: UIImage(named: "plan_product_default")) { [weak self] image, _, _, _ in
                    guard let self = self else {
                        return
                    }
                    guard let image = image, image.size.width > 0, image.size.height > 0 else {
                        return
                    }
                    let newImageHeight = image.size.height / image.size.width * imageWidth
                    if abs(newImageHeight - imageHeight) > 10 {
                        // 关键：用 updateConstraints 而不是 remakeConstraints
                        imageView.snp.updateConstraints { make in
                            make.height.equalTo(newImageHeight)
                        }
                        self.onImageHeightChanged?()
                    }
                }
            } else {
                // 设置图片视图的高度
                imageView.snp.makeConstraints { make in
                    make.height.equalTo(imageWidth)
                }
                imageView.image = UIImage(named: "plan_product_default")
            }
            
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(imageTapped(_:)))
            imageView.addGestureRecognizer(tapGesture)
            imageView.tag = index
            imagesStackView.addArrangedSubview(imageView)
        }
    }
    
    @objc private func imageTapped(_ gesture: UITapGestureRecognizer) {
        if let imageView = gesture.view {
            onImageTapped?(imageView.tag)
        }
    }
}
