//
//  MergePreButtonView.swift
//  PhoneManager
//
//  Created by edy on 2025/5/8.
//

import Foundation

class MergePreButtonView : UIView {
    
    var mergePreCallBack : ()->Void = {}
    
    
    lazy var mergePreButton : UIButton = {
        let view = UIButton(type: .custom)
        view.backgroundColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 1)
        view.setTitleColor(.white, for: .normal)
        view.clipsToBounds = true
        view.layer.cornerRadius = 23
        view.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        view.setTitle("See Merge Preview", for: .normal)
        view.setImage(UIImage(named: "ic_hebing"), for: .normal)
        
        // 设置间距为 8
        let spacing: CGFloat = 8
        // 获取图片和文字的大小
        let imageSize = view.imageView?.image?.size ?? .zero
        let titleSize = view.titleLabel?.intrinsicContentSize ?? .zero
        // 计算 imageEdgeInsets 和 titleEdgeInsets
        view.imageEdgeInsets = UIEdgeInsets(top: 0, left: -spacing / 2, bottom: 0, right: spacing / 2)
        view.titleEdgeInsets = UIEdgeInsets(top: 0, left: spacing / 2, bottom: 0, right: -spacing / 2)
        
        view.addTarget(self, action: #selector(mergePre), for: .touchUpInside)
        return view
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .white
        self.addSubview(self.mergePreButton)
        
        self.mergePreButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(46)
            make.top.equalToSuperview().offset(16)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension MergePreButtonView {
    
    @objc func mergePre(){
        if IAPManager.share.isSubscribed == false {
            // 添加的时候需要先弹出广告
            ADManager.shared.showRewardedInterstitialAd(from: ADShowTypeEnum.Merge.name) {[weak self] in
                guard let weakSelf = self else { return }
                weakSelf.mergePreCallBack()
            } showFailBlock: { _ in
                ADManager.shared.failShowErrMessage()
            }
        }else {
            self.mergePreCallBack()
        }
    }
}
