//
//  HomePayView.swift
//  PhoneManager
//
//  Created by zxhy on 2025/3/20.
//

import UIKit
import SnapKit
import Lottie
import StoreKit
import Kingfisher

class HomePayView:UIView {
    
    private var restoreBtn:UIButton?
    private var closeBtn:UIButton?
    private var titleLabel1:UILabel?
    private var titleLabel2:UILabel?
//    private var photoImage:UIImageView!
//    private var icloudImage:UIImageView!
//    private var photoLabel:UILabel?
//    private var icloudLabel:UILabel?
//    private var animationLabel:UILabel?
    private var contentView2:UIView?
    private var contentView2Title:UILabel?
    private var contentView2Switch:UISwitch?
    
    private var ppLabel:UILabel?
    private var touLabel:UILabel?
    private var appleLabel:UILabel?
    private var payButton:UIButton?
    
    private var freeContent:UIView?
    private var freeContentTitle:UILabel?
    private var freeContentTip:UILabel?
    private var freeContentMoney:UILabel?
    private var normalContent:UIView?
    private var normalContentTitle:UILabel?
    private var normalContentMoney:UILabel?
    
    private var trailTitle:UILabel!
    private var tipsView:UIView!
    private var memSize:UILabel!
//    var sizeLabel:UILabel!
    
    var type = 0 {
        didSet {
            setIsSelect()
        }
    }
    
    lazy var ppBtn:UIButton = {
        let sview:UIButton = UIButton()
        let content:String = "Terms"
        let font = UIFont.scaledSystemFont(ofSize: 12, weight: .medium)
        let color = UIColor.colorWithHex(hexStr: black6Color)
        sview.setTitle(content, for: .normal)
        sview.setTitleColor(color, for: .normal)
        sview.titleLabel?.font = font
        sview.sizeToFit()
        sview.isSelected = false
        let attributes: [NSAttributedString.Key: Any] = [
            .font: font,
            .foregroundColor: color,
            .underlineStyle: NSUnderlineStyle.single.rawValue
        ]
        let attributedString = NSAttributedString(string: content, attributes: attributes)
        sview.setAttributedTitle(attributedString, for: .normal)
        sview.addTarget(self, action: #selector(ppBtnClick(btn:)), for: .touchUpInside)
        sview.sizeToFit()
        
        return sview
    }()
    
    lazy var touBtn:UIButton = {
        
        let sview:UIButton = UIButton()
        let content:String = "Restore"
        let font = UIFont.scaledSystemFont(ofSize: 12, weight: .medium)
        let color = UIColor.colorWithHex(hexStr: black6Color)
        
        sview.setTitle(content, for: .normal)
        sview.setTitleColor(color, for: .normal)
        sview.titleLabel?.font = font
        sview.sizeToFit()
        
        let attributes: [NSAttributedString.Key: Any] = [
            .font: font,
            .foregroundColor: color,
            .underlineStyle: NSUnderlineStyle.single.rawValue
        ]
        let attributedString = NSAttributedString(string: content, attributes: attributes)
        sview.setAttributedTitle(attributedString, for: .normal)
        sview.addTarget(self, action: #selector(touBtnClick(btn:)), for: .touchUpInside)
        sview.sizeToFit()
        
        return sview
    }()
    
    
    lazy var animationView:LottieAnimationView = {
        let animationView = LottieAnimationView(name: "OnboardingPaywallScreenAnimationLIGHT")
        animationView.loopMode = .loop
        return animationView
    }()
   
    var callBack:callBack<Any> = {text in}
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setupUI()
        setPayAnime()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        backgroundColor = .white
        
        closeBtn = UIButton()
        closeBtn?.setImage(UIImage(named: "home_pay_close"), for: .normal)
        closeBtn?.addTarget(self, action: #selector(closeBtnClick), for: .touchUpInside)
        self.addSubview(closeBtn!)
        
        closeBtn?.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(statusBarHeight +  10)
            make.right.equalToSuperview().offset(-15)
            make.width.height.equalTo(28)
        }
        
        titleLabel1 = UILabel()
        titleLabel1?.text = "Clean your Storage"
        titleLabel1?.font = UIFont.scaledSystemFont(ofSize: 24.RW(), weight: .bold)
        titleLabel1?.textColor = UIColor.colorWithHex(hexStr: black3Color)
        self.addSubview(titleLabel1!)
        
        titleLabel1?.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(statusBarHeight + (68.RH()))
            make.centerX.equalToSuperview()
        }
        
        titleLabel1?.sizeToFit()
        
        titleLabel2 = UILabel()
        titleLabel2?.text = "Get rid of what you don't need"
        titleLabel2?.font = UIFont.scaledSystemFont(ofSize: 14.RW(), weight: .regular)
        titleLabel2?.textColor = UIColor.colorWithHex(hexStr: black3Color)
        self.addSubview(titleLabel2!)
        
        titleLabel2?.snp.makeConstraints { make in
            make.top.equalTo(titleLabel1!.snp.bottom).offset(12)
            make.centerX.equalToSuperview()
        }
        
        titleLabel2?.sizeToFit()
   
        self.addSubview(animationView)
        
//        let webpImage = UIImageView()
//        if let webpPath = Bundle.main.path(forResource: "pay_animation", ofType: "gif"),
//            let webpURL = URL(string: "file://" + webpPath) {
//            webpImage.kf.setImage(with: webpURL)
//        }
//        self.addSubview(webpImage)
        
        playAnimationWithDelay()
        animationView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(titleLabel2!.snp.bottom).offset(20)
            make.width.equalTo(290.RW())
            make.height.equalTo(186.RW())
        }
        
