//
//  ChargeInfoViewController.swift
//  PhoneManager
//
//  Created by edy on 2025/3/26.
//

import UIKit

class ChargeInfoViewController:BaseViewController {
    
    enum ChargeInfoType {
        case setting
        case charge
    }
    
    var model:ChargeDataModel?
    
    var type:ChargeInfoType?
    
    var flag : Int?
    
    var isShowBack:Bool? {
        
        didSet {
            
            changeTitleView()
        }
    }
    
    var isShowSettingView:Bool? {
        
        didSet {
            
            changeSettingViews()
        }
    }
    
    lazy var backImageView:ChargeInfoBackView = {
        
        let sview:ChargeInfoBackView = ChargeInfoBackView(frame: view.bounds, model: self.model!)
        sview.model = self.model
        return sview
    }()
    
    lazy var settingView:ChargeInfoSettingView = {
        
        let sview:ChargeInfoSettingView = ChargeInfoSettingView(frame: CGRect(x: 0, y: 0, width: view.width, height: 78 + safeHeight))
        sview.model = self.model
        sview.flag = self.flag
        sview.isHidden = type == .setting ? false : true
        
        sview.settingCallBack = {isFree,flag in
            // 如果是pro用户或者是免费的或者已经设置过的
            if UserDefaults.standard.object(forKey: "chargePicInfo") != nil {
                let save : String = UserDefaults.standard.object(forKey: "chargePicInfo") as! String
                if Int(save) == flag {
                    self.setAnimation()
                    return
                }
            }
            
            if IAPManager.share.isSubscribed == false && isFree != true {
                
                // 弹出内购页面
                HomePayViewController.show {
                    // 再次判断下
                    if IAPManager.share.isSubscribed == false {
                        // 弹出提示框
                        let alertView = AdvTipSelectView()
                        alertView.selectType = .selectTypeSetAnimation
                        alertView.getOtherInfoByType()
                        alertView.modalPresentationStyle = .overFullScreen
                        self.view.showBlur()
                        self.present(alertView, animated: true)
                        alertView.selectClickCallback = {isSure in
                            alertView.dismiss(animated: true) {
                                self.view.hideBlur()
                                if isSure {
                                    self.popAdverTisement()
//                                    AdvManager.shared.finisedCallBack = {
//                                        self.setAnimation()
//                                    }
                                }
                            }
                        }
                    }else{
                        self.setAnimation()
                    }
                }
            }else {
                self.setAnimation()
            }
        }
        
        return sview
    }()
    
    init(model: ChargeDataModel?,type:ChargeInfoType?) {
        self.type = type
        self.model = model
        super.init(nibName: nil, bundle: nil)
    }
    
    // 由于继承自 UIViewController，必须实现这个必需的构造器
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        self.barHidden = true
        
        titleView.model.title = ""
        
        titleView.lineView.isHidden = true
        
        titleView.backgroundColor = .clear
        
        if type == .charge {
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: {[weak self] in
                
                guard let self else {return}
                
                isShowBack = true
            })
        }
    }
    
    override func addViews() {
        
        view.addSubview(backImageView)
        
        view.addSubview(titleView)
        
        view.addSubview(settingView)
    }
    
    func changeSettingViews() {
        
        if type == .charge {
            
            return
        }
        
        DispatchQueue.main.async {
            
            if !(self.isShowSettingView ?? false) {
                
                self.settingView.isHidden = false
            }
            
            UIView.animate(withDuration: 0.3, animations: {[weak self] in
                guard let self else {return}
                self.settingView.alpha = (self.isShowSettingView ?? false) ? 0 : 1
            }, completion: {[weak self] _ in
                guard let self else {return}
                self.settingView.isHidden = self.isShowSettingView ?? false
            })
        }
    }
    
    func changeTitleView() {
        
        if !(self.isShowBack ?? false) {
            
            self.titleView.isHidden = false
        }
        
        UIView.animate(withDuration: 0.3, animations: {[weak self] in
            guard let self else {return}
            self.titleView.alpha = (self.isShowBack ?? false) ? 0 : 1
        }, completion: {[weak self] _ in
            guard let self else {return}
            self.titleView.isHidden = self.isShowBack ?? false
        })
    }
    
    override func viewWillLayoutSubviews() {
        
        super.viewWillLayoutSubviews()
        
        backImageView.snp.makeConstraints { make in
            
            make.center.width.height.equalToSuperview()
        }
        
        settingView.snp.makeConstraints { make in
            
            make.bottom.width.centerX.equalToSuperview()
            make.height.equalTo(safeHeight + (safeHeight == 0 ? 78 : 68))
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        isShowSettingView = !(isShowSettingView ?? false)
        isShowBack = !(isShowBack ?? false)
    }
    
    
    func setAnimation(){
        // 存储到userDefaults
        UserDefaults.standard.set(String(self.flag!), forKey: "chargePicInfo")
        
        let alert = UIAlertController(title: nil, message: "Done！", preferredStyle: .alert)
        self.present(alert, animated: true, completion: nil)
        
        // 2 秒后关闭弹窗
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            alert.dismiss(animated: true, completion: nil)
            
            // 是否是第一次进入
            let chargeGuideFinished = UserDefaults.standard.object(forKey: "ChargeGuideFinished")
            if chargeGuideFinished == nil {
                let vc : ChargeGuideStartController = ChargeGuideStartController()
                let navigation = UINavigationController(rootViewController: vc)
                navigation.modalPresentationStyle = .fullScreen
                self.present(navigation, animated: true)
//                let vc : ChargeGuideStartController = ChargeGuideStartController()
//                vc.modalPresentationStyle = .fullScreen
//                self.present(vc, animated: true)
//                vc.callback = {[weak self] text in
//                    guard let self else {return}
//                    let vc : ChargeGuideController = ChargeGuideController()
//                    self.navigationController?.pushViewController(vc, animated: true)
//                }
                
                UserDefaults.standard.set("ChargeGuideFinished", forKey: "ChargeGuideFinished")
            }else{
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
    
    
    /// 弹出广告
    func popAdverTisement(){
        //AdvManager.shared.showRewardedInterstitialAd(vc: self,from:"charge")
        ADManager.shared.showRewardedInterstitialAd(from: ADShowTypeEnum.Charge.name) {
            self.setAnimation()
        } showFailBlock: { error in
            
        }

    }

}
