//
//  ViewController.swift
//  QuickSearchLocation
//
//  Created by mac on 2024/4/10.
//

import UIKit
import Alamofire

class ViewController: UIViewController {
    private var timer: Timer?
    private var count = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.checkNetwork()
        self.setUI()
    }
    
    @objc private func updateCountdown() {
        if(count > 6){
            self.contentLabel.isHidden = false
            self.oneButton.isHidden = false
            invalidateTimer()
        }
        count += 1
        
    }
    
    private func invalidateTimer() {
        timer?.invalidate()
        timer = nil
    }
    
    func setUI(){
        if timer == nil {
            timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCountdown), userInfo: nil, repeats: true)
            RunLoop.current.add(timer!, forMode: .common)
        }
        
        self.view.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(131)
        }

        self.view.addSubview(bgLogoView)
        bgLogoView.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 96, height: 96))
            make.centerX.equalToSuperview()
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top).offset(130)
        }
        
        self.view.addSubview(bgTitleView)
        bgTitleView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(96)
            make.right.equalToSuperview().offset(-96)
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom).offset(-40)
            make.height.equalTo(bgTitleView.snp.width).multipliedBy(156.0/501.0)
        }
        
        self.view.addSubview(contentLabel)
        contentLabel.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: QSLConst.qsl_kScreenW, height: 18.0.rpx))
            make.center.equalToSuperview()
        }
        
        self.view.addSubview(oneButton)
        oneButton.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 140.rpx, height: 44.rpx))
            make.centerX.equalToSuperview()
            make.top.equalTo(contentLabel.snp.bottom).offset(20.rpx)
        }
        
        self.contentLabel.isHidden = true
        self.oneButton.isHidden = true
        
    }
    
    @objc func checkNetworkSetting(){
        if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
            
            UIApplication.shared.open(url)
        }
    }
    
    @objc func checkNetwork(){
        NetworkReachabilityManager.default?.startListening(onUpdatePerforming: {[weak self] status in
            if(status != .notReachable){
                print("checkIDFA")
                UNUserNotificationCenter.current().requestAuthorization(
                    options: [.alert, .sound, .badge]
                ) { granted, error in
                    DispatchQueue.main.async {
                        if granted {
                            DispatchQueue.main.async {
                                UIApplication.shared.registerForRemoteNotifications()
                            }
                        } else if let error = error {
                            print("Error: \(error.localizedDescription)")
                        }

                        self?.intoMain()
                    }
                }
                NetworkReachabilityManager.default?.stopListening()
                self?.invalidateTimer()
            }
        })
    }
    
    func intoMain() {
        self.contentLabel.isHidden = true
        self.oneButton.isHidden = true
        QSLBaseManager.shared.initConfig()
        
        // 是否通过引导页
//        let isShowGuideKey = UserDefaults.standard.bool(forKey: "isShowGuideKey")
//        if !isShowGuideKey {
//            // 引导页
//            UserDefaults.standard.set(true, forKey: "isShowGuideKey")
//            if let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate {
//                sceneDelegate.window?.rootViewController = QSLGuideController()
//                sceneDelegate.window?.makeKeyAndVisible()
//            }
//        } else {
            UNUserNotificationCenter.current().requestAuthorization(
                options: [.alert, .sound, .badge]
            ) { granted, error in
                DispatchQueue.main.async {
                    if granted {
                        DispatchQueue.main.async {
                            UIApplication.shared.registerForRemoteNotifications()
                        }
                    } else if let error = error {
                        print("Error: \(error.localizedDescription)")
                    }
                }
            }
            
            QSLBaseManager.shared.initIDFA()
            // 主页
            if let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate {
                sceneDelegate.window?.rootViewController = CustomTabBarController()
                sceneDelegate.window?.makeKeyAndVisible()
            }
//        }
        
    }
    
    lazy var bgView: UIImageView = {
        let item = UIImageView()
        item.image = UIImage(named: "launch_bottom_bg")
        item.contentMode = .scaleToFill
        return item
    }()
    
    lazy var bgLogoView: UIImageView = {
        let item = UIImageView()
        item.image = UIImage(named: "launch_icon")
        item.contentMode = .scaleToFill
        return item
    }()
    
    lazy var bgTitleView: UIImageView = {
        let item = UIImageView()
        item.image = UIImage(named: "launch_title")
        item.contentMode = .scaleToFill
        return item
    }()
    
    lazy var contentLabel: UILabel = {
        let label = UILabel()
        label.text("网络错误，请检查网络权限")
        label.font(16)
        label.textColor = .black
        label.textAlignment = .center
        return label
    }()
    
    lazy var oneButton: UIButton = {
      
        let btn = UIButton()
        btn.addRadius(radius: 22.rpx)
        btn.title("去设置")
        btn.textColor(.white)
        btn.mediumFont(14)
        btn.gradientBackgroundColor(color1: .hexStringColor(hexString: "#15CBA1"), color2: .hexStringColor(hexString: "#1FE0BA"), width: 250.rpx, height: 44.rpx, direction: .horizontal)
        btn.addTarget(self, action: #selector(checkNetworkSetting), for: .touchUpInside)
        return btn
    }()
    
    
    // 用户协议跳转
    func agreementAction() {
        
        let vc = QSLWebViewController()
        vc.webUrl = QSLConfig.AppServiceAgreementLink
        vc.title = "用户协议"
        vc.isShowTop = true
        self.present(vc, animated: true)
    }
    
    // 隐私协议跳转
    func privacyAction() {
        
        let vc = QSLWebViewController()
        vc.webUrl = QSLConfig.AppPrivacyAgreementLink
        vc.title = "隐私政策"
        vc.isShowTop = true
        self.present(vc, animated: true)
    }
}