        appleLabel = UILabel()
        appleLabel?.text = " Secured with Apple"
        appleLabel?.font = UIFont.scaledSystemFont(ofSize: 12, weight: .bold)
        appleLabel?.textColor = UIColor.colorWithHex(hexStr: black3Color)
        self.addSubview(appleLabel!)
        self.addSubview(ppBtn)
        self.addSubview(touBtn)
        payButton = UIButton()
        payButton?.setTitle("Try Free", for: .normal)
        payButton?.setTitleColor(UIColor.colorWithHex(hexStr: whiteColor), for: .normal)
        payButton?.titleLabel?.font = UIFont.scaledSystemFont(ofSize: 16, weight: .bold)
        payButton?.backgroundColor = UIColor.colorWithHex(hexStr: mColor)
        payButton?.isEnabled = false
        payButton?.addTarget(self, action: #selector(payButtonClick), for: .touchUpInside)
        self.addSubview(payButton!)
        
        appleLabel?.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(ScreenH - (20+kSafeAreaInsets.bottom))
            make.centerX.equalToSuperview()
        }
        ppBtn.snp.makeConstraints { make in
            make.centerY.equalTo(appleLabel!)
            make.left.equalToSuperview().offset(marginLR)
        }
        touBtn.snp.makeConstraints { make in
            make.centerY.equalTo(appleLabel!)
            make.right.equalToSuperview().offset(-marginLR)
        }
        payButton?.layer.cornerRadius = 32.RH()
        payButton?.layer.masksToBounds = true
        
        // 额外添加视图
        setCenterViewUI()
        
        contentView2 = UIView()
        contentView2?.backgroundColor = UIColor.colorWithHex(hexStr: "#F2F6FC")
        self.addSubview(contentView2!)
        contentView2?.snp.makeConstraints({ make in
            make.top.equalTo(tipsView.snp.bottom).offset(12)
//            make.centerX.equalToSuperview()
//            make.width.equalToSuperview().offset(-32)
            make.left.right.equalToSuperview().inset(15)
            make.height.equalTo(60.RH())
        })
        payButton?.snp.makeConstraints({ make in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(appleLabel!.snp.top).offset(-12.RH())
            make.width.equalToSuperview().offset(-30)
            make.height.equalTo(65.RH())
        })
        contentView2?.layer.cornerRadius = 12
        contentView2?.layer.masksToBounds = true
        

