//
//  PayDistanceViewController.swift
//  PhoneManager
//
//  Created by edy on 2025/5/19.
//

import UIKit
import StoreKit
import SVProgressHUD
import Lottie

class PayDistanceViewController: UIViewController {
    
    var scrollView:UIScrollView!
    
    var dropImage:UIImageView!
    var distanceL:UILabel!
    var annual:UILabel!
    var cancelLabel:UILabel!
    var yearDistacePrice:UILabel!
    var offerImage:UIImageView!
    
    var payBtn:UIButton!
    
    var year:SKProduct?
    var life:SKProduct?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configUI()
        reloadSKPorduct()
        IAPManager.share.showYearPage = false
    }
    
    
    func configUI(){
        
        scrollView = UIScrollView()
        scrollView.frame = CGRect(x: 0, y: 0, width: ScreenW, height: ScreenH)
        scrollView.contentSize = CGSize(width: ScreenW, height: ScreenH)
        scrollView.contentInsetAdjustmentBehavior = .never
        scrollView.delaysContentTouches = false  // 添加这一行
        scrollView.canCancelContentTouches = true  // 添加这一行
        view.addSubview(scrollView)
        
        let closeBtn = UIButton()
        closeBtn.setImage(UIImage.init(named: "home_pay_close"), for: .normal)
        closeBtn.addTarget(self, action: #selector(payClose), for: .touchUpInside)
        scrollView.addSubview(closeBtn)
        
        offerImage = UIImageView()
        offerImage.image = UIImage.init(named: "iap_distance_offer")
        scrollView.addSubview(offerImage)
        
        
        dropImage = UIImageView()
        dropImage.image = UIImage.init(named: "iap_distance_bg")
        scrollView.addSubview(dropImage)
        
        
        distanceL = UILabel()
        distanceL.text = "50% Discount"
        distanceL.textAlignment = .center
        distanceL.font = UIFont.systemFont(ofSize: 40.RW(), weight: .semibold)
        distanceL.textColor = UIColor.colorWithHex(hexStr: "#111111")
        scrollView.addSubview(distanceL)
        
        annual = UILabel()
        annual.text = "Annual visit"
        annual.textAlignment = .center
        annual.font = UIFont.systemFont(ofSize: 18.RW(), weight: .semibold)
        annual.textColor = UIColor.colorWithHex(hexStr: "#111111")
        scrollView.addSubview(annual)
        
        yearDistacePrice = UILabel()
        yearDistacePrice.font = UIFont.systemFont(ofSize: 14.RW(),weight: .semibold)
        yearDistacePrice.textColor = UIColor.colorWithHex(hexStr: "#111111")
        yearDistacePrice.text = ""//"$39.99 $19.99 / Year"
        yearDistacePrice.textAlignment = .center
        scrollView.addSubview(yearDistacePrice)
        
        cancelLabel =  UILabel()
        cancelLabel.font = UIFont.systemFont(ofSize: 12.RW(),weight: .semibold)
        cancelLabel.textColor = UIColor.colorWithHex(hexStr: "#0082FF")
        cancelLabel.text = "Cancel at any time"
        cancelLabel.textAlignment = .center
        scrollView.addSubview(cancelLabel)
        
        payBtn = UIButton()
        payBtn.setTitle("Get discounts", for: .normal)
        payBtn.setTitleColor(.white, for: .normal)
        payBtn.titleLabel?.font = UIFont.systemFont(ofSize: 18.RW(), weight: .semibold)
        payBtn.layer.cornerRadius = 30.RW()
        payBtn.isEnabled = false
        payBtn.addTarget(self, action: #selector(iapPayAction), for: .touchUpInside)
        payBtn.backgroundColor = UIColor.colorWithHex(hexStr: "#0082FF")
        scrollView.addSubview(payBtn)
        
        let termsBtn = UIButton()
        termsBtn.setTitle("Terms", for: .normal)
        termsBtn.titleLabel?.font = UIFont.systemFont(ofSize: 11.RW(),weight: .medium)
        termsBtn.setTitleColor(UIColor.colorWithHex(hexStr: "#999999"), for: .normal)
        termsBtn.titleLabel?.addUnderline()
        termsBtn.addTarget(self, action: #selector(termsAction(btn:)), for: .touchUpInside)
        scrollView.addSubview(termsBtn)
        
 
        
        let recoveryBtn = UIButton()
        recoveryBtn.setTitle("Restore", for: .normal)
        recoveryBtn.titleLabel?.font = UIFont.systemFont(ofSize: 11.RW(),weight: .medium)
        recoveryBtn.setTitleColor(UIColor.colorWithHex(hexStr: "#999999"), for: .normal)
        recoveryBtn.frame = CGRect(x: scrollView.bounds.width - 66, y: ScreenH - (20+kSafeAreaInsets.bottom), width: CGFloat(50.RW()), height: 20)
        recoveryBtn.titleLabel?.addUnderline()
        recoveryBtn.addTarget(self, action: #selector(recoveryBtnAction), for: .touchUpInside)
        scrollView.addSubview(recoveryBtn)
        
        
        let appleLabel =  UILabel()
        appleLabel.font = UIFont.systemFont(ofSize: 10.RW(),weight: .medium)
        appleLabel.textColor = UIColor.colorWithHex(hexStr: "#111111")
        appleLabel.text = " Apple Security Guarantee"
        scrollView.addSubview(appleLabel)
        
        
        closeBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(kSafeAreaInsets.top+20)
            make.size.equalTo(30)
        }
        
//        offerImage.snp.makeConstraints { make in
//            make.centerX.equalToSuperview()
//            make.top.equalTo(kSafeAreaInsets.top+70)
//            make.width.equalTo(111)
//            make.height.equalTo(37)
//        }
//
//        distanceL.snp.makeConstraints { make in
//            make.centerX.equalToSuperview()
//            make.top.equalTo(annual.snp.top).offset(-115.RH())
//        }
//        

        
        appleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.height.equalTo(20)
            make.top.equalToSuperview().offset(ScreenH - (20+kSafeAreaInsets.bottom))
        }
        
        termsBtn.snp.makeConstraints { make in
            make.centerY.equalTo(appleLabel)
            make.left.equalTo(16)
        }

        payBtn.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(343.RW())
            make.height.equalTo(57.RW())
            make.bottom.equalTo(appleLabel.snp.top).offset(-24.RH())
        }
        
//        cancelLabel.snp.makeConstraints { make in
//            make.centerX.equalToSuperview()
//            make.bottom.equalTo(payBtn.snp.top).offset(-22)
//            make.height.equalTo(22)
//        }
//        
//        yearDistacePrice.snp.makeConstraints { make in
//            make.centerX.equalToSuperview()
//            make.bottom.equalTo(cancelLabel.snp.top).offset(0)
//            make.height.equalTo(22)
//        }
//        
//        annual.snp.makeConstraints { make in
//            make.centerX.equalToSuperview()
//            make.bottom.equalTo(yearDistacePrice.snp.top).offset(-8)
//            make.height.equalTo(22)
//        }
        
        
        scrollView.addSubview(termsView)
        termsView.addSubview(privavye_Label)
        
    
        termsView.snp.makeConstraints { make in
            make.left.equalTo(scrollView).offset(16)
            make.right.equalTo(scrollView).offset(-16)
            make.top.equalTo(termsBtn.snp.bottom).offset(15.RH())
            make.height.equalTo(500.RW())
            // 添加这一行确保 termsView 的宽度正确
            make.width.equalTo(scrollView).offset(-32)
        }
           
        privavye_Label.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            // 添加宽度约束确保 label 能正确计算其尺寸
            make.width.equalToSuperview()
        }
        
        view.addSubview(animationView)
        animationView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        animationView.play { completed in
            if completed{
                self.animationView.removeFromSuperview()
                self.setAnim()
            }
        }
        
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
    }
    
   
    func setAnim(){
        
        let dropW = CGFloat(300.RW())
        let dropH = CGFloat(224.RW())
        
//        dropImage.frame = CGRect(x: (ScreenW - dropW) / 2, y: -dropH, width: dropW, height: dropH)
//        
//        offerImage.frame = CGRect(x: (ScreenW - 111) / 2, y: -37, width: 111, height: 37)
//        distanceL.frame = CGRect(x: (ScreenW - 270) / 2, y: -40, width: 270, height: 40)
//        annual.frame = CGRect(x: (ScreenW - 150) / 2, y: -30, width: 150, height: 22)
//        yearDistacePrice.frame = CGRect(x: (ScreenW - 200) / 2, y: -30, width: 200, height: 22)
//        cancelLabel.frame = CGRect(x: (ScreenW - 150) / 2, y: -30, width: 150, height: 22)
        
        self.dropImage.frame = CGRect(x: (ScreenW - dropW)/2.0,
                                      y: kSafeAreaInsets.top + 129.RH(), // 根据原来的约束位置计算
                                    width: dropW,
                                    height: dropH)
        
        self.offerImage.frame = CGRect(x: (ScreenW - 111) / 2,
                                       y: kSafeAreaInsets.top + 70,
                                       width: 111,
                                       height: 37)
        
        self.distanceL.frame = CGRect(x: (ScreenW - 300) / 2,
                                      y: kSafeAreaInsets.top + CGFloat(129.RH()) + dropH + CGFloat(40.RH()),
                                      width: 300,
                                      height: CGFloat(40.RW()))
        
        let topH = 85 + kSafeAreaInsets.top
        
        self.annual.frame = CGRect(x: (ScreenW - 150) / 2,
                                   y: self.distanceL.frame.maxY + CGFloat(85.RH()),
                                   width: 150,
                                   height: 22)
        
        self.yearDistacePrice.frame = CGRect(x: (ScreenW - 200) / 2,
                                             y: self.annual.frame.maxY + 8,
                                             width: 200,
                                             height: 22)
        
        self.cancelLabel.frame = CGRect(x: (ScreenW - 200) / 2,
                                        y: self.yearDistacePrice.frame.maxY,
                                        width: 200,
                                        height: 22)
        
        payBtn.alpha = 0
        dropImage.alpha = 0
        offerImage.alpha = 0
        distanceL.alpha = 0
        annual.alpha = 0
        yearDistacePrice.alpha = 0
        cancelLabel.alpha = 0
        UIView.animate(withDuration: 1) {
            self.payBtn.alpha = 1
            self.dropImage.alpha = 1
            self.offerImage.alpha = 1
            self.distanceL.alpha = 1
            self.annual.alpha = 1
            self.yearDistacePrice.alpha = 1
            self.cancelLabel.alpha = 1
        }
        
        
        
        // 添加重力动画效果
//        UIView.animate(withDuration: 1.1,
//                      delay: 0.2,
//                      usingSpringWithDamping: 0.5, // 弹性系数，越小弹性越大
//                      initialSpringVelocity: 0.8,  // 初始速度
//                      options: .curveEaseIn,
//                      animations: {
//            // 设置最终位置
//            self.dropImage.frame = CGRect(x: (ScreenW - dropW)/2.0,
//                                          y: kSafeAreaInsets.top + 129.RH(), // 根据原来的约束位置计算
//                                        width: dropW,
//                                        height: dropH)
//            
//            self.offerImage.frame = CGRect(x: (ScreenW - 111) / 2,
//                                           y: kSafeAreaInsets.top + 70,
//                                           width: 111,
//                                           height: 37)
//            
//            self.distanceL.frame = CGRect(x: (ScreenW - 270) / 2,
//                                          y: kSafeAreaInsets.top + CGFloat(129.RH()) + dropH + CGFloat(40.RH()),
//                                          width: 270,
//                                          height: 40)
//            
//            self.annual.frame = CGRect(x: (ScreenW - 150) / 2,
//                                       y: self.distanceL.frame.maxY + CGFloat(115.RH()),
//                                       width: 150,
//                                       height: 22)
//            
//            self.yearDistacePrice.frame = CGRect(x: (ScreenW - 200) / 2,
//                                                 y: self.annual.frame.maxY + 8,
//                                                 width: 200,
//                                                 height: 22)
//            
//            self.cancelLabel.frame = CGRect(x: (ScreenW - 150) / 2,
//                                            y: self.yearDistacePrice.frame.maxY,
//                                            width: 150,
//                                            height: 22)
//        }, completion: nil)
        
//        offerImage.frame = CGRect(x: (ScreenW - 111) / 2, y: -37, width: 111, height: 37)
//        distanceL.frame = CGRect(x: (ScreenW - 270) / 2, y: -40, width: 270, height: 40)
//        annual.frame = CGRect(x: (ScreenW - 150) / 2, y: -30, width: 150, height: 22)
//        yearDistacePrice.frame = CGRect(x: (ScreenW - 200) / 2, y: -30, width: 200, height: 22)
//        cancelLabel.frame = CGRect(x: (ScreenW - 150) / 2, y: -30, width: 150, height: 22)
//           
//           // 添加下落动画
//        UIView.animate(withDuration: 0.3,
//                         delay: 0, // 稍微延迟一点，让动画错开
//                         options: .curveEaseOut) {
//            // 设置最终位置
//            self.offerImage.frame = CGRect(x: (ScreenW - 111) / 2,
//                                           y: kSafeAreaInsets.top + 70,
//                                           width: 111,
//                                           height: 37)
//            
//            self.distanceL.frame = CGRect(x: (ScreenW - 270) / 2,
//                                          y: kSafeAreaInsets.top + CGFloat(129.RH()) + dropH + CGFloat(40.RH()),
//                                          width: 270,
//                                          height: 40)
//            
//            self.annual.frame = CGRect(x: (ScreenW - 150) / 2,
//                                       y: self.distanceL.frame.maxY + CGFloat(115.RH()),
//                                       width: 150,
//                                       height: 22)
//            
//            self.yearDistacePrice.frame = CGRect(x: (ScreenW - 200) / 2,
//                                                 y: self.annual.frame.maxY + 8,
//                                                 width: 200,
//                                                 height: 22)
//            
//            self.cancelLabel.frame = CGRect(x: (ScreenW - 150) / 2,
//                                            y: self.yearDistacePrice.frame.maxY,
//                                            width: 150,
//                                            height: 22)
//              
//        }
              
        
        // 添加呼吸动画
         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)
         payBtn.layer.add(breathAnimation, forKey: "breathingAnimation")
  
    }
    
    func reloadSKPorduct(){

        IAPManager.share.fetchProducts { [weak self] products in
            guard let weakSelf = self else { return }
            DispatchQueue.main.async {
                if let (_,lifetimeProduct,yearProduct) = products {
                    weakSelf.year = yearProduct
                    weakSelf.life = lifetimeProduct
                    weakSelf.reloadSKUI()
                }
            }
        }
    }
    
    func reloadSKUI(){
        
        guard let year = year,let life = life else{
            payBtn.isEnabled = false
            return
        }
        payBtn.isEnabled = true
        let priceAtt = createRichPriceText(
            originalPrice: "\(life.localizedPrice)",
            discountedPrice: "\(year.localizedPrice) / Year"
        )
        yearDistacePrice.attributedText = priceAtt
        
    }
    
    lazy var termsView:UIView = {
        let termsView = UIView()
        termsView.backgroundColor = .clear
        return termsView
    }()
    
    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(_:)))
        tap.delegate = self
        tap.cancelsTouchesInView = false  // 添加这一行
        priva.addGestureRecognizer(tap)
        return priva
    }()
    
    
    lazy var animationView:LottieAnimationView = {
        let animationView = LottieAnimationView(name: "discount")
        animationView.loopMode = .playOnce
        animationView.contentMode = .scaleAspectFill
        return animationView
    }()

}


