//
//  PermissionViewController.swift
//  PhoneManager
//
//  Created by zxhy on 2025/3/19.
//

import UIKit
import Lottie
import Foundation
import AppTrackingTransparency

class PermissionVC:UIViewController {
    
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var animationBackView: UIView!
    
    @IBOutlet weak var tipLabel: UILabel!
    @IBOutlet weak var bottomTextView: UITextView!
    @IBOutlet weak var nextButton: UIButton!
    
    private var isPPClick:Bool = false
    
    private var isTOUClick:Bool = false
    
    private var isNextClick:Bool = false
    
    lazy var animationView:LottieAnimationView = {
        
        let animationView = LottieAnimationView(name: "onboardingStorageLight")
        
        animationView.play(fromProgress: 0.0, toProgress: 0.7, loopMode: .playOnce) { finished in
            print("Animation finished at 80%")
        }
        return animationView
    }()

    override func viewDidLoad() {
        
        super.viewDidLoad()
        view.backgroundColor = .white
        checkTrackingAuthorization()
        setupUI()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        
        super.viewDidAppear(animated)
        
        navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        
        isPPClick = false
        
        isTOUClick = false
    }
    
    func setupUI() {
        
        titleLabel.font = UIFont.systemFont(ofSize: 24, weight: .bold)
        titleLabel.textColor = UIColor.colorWithHex(hexStr: black3Color)
        titleLabel.width = 183
        titleLabel.numberOfLines = 2
        titleLabel.text = "Welcome to PhoneManager"
        
        // 创建 NSMutableAttributedString
        
        titleLabel.setlineSpacing(font: titleLabel.font, lineSpacing: 8,width: titleLabel.width,numberOfLines: 2, content: titleLabel.text ?? "")
        titleLabel.textAlignment = .center
        titleLabel.centerX = view.width / 2
        
        animationView.frame = animationBackView.bounds
        animationBackView.addSubview(animationView)
        
        tipLabel.font = UIFont.systemFont(ofSize: 20, weight: .medium) // 设置字体大小和粗体
        tipLabel.textAlignment = .center // 设置对齐方式（可选）
        
        // 创建 NSAttributedString
        
        let disk = WidgetPublicModel.getDiskSpace()
        let all = String(format: "%.1f" ,CGFloat(disk.0)/(1000.0 * 1000.0 * 1000.0))
        let use = String(format: "%.1f" ,CGFloat(disk.0 - disk.1)/(1024.0 * 1024.0 * 1024.0))
        
        let text = "\(use) of \(all) GB used"
        let attributedString = NSMutableAttributedString(string: text)
        
        // 设置整体颜色为 #333333
        attributedString.addAttribute(.foregroundColor, value: UIColor(red: 51/255, green: 51/255, blue: 51/255, alpha: 1.0), range: NSRange(location: 0, length: text.count))
        
        // 设置 "used" 的颜色为 #E73A3A
        if let range = text.range(of: "used") {
            let nsRange = NSRange(range, in: text)
            
            attributedString.addAttribute(.foregroundColor, value: UIColor(red: 231/255, green: 58/255, blue: 58/255, alpha: 1.0), range: nsRange)
        }
        
        // 将 NSAttributedString 赋值给 UILabel
        tipLabel.attributedText = attributedString
        
        bottomTextView.isEditable = false
        bottomTextView.isScrollEnabled = false
        bottomTextView.backgroundColor = .clear
        
        bottomTextView.delegate = self
        
        let fullText = "PhoneManager needs access to your Photos to free up storage. We intend to provide transparency and protect your privacy. By starting you accept our Terms of Use and Privacy Policy."
        let termsText = "Terms of Use"
        let privacyText = "Privacy Policy"
        
        let attributedString2 = NSMutableAttributedString(string: fullText, attributes: [
            .font: UIFont.systemFont(ofSize: 14),
            .foregroundColor: UIColor.colorWithHex(hexStr: "#666666")
        ])
        
        let termsRange = (fullText as NSString).range(of: termsText)
        let privacyRange = (fullText as NSString).range(of: privacyText)
        
        attributedString2.addAttributes([
            .foregroundColor: UIColor.colorWithHex(hexStr: "#0082FF"),
            .underlineStyle: NSUnderlineStyle.single.rawValue,
            .link:"terms://termsOfUse"
        ], range: termsRange)
        
        attributedString2.addAttributes([
            .foregroundColor: UIColor.colorWithHex(hexStr: "#0082FF"),
            .underlineStyle: NSUnderlineStyle.single.rawValue,
            .link: "privacy://privacyPolicy"
        ], range: privacyRange)
        
        bottomTextView.gestureRecognizers?.forEach { gestureRecognizer in
            if gestureRecognizer is UILongPressGestureRecognizer {
                // 移除长按手势
                bottomTextView.removeGestureRecognizer(gestureRecognizer)
            }
        }
        
        bottomTextView.gestureRecognizers?.forEach { gestureRecognizer in
            if gestureRecognizer is UILongPressGestureRecognizer {
                // 禁用长按和双击手势
                gestureRecognizer.isEnabled = false
            }
            
            if let tapGesture = gestureRecognizer as? UITapGestureRecognizer {
                // 判断是否是双击手势
                if tapGesture.numberOfTapsRequired == 2 {
                    tapGesture.isEnabled = false // 禁用双击手势
                }
            }
        }
        bottomTextView.attributedText = attributedString2
        bottomTextView.textAlignment = .center
        bottomTextView.linkTextAttributes = [:]  // 取消默认 link 颜色
        
        nextButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .bold)
    }
    
    @IBAction func gerstartedClick(_ sender: Any) {
        
//        PhotoAndVideoMananger.getPrivacy {[weak self] status in
//            
//            guard let self else {return}
//            
//            if let photoStatus = status as? PrivacyType {
//                
//                switch photoStatus {
//                    
//                case .authorized,.denied,.restricted:
//                    self.gotoNext()
//                case .notDetermined: break
//                }
//            }
//        }
        
        self.gotoNext()
        
    }
    
    private func gotoNext() {
        
        guard isNextClick == false else{
            return
        }
        
        isNextClick = true
        
        DispatchQueue.main.async {[weak self] in
            guard let self else {return}
            let vc = NewGuideViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        }

    }
    
    private func ppClick() {
        
        if (!isPPClick) {
            
            isPPClick = true
            
            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() {
        
        if (!isTOUClick) {
            
            isTOUClick = true
            
            DispatchQueue.main.async {[weak self] in
                
                guard let self else {return}
                
                let vc:TermOfUseWebViewController = TermOfUseWebViewController()
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
        
    }
    
}

extension PermissionVC: UITextViewDelegate {
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if URL.scheme == "terms" {
            touClick()
            // 处理 Terms of Use 点击事件
            return false // 阻止默认行为（打开链接）
        } else if URL.scheme == "privacy" {
            ppClick()
            // 处理 Privacy Policy 点击事件
            return false // 阻止默认行为（打开链接）
        }
        return true
    }
    
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        // 禁用所有菜单选项
        return false
    }
}


extension PermissionVC {
    
    // 检查跟踪授权状态
    func checkTrackingAuthorization() {
        if #available(iOS 14, *) {
            let status = ATTrackingManager.trackingAuthorizationStatus
            switch status {
            case .authorized:
                // 用户已授权跟踪
                print("用户已授权应用进行跟踪")
                Print("idfa",ADManager.shared.getIDFA())
            case .denied:
                // 用户拒绝了跟踪请求
                print("用户拒绝了应用的跟踪请求")
            case .restricted:
                // 由于系统限制，无法跟踪用户
                print("由于系统限制，无法跟踪用户")
            case .notDetermined:
                // 用户尚未对跟踪请求做出决定
                print("用户尚未对跟踪请求做出决定，再次请求授权")
                requestTrackingAuthorization()
            @unknown default:
                break
            }
        } else {
            // iOS 14 以下系统不支持 ATT 框架
            // 可以执行其他操作
        }
    }
    func requestTrackingAuthorization() {
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
                switch status {
                case .authorized:
                    // 用户已授权跟踪
                    print("用户已授权应用进行跟踪")
                    Print("idfa",ADManager.shared.getIDFA())
                case .denied:
                    // 用户拒绝了跟踪请求
                    print("用户拒绝了应用的跟踪请求")
                case .restricted:
                    // 由于系统限制，无法跟踪用户
                    print("由于系统限制，无法跟踪用户")
                case .notDetermined:
                    // 用户尚未对跟踪请求做出决定
                    print("用户尚未对跟踪请求做出决定")
                @unknown default:
                    break
                }
            })
        } else {
            // iOS 14 以下系统不支持 ATT 框架
            // 可以执行其他操作
        }
    }
}