        contentView2Title = UILabel()
        contentView2Title?.text = "Free trial enabled"
        contentView2Title?.font = UIFont.scaledSystemFont(ofSize: 16, weight: .bold)
        contentView2Title?.textColor = UIColor.colorWithHex(hexStr: black3Color)
        self.contentView2?.addSubview(contentView2Title!)
        
        contentView2Title?.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.centerY.equalToSuperview()
            make.width.equalToSuperview().offset(-32)
            make.height.equalTo(22)
        }
        contentView2Switch = UISwitch()
        contentView2Switch?.onTintColor = UIColor.colorWithHex(hexStr: mColor)
        contentView2Switch?.tintColor = .white
        contentView2Switch?.backgroundColor = .clear
        contentView2Switch?.isOn = true
        self.contentView2?.addSubview(contentView2Switch!)
        
        contentView2Switch?.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-16)
            make.centerY.equalToSuperview()
//            make.width.equalTo(46)
//            make.height.equalTo(28)
        }
        contentView2Switch?.addTarget(self, action: #selector(switchValueChanged(_:)), for: .valueChanged)
        
        privavye_Label.snp.makeConstraints { make in
            make.left.right.equalTo(self.contentView2!)
            make.top.equalTo(ppBtn.snp.bottom).offset(15.RH())
            make.bottom.equalToSuperview().offset(-10)
        }
        self.layoutIfNeeded()
        setIsSelect()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
            self.callBack(CommonPush.change)
        }
        
          
    }
    
    func playAnimationWithDelay() {
        // 播放动画
        animationView.play()
//        animationView.play(fromProgress: 0.4, toProgress: 1, loopMode: .playOnce) {[weak self] finished in
//            if finished {
//                // 动画播放完成后，延迟 2 秒再重新播放
//                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
//                    self?.playAnimationWithDelay()
//                }
//            }
//        }
    }
    
    lazy var privavye_Label: UILabel = {
        let priva = UILabel()
        priva.font = UIFont.scaledSystemFont(ofSize: 14, weight: .regular)
        priva.textColor = .gray
        priva.text = ""
        priva.numberOfLines = 0
        priva.clipsToBounds = true
        priva.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(labelTapped(_:)))
        priva.addGestureRecognizer(tap)
        addSubview(priva)
        return priva
    }()
    
    
    @objc private func labelTapped(_ gesture: UITapGestureRecognizer) {
        let location = gesture.location(in: privavye_Label)
        let strs:NSString = "privacy policy"
        let frssss = strs.boundingRect(with: CGSizeMake(.infinity, .infinity), options: .truncatesLastVisibleLine, attributes: [NSAttributedString.Key.font : privavye_Label.font], context: nil)
        let frame1 = CGRectMake(0, privavye_Label.height-25, CGRectGetWidth(frssss), 25)
        let frame2 = CGRectMake(CGRectGetWidth(frssss)+20, privavye_Label.height-25, 90, 25)
        if frame1.contains(location) {
            Print("点击了隐私")
            callBack(CommonPush.pp)
        }else if frame2.contains(location){
            Print("点击了terms")
            callBack(CommonPush.tou)
        }
    }
    
    
    var weekProduct : SKProduct?
    
    var lifeProduct : SKProduct?
    
    func reloadSKPorduct(week:SKProduct?,life:SKProduct?){
       
        self.weekProduct = week
        self.lifeProduct = life
        
        if week != nil,life != nil{
            payButton?.isEnabled = true
        }else{
            payButton?.isEnabled = false
        }
    
        payDueView.reloadUI(type, week: week, life: life)
        
        trailTitle.attributedText = nil
        if let pord = week{
//            trailTitle.text = "Free for 7 days, then \(pord.localizedPrice)/week"
            let be = NSMutableAttributedString(string: "Free for 7 days,", attributes: [.font:UIFont.scaledSystemFont(ofSize: 14, weight: .regular)])
            be.append(NSAttributedString(string: " then \(pord.localizedPrice)/week", attributes: [.font:UIFont.scaledSystemFont(ofSize: 16, weight: .regular)]))
            trailTitle.attributedText = be
        }
        
    }
    
    private func setIsSelect() -> Void {

        contentView2Switch?.isOn = type == 0
        payButton?.setTitle(type == 0 ? "Try Free" : "Start Now", for: .normal)
        
        payDueView.reloadUI(type, week: weekProduct, life: lifeProduct)
        
        if let pord = weekProduct,type == 0 {
//            trailTitle.text = "Free for 7 days, then \(pord.localizedPrice)/week"
//            trailTitle.font = UIFont.scaledSystemFont(ofSize: 16)
            let be = NSMutableAttributedString(string: "Free for 7 days,", attributes: [.font:UIFont.scaledSystemFont(ofSize: 14, weight: .regular)])
            be.append(NSAttributedString(string: " then \(pord.localizedPrice)/week", attributes: [.font:UIFont.scaledSystemFont(ofSize: 16, weight: .regular)]))
            trailTitle.attributedText = be
        }
        
        if let pord = lifeProduct,type == 1{
            trailTitle.attributedText = nil
            trailTitle.text = "\(pord.localizedPrice)/Lifetime"
//            trailTitle.font = UIFont.scaledSystemFont(ofSize: 16, weight: .regular)
//            setAttributedString(price: pord.localizedPrice)
            
        }
       
    }
    
    @objc func closeBtnClick() {
        callBack(OperStatus.close)
    }
    
    @objc func ppBtnClick(btn:UIButton) {
        btn.isSelected = !btn.isSelected
        let strs:NSString = btn.isSelected ? "We offer 1-year and lifetime subscriptions. The price is clearly displayed within the application.\n\n·After the purchase confirmation, your iTunes account will be charged.\n\n·Unless the automatic update is turned off at least 24 hours before the end of the current cycle, the subscription will be automatically updated.\n\n·Your account will be renewed within 24 hours before the end of the current cycle cost.\n\n·You can go to the \"Account Settings\" in the iTunes store to manage your subscriptions and turn off auto renewal.\n\n·If provided, if you choose to use our free trial version, any unused portion during the free trial period will become invalid when you purchase a publication subscription, if applicable.\n\n·If you choose not to purchase the AI PhoneManager Pro version, you can continue to use it for free and enjoy PhoneManager.\n\nYour personal data is securely stored in PhoneManager, please make sure to read our \nprivacy policy and terms of use." : ""
        
        let attribtit = NSMutableAttributedString(string:strs as String , attributes: [:])
        if strs.length > 3 {
            let rang = strs.range(of: "privacy policy")
            attribtit.addAttributes([NSAttributedString.Key.font : UIFont.scaledSystemFont(ofSize: 14, weight: .bold),NSAttributedString.Key.underlineStyle:NSUnderlineStyle.single.rawValue,.link:"appscheme://private"], range: rang)
            let rang1 = strs.range(of: "terms of use")
            attribtit.addAttributes([NSAttributedString.Key.font : UIFont.scaledSystemFont(ofSize: 14, weight:  .bold),NSAttributedString.Key.underlineStyle:NSUnderlineStyle.single.rawValue,.link:"appscheme://terms"], range: rang1)
        }
        privavye_Label.attributedText = attribtit
        layoutIfNeeded()
        callBack(CommonPush.change)
    }
    
    @objc func touBtnClick(btn:UIButton) {
//        callBack(CommonPush.tou)
        callBack(CommonPush.restore)
    }
    
    @objc func switchValueChanged(_ sender: UISwitch) {
        type = sender.isOn ? 0 : 1
        self.vibrate()
    }
    
    @objc func restoreTouch() -> Void {
        callBack(CommonPush.restore)
    }
    
    @objc func payButtonClick() {
        callBack(CommonPush.pay)
    }
    
    

    
    func setCenterViewUI(){
        
        tipsView = UIView()
        tipsView.backgroundColor = UIColor.colorWithHex(hexStr: "#F2F6FC")
        tipsView.layer.cornerRadius = 12
        addSubview(tipsView)
        
        let tiptTitle = UILabel()
        tiptTitle.text = "Phone Manager"
        tiptTitle.textColor = UIColor.colorWithHex(hexStr: black3Color)
        tiptTitle.font = UIFont.scaledSystemFont(ofSize: 16, weight: .bold)
        tipsView.addSubview(tiptTitle)
        tiptTitle.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(16.RH())
        }
        
        let subTitle = UILabel()
        subTitle.text = "Smart Cleaning, Video Compressor, Secret Storage, Manage Contacts, No Ads and Limits."
        subTitle.textColor = UIColor.colorWithHex(hexStr: black6Color)
        subTitle.numberOfLines = 2
        subTitle.font = UIFont.scaledSystemFont(ofSize: 12, weight: .regular)
        tipsView.addSubview(subTitle)
        subTitle.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(tiptTitle.snp.bottom).offset(8.RH())
        }
        
        trailTitle = UILabel()
        trailTitle.text = "" //"Free for 7 days, then $6.99/week"
        trailTitle.textColor = UIColor.colorWithHex(hexStr: black6Color)
        trailTitle.font = UIFont.scaledSystemFont(ofSize: 16, weight: .regular)
        tipsView.addSubview(trailTitle)
        trailTitle.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(subTitle.snp.bottom).offset(8.RH())
