//
//  YHNewProductCell.swift
//  galaxy
//
//  Created by Dufet on 2025/10/12.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHNewProductCell: UITableViewCell {

    static let cellReuseIdentifier = "YHNewProductCell"
    var model: YHSelectGoodsModel = YHSelectGoodsModel()
    var onImageHeightChanged: (() -> Void)?
    
    lazy var imgView: UIImageView = {
        let v = UIImageView()
        v.contentMode = .scaleAspectFill
        v.clipsToBounds = true
        return v
    }()

    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")
    }

    func updateModel(_ model: YHSelectGoodsModel) {
        self.model = model
        if let url = URL(string: model.image) {
            imgView.sd_setImage(with: url, placeholderImage: UIImage(named: "plan_product_default")) { [weak self] image, _, _, resultUrl in
                guard let self = self else {
                    return
                }
                guard resultUrl?.absoluteString == self.model.image else {
                    return
                }
                guard let image = image, image.size.width > 0, image.size.height > 0 else {
                    return
                }
                model.ratio = image.size.height / image.size.width
                self.imgView.snp.updateConstraints { make in
                    make.height.equalTo(model.ratio * (KScreenWidth-20.0*2))
                }
                self.onImageHeightChanged?()
            
            }
        } else {
            imgView.snp.updateConstraints { make in
                make.height.equalTo(YHSelectGoodsModel.fix_new_productRatio * (KScreenWidth-20.0*2))
            }
        }
    }
    
    func setupUI() {
        self.selectionStyle = .none
        self.contentView.addSubview(self.imgView)
        self.imgView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.top.equalToSuperview()
            make.height.equalTo(YHSelectGoodsModel.fix_new_productRatio * (KScreenWidth-20.0*2))
            make.bottom.equalTo(-12)
        }
    }

}
