//
//  MP_IAPViewController.swift
//  relax.offline.mp3.music
//
//  Created by Mr.Zhou on 2024/7/31.
//

import UIKit

///内购选中图片
let IAPChooseedImage:UIImage? = .init(named: "IAP Chooseed'logo")
///内购未选中图片
let IAPChooseImage:UIImage? = .init(named: "IAP Choose'logo")
///内购页面（A/B面样式区别）
class MP_IAPViewController: UIViewController {
    //样式版，根据A/B面决定
    @IBOutlet weak var bgImageView: UIImageView!
    @IBOutlet weak var scrollView: UIScrollView!
    var isType:Bool = false
    @IBOutlet weak var aConstraint: NSLayoutConstraint!
    @IBOutlet weak var bConstraint: NSLayoutConstraint!
    @IBOutlet weak var adView: UIView!
    @IBOutlet weak var adLabel: UILabel!
    @IBOutlet weak var musicView: UIView!
    @IBOutlet weak var musicLabel: UILabel!
    @IBOutlet weak var downloadView: UIView!
    @IBOutlet weak var downloadLabel: UILabel!
    @IBOutlet weak var weekView: UIView!{
        didSet{
            weekView.isUserInteractionEnabled = true
            weekView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(chooseLevelClick(_ :))))
        }
    }
    @IBOutlet weak var weekImageView: UIImageView!
    @IBOutlet weak var weekPriceLabel: UILabel!
    @IBOutlet weak var yearView: UIView!{
        didSet{
            yearView.isUserInteractionEnabled = true
            yearView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(chooseLevelClick(_ :))))
        }
    }
    @IBOutlet weak var yearImageView: UIImageView!
    @IBOutlet weak var yearPriceLabel: UILabel!
    @IBOutlet weak var lifeView: UIView!{
        didSet{
            lifeView.isUserInteractionEnabled = true
            lifeView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(chooseLevelClick(_ :))))
        }
    }
    @IBOutlet weak var lifeImageView: UIImageView!
    @IBOutlet weak var lifePriceLabel: UILabel!
    var privacyBlock:(() -> Void)?
    var termsBlock:(() -> Void)?
    //选择的等级
    private var level:Int?
    override func viewDidLoad() {
        super.viewDidLoad()
        scrollView.contentInsetAdjustmentBehavior = .never
        MP_IAPManager.shared.requestProducts()
        //根据isType调整约束（A/B面样式存在差距）
        if isType {
            //B面
            bgImageView.image = UIImage(named: "IAP B'bg")
            aConstraint.priority = .init(500)
            bConstraint.priority = .init(999)
            //展示所有的权益
            musicView.isHidden = false
            downloadView.isHidden = false
            
        }else {
            //A面
            bgImageView.image = UIImage(named: "IAP A'bg")
            aConstraint.priority = .init(999)
            bConstraint.priority = .init(500)
            //隐藏权益
            musicView.isHidden = true
            downloadView.isHidden = true
        }
        //实现文本填充
        adLabel.attributedText = setSubstring("Ad-free experience, NO ADs!!", coloredText: "NO ADs!!")
        musicLabel.text = "All \"YouTube\" music & videos"
        downloadLabel.text = "Unlimited Downloads"
        
        //设置价格文本
        weekPriceLabel.attributedText = setPriceText(1.99)
        yearPriceLabel.attributedText = setPriceText(14.99)
        lifePriceLabel.attributedText = setPriceText(24.99)
    }
    //根据文本内容调整显示颜色
    private func setSubstring(_ fullText:String, coloredText:String) -> NSAttributedString {
        //调整展示颜色
        let attributedString = NSMutableAttributedString(string: fullText, attributes: [.foregroundColor:UIColor.white, .font:UIFont.systemFont(ofSize: 16*width)])
        let attributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor(hex: "#80F988")]
        if let range = fullText.range(of: coloredText) {
            let nsRange = NSRange(range, in: fullText)
            attributedString.addAttributes(attributes, range: nsRange)
        }
        return attributedString
    }
    //设置价格副文本
    private func setPriceText(_ price:Double) -> NSAttributedString {
        let font = UIFont(name: "DINAlternate-Bold", size: 24*width) ?? .systemFont(ofSize: 24*width, weight: .bold)
        let attributedString = NSMutableAttributedString(string: "$\(price)", attributes: [.foregroundColor:UIColor.white, .font:font])
        attributedString.addAttributes([.font:UIFont(name: "DINAlternate-Bold", size: 16*width) ?? .systemFont(ofSize: 16*width, weight: .bold)], range: .init(location: 0, length: 1))
        return attributedString
    }
    
    //退出页面
    @IBAction func dismissClick(_ sender: UIButton) {
        dismiss(animated: true)
    }
    //选择档位
    @objc private func chooseLevelClick(_ sender:UITapGestureRecognizer) {
        let tag = sender.view?.tag ?? 0
        switch tag {
        case 0://选择了第一档
            weekPriceLabel.setGradientTextColor(gradientTextColors)
            weekImageView.image = IAPChooseedImage
            
            yearPriceLabel.cleanGradientTextColor()
            yearImageView.image = IAPChooseImage
            lifePriceLabel.cleanGradientTextColor()
            lifeImageView.image = IAPChooseImage
        case 1://选择了第二档
            yearPriceLabel.setGradientTextColor(gradientTextColors)
            yearImageView.image = IAPChooseedImage
            
            weekPriceLabel.cleanGradientTextColor()
            weekImageView.image = IAPChooseImage
            lifePriceLabel.cleanGradientTextColor()
            lifeImageView.image = IAPChooseImage
        default://选择了第三档
            lifePriceLabel.setGradientTextColor(gradientTextColors)
            lifeImageView.image = IAPChooseedImage
            
            weekPriceLabel.cleanGradientTextColor()
            weekImageView.image = IAPChooseImage
            yearPriceLabel.cleanGradientTextColor()
            yearImageView.image = IAPChooseImage
        }
        level = tag
    }
    //继续购买
    @IBAction func continueClick(_ sender: UIButton) {
        guard let level = level else {
            MP_HUD.onlytext("Please select your membership type", delay: 1.0, completion: nil)
            return
        }
        guard MP_NetWorkManager.shared.netWorkStatu == .reachable else {
            MP_HUD.onlytext("Bad connection~", delay: 1.0, completion: nil)
            return
        }
        MP_IAPManager.shared.purchaseProduct(level)
    }
    //刷新商店
    @IBAction func reStoreClick(_ sender: UIButton) {
        MP_IAPManager.shared.restorePurchases()
    }
    //协议
    @IBAction func privacyClick(_ sender: UIButton) {
        dismiss(animated: true) {
            [weak self] in
            if let block = self?.privacyBlock {
                block()
            }
        }
    }
    //用户服务
    @IBAction func termsClick(_ sender: UIButton) {
        dismiss(animated: true) {
            [weak self] in
            if let block = self?.termsBlock {
                block()
            }
        }
    }
}