//            make.bottom.equalToSuperview().offset(-16)
        }
        
        tipsView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel2!.snp.bottom).offset(230.RH())
            make.left.right.equalToSuperview().inset(marginLR)
            make.height.equalTo(130.RH())
        }
 
        payDueView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(tipsView.snp.bottom).offset(90.RH())
            make.height.equalTo(50.RH())
        }
        
    }
    
    func setAttributedString(price:String){
        

        // 定义动态的文本
        let sizeValue = price // 这里可以是任何动态数值，例如来自其他计算或输入
        let unit = "/Lifetime"
        let fullText = "\(sizeValue) \(unit)"

        // 创建一个可变的富文本字符串
        let attributedString = NSMutableAttributedString(string: fullText)

        // 设置前半部分（动态数值）的范围
        let regularFont = UIFont.scaledSystemFont(ofSize: 18, weight: .regular) // 设置常规字体大小
        let range1 = (fullText as NSString).range(of: sizeValue)
        attributedString.addAttribute(.font, value: regularFont, range: range1)

        // 设置“GB”部分的范围并将字体大小设置为12
        let smallFont = UIFont.scaledSystemFont(ofSize: 14, weight: .regular) // 设置字体大小为12
        let range2 = (fullText as NSString).range(of: unit)
        attributedString.addAttribute(.font, value: smallFont, range: range2)
        
        trailTitle.attributedText = attributedString
        
    }
    
    
    lazy var payDueView:HomePayDueView = {
        let payDueView = Bundle.main.loadNibNamed("HomePayDueView", owner: nil, options: nil)?.last as! HomePayDueView
        addSubview(payDueView)
        return payDueView
    }()
    
    
    func setPayAnime(){
        // 添加呼吸动画
         let breathAnimation = CABasicAnimation(keyPath: "transform.scale")
         breathAnimation.fromValue = 1.0
         breathAnimation.toValue = 1.05
         breathAnimation.duration = 0.8
         breathAnimation.autoreverses = true
         breathAnimation.repeatCount = Float.infinity
         breathAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
         payButton?.layer.add(breathAnimation, forKey: "breathingAnimation")
    }
}