extension PayDistanceViewController{
    
    @objc func payClose(){
        
        self.dismiss(animated: true)
        
    }
    
    @objc func iapPayAction(){
        
        IAPManager.share.purchase(.yearSubscribe) {[weak self] result in
            guard let weakSelf = self else { return }
            switch result {
            case .success(_):
                DispatchQueue.main.async {
                    SVProgressHUD.showSuccess(withStatus: "purchase succeeds")
                    weakSelf.dismiss(animated: true)
                }
            case .failure(let failure):
                DispatchQueue.main.async {
                    SVProgressHUD.showError(withStatus: failure.localizedDescription)
                }
            }
        }
    }
    
    
    func createRichPriceText(originalPrice: String, discountedPrice: String) -> NSAttributedString {
        // 创建可变属性字符串
        let attributedString = NSMutableAttributedString()
        
        // 1. 设置原价部分（带删除线）
        let originalPriceAttributes: [NSAttributedString.Key: Any] = [
            .foregroundColor: UIColor.colorWithHex(hexStr: "#111111", alpha: 0.6),
            .strikethroughStyle: NSUnderlineStyle.single.rawValue,
            .font: UIFont.systemFont(ofSize: 14,weight: .semibold)
        ]
        let originalPricePart = NSAttributedString(string: originalPrice, attributes: originalPriceAttributes)
        attributedString.append(originalPricePart)
        
        // 2. 添加空格分隔
        attributedString.append(NSAttributedString(string: " "))
        
        // 3. 设置折扣价部分（无删除线）
        let discountedPriceAttributes: [NSAttributedString.Key: Any] = [
            .foregroundColor: UIColor.colorWithHex(hexStr: "#111111"),
            .font: UIFont.systemFont(ofSize: 14, weight: .semibold)
        ]
        let discountedPricePart = NSAttributedString(string: discountedPrice, attributes: discountedPriceAttributes)
        attributedString.append(discountedPricePart)
        
        return attributedString
    }
    
