//
//  YHVisaRenewalPayMethodQrcodeCell.swift
//  galaxy
//
//  Created by alexzzw on 2024/10/10.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import Kingfisher

class YHVisaRenewalPayMethodQrcodeCell: YHResignDocumentCell {

    static let cellReuseIdentifier = "YHVisaRenewalPayMethodQrcodeCell"
    private var qrCode: String = ""
    
    var onLongPressEvent: ((UIImage) -> Void)?
    
    private lazy var infoTitleLabel: UILabel = {
        let label = UILabel()
        label.font = .PFSC_M(ofSize: 14)
        label.textColor = .mainTextColor
        return label
    }()
    
    private lazy var infoTipsLabel: UILabel = {
        let label = UILabel()
        label.font = .PFSC_R(ofSize: 12)
        label.textColor = .mainTextColor50
        label.numberOfLines = 0
        label.lineBreakMode = .byCharWrapping
        return label
    }()
    
    private lazy var qrcodeIcon: UIImageView = {
        let view = UIImageView()
        view.contentMode = .scaleAspectFit
        view.isUserInteractionEnabled = false
        view.addGestureRecognizer(longPress)
        return view
    }()
    
    /// 已添加的长按手势
    private lazy var longPress: UILongPressGestureRecognizer = {
        return UILongPressGestureRecognizer(target: self, action: #selector(onLongPress(_:)))
    }()
    
    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 setupCellInfo(title: String, tips: String, qrCode: String) {
        infoTitleLabel.text = title
        infoTipsLabel.text = tips
        self.qrCode = qrCode
        let cacheKey = "qrcode_\(qrCode)"
        let currentCode = qrCode
        
        func updateQRCode() {
            DispatchQueue.global(qos: .userInitiated).async { [weak self] in
                if let qrCodeImage = qrCode.generateQRCode() {
                    ImageCache.default.store(qrCodeImage, forKey: cacheKey)
                    DispatchQueue.main.async {
                        if let self = self, currentCode == self.qrCode {
                            self.qrcodeIcon.image = qrCodeImage
                            self.qrcodeIcon.isUserInteractionEnabled = true
                        }
                    }
                }
            }
        }
        
        if ImageCache.default.isCached(forKey: cacheKey) {
            ImageCache.default.retrieveImage(forKey: cacheKey) { [weak self] result in
                switch result {
                case .success(let cacheResult):
                    if let self = self, currentCode == self.qrCode, let image = cacheResult.image {
                        self.qrcodeIcon.image = image
                        self.qrcodeIcon.isUserInteractionEnabled = true
                    }
                case .failure:
                    updateQRCode()
                }
            }
        } else {
            updateQRCode()
        }
    }
}

extension YHVisaRenewalPayMethodQrcodeCell {
    
    /// 长按
    @objc func onLongPress(_ press: UILongPressGestureRecognizer) {
        if press.state == .began {
            guard let image = self.qrcodeIcon.image else {
                return
            }
            onLongPressEvent?(image)
        }
    }
    
    private func setupUI() {
        subContainerView.radius = 6
        updateCellCorner(.bottom)
        subContainerView.addSubview(infoTitleLabel)
        subContainerView.addSubview(infoTipsLabel)
        subContainerView.addSubview(qrcodeIcon)
        
        qrcodeIcon.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(18)
            make.right.equalToSuperview().offset(-18)
            make.bottom.equalToSuperview().offset(-27)
            make.width.height.equalTo(86)
        }
        
        infoTitleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(18)
            make.top.equalToSuperview().offset(31)
            make.right.lessThanOrEqualTo(qrcodeIcon.snp.left).offset(-16)
        }
        
        infoTipsLabel.snp.makeConstraints { make in
            make.left.equalTo(infoTitleLabel.snp.left)
            make.top.equalTo(infoTitleLabel.snp.bottom).offset(6)
            make.right.lessThanOrEqualTo(qrcodeIcon.snp.left).offset(-16)
            make.bottom.lessThanOrEqualToSuperview().offset(-18)
        }
    }
}
