//
//  YHStartPageViewController.swift
//  galaxy
//
//  Created by davidhuangA on 2024/4/7.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import ESTabBarController_swift
/*
 启动页 自带倒计时
 */

class YHStartPageViewController: UIViewController {
    
    private var MaxTime : Int = 3
    private var timer : Timer?
    
    lazy var imagV: UIImageView = {
        let imagV  = UIImageView()
        imagV.contentMode = .scaleAspectFill
        return imagV
    }()
    
    lazy var closeBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_R(ofSize: 12)
        button.setTitle("跳过 3", for: .normal)
        button.setTitleColor( UIColor(hex:0xffffff), for: .normal)
        button.setBackgroundColor(color: UIColor(red: 0.071, green: 0.102, blue: 0.149, alpha: 0.3), forState: .normal)
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initView()
    }
    
    lazy var agreeAlertView : YHAgreementAlertView = {
       let view = YHAgreementAlertView()
        view.isHidden = true
        return view
    }()
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
}


private extension YHStartPageViewController {
    
    func cancelTimer() {
        guard self.timer != nil else {
            return
        }
        self.timer!.invalidate()
        self.timer = nil
    }
    
    
    func startTimer() {
        cancelTimer()
        self.timer = Timer.scheduledTimer(timeInterval: TimeInterval(1), target: self, selector: #selector(downTimerOp), userInfo: nil, repeats:  true)
        RunLoop.current.add(self.timer!, forMode: .common)
    }
    
    @objc func downTimerOp() {
        MaxTime = MaxTime - 1
        if MaxTime < 0 {
            cancelTimer()
            clickCancelBtn()
            return
        }
        
        let title = "跳过 " + MaxTime.string
        closeBtn.setTitle(title, for: .normal)
    }
    
    func initView() {
        gk_navigationBar.isHidden = true
        
        imagV.image = UIImage(named: "start_page_bkg")
        view.addSubview(imagV)
        imagV.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        view.addSubview(closeBtn)
        closeBtn.layer.zPosition = 10
        closeBtn.clipsToBounds = true
        closeBtn.layer.cornerRadius = 14
        closeBtn.snp.makeConstraints { make in
            make.top.equalTo(k_Height_safeAreaInsetsTop() + 15)
            make.right.equalTo(-20)
            make.width.equalTo(56)
            make.height.equalTo(28)
        }
        closeBtn.addTarget(self, action: #selector(clickCancelBtn), for: .touchUpInside)
        
        view.addSubview(agreeAlertView)
        agreeAlertView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(forceUpdateOp), name: YhConstant.YhNotification.didForceUpgradeNotifiction, object: nil)
        
        if let key = UserDefaults.standard.value(forKey: "userAgreeProtocal") as? String,key.contains("true") {
            let dateString = Date().dateString(ofStyle: .short)
            UserDefaults.standard.set(dateString, forKey: "todayShowStartPageViewFlag")
            UserDefaults.standard.synchronize()
            
            startTimer()
        } else {
            agreeAlertView.isHidden = false
            cancelTimer()
            closeBtn.isHidden = true
            agreeAlertView.agreeBlock = {
                UserDefaults.standard.set("true", forKey: "userAgreeProtocal")
                UserDefaults.standard.synchronize()
                self.closeBtn.isHidden = false
                self.startTimer()
                
                
                
                let dateString = Date().dateString(ofStyle: .short)
                UserDefaults.standard.set(dateString, forKey: "todayShowStartPageViewFlag")
                UserDefaults.standard.synchronize()
            }
            
            agreeAlertView.cancelBlock = {
                //点击了取消按钮
                YHCommonAlertView.show("", "确认退出银河港生活?", "退出", "继续使用",fullGuestureEnable: false) {
                    //退出
                    exit(0)
                } callBack: {
                    //继续使用
                    self.view.addSubview(self.agreeAlertView)
                    self.agreeAlertView.snp.makeConstraints { make in
                        make.edges.equalToSuperview()
                    }
                    
                    self.agreeAlertView.isHidden = false
                    self.cancelTimer()
                    self.closeBtn.isHidden = true
                }
            }
            
            
            agreeAlertView.urlBlock = { [weak self] url,tag in
                guard let self = self else { return }
                let vc = YHWebViewViewController()
                vc.url = url
                if tag == 0 {
                    vc.navTitle = "银河港生活隐私协议"
                } else if tag == 1 {
                    vc.navTitle = "银河港生活用户条款"
                }
                
                self.navigationController?.pushViewController(vc)
            }
            
        }
    }
    
    @objc func clickCancelBtn() {
        cancelTimer()
        setupRootVC()
    }
    
    @objc func forceUpdateOp() {
        cancelTimer()
        agreeAlertView.isHidden = true
        closeBtn.isHidden = true
    }
    
    //1.设置主窗口
    func setupRootVC() {
        
        gk_navigationBar.isHidden = false
    
        let window = UIApplication.shared.yhKeyWindow()
        window?.rootViewController = configTabBarController()
        window?.makeKeyAndVisible()
        
        if YHLoginManager.shared.needJumpToMsgTabFlag {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: {
                goToMessagePage()
            })
        }
    }
}