    @objc func termsAction(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)
        }
        let contentH =  attribtit.length > 0 ? 500.RW() : 0
        
       // self.scrollView.contentSize = CGSizeMake(ScreenW, contentH + ScreenH)
        
        self.scrollView.contentSize = CGSize(width: self.scrollView.frame.width, height: contentH + ScreenH)
        
        privavye_Label.attributedText = attribtit

       // privavye_Label.frame = CGRect(x: 16, y: ScreenH+20, width: ScreenW-32, height: contentH)
        Print("scrollView frame:", scrollView.frame)
        Print("scrollView contentSize:", scrollView.contentSize)
        Print("termsView frame:", termsView.frame)
        Print("privavye_Label frame:", privavye_Label.frame)
//        view.layoutIfNeeded()
//        if privavye_Label.attributedText?.length ?? 0 > 10 {
//            UIView.animate(withDuration: 0.1) {
//                self.scrollView.contentOffset = CGPoint(x: 0, y: self.scrollView.contentSize.height - self.scrollView.height)
//            }
//        }
    }
    
    @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 ?? UIFont.scaledSystemFont(ofSize: 14, weight: .regular)], 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("点击了隐私")
            ppClick()
        }else if frame2.contains(location){
            Print("点击了terms")
            touClick()
        }
    }
    
    private func ppClick() {
        DispatchQueue.main.async {[weak self] in
            guard let self else {return}
            let vc:PrivacyPolicyWebViewController = PrivacyPolicyWebViewController()
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    private func touClick() {
        DispatchQueue.main.async {[weak self] in
            guard let self else {return}
            let vc:TermOfUseWebViewController = TermOfUseWebViewController()
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
 
    
    @objc func recoveryBtnAction(){
        IAPManager.share.restore { result in
            
        }
    }
}


// 在文件末尾添加
extension PayDistanceViewController: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        // 允许手势同时识别
        return true
    }
}
