//
//  AV_MineVC.swift
//  anniversary_Project
//
//  Created by 忆海16 on 2024/4/11.
//

import UIKit
import FSCalendar
//import FirebaseAnalytics
import AppLovinSDK
import Alamofire
import FirebaseRemoteConfig

class AV_MineVC: AV_RootVC {
    

    
    @IBOutlet weak var calendarV: FSCalendar!
    
    @IBOutlet weak var TitleLabel: UILabel!
    
    
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var countLabel: UILabel!
    
    
    @IBOutlet weak var noneImagV: UIImageView!
    
    var interstitialAd: MAInterstitialAd!
    var remoteConfig: RemoteConfig!
    var isadshow:Bool = false
    var retryAttempt = 0.0
    
    var arr = [UserModel]()
    
    var arrdate = [UserModel]()
    
//    var ispushView:Bool = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setbackBtn()
        setTableView()
        calendarV.dataSource = self
        calendarV.delegate = self

        let currentDate = Date()
        let formatter = DateFormatter()
        formatter.dateFormat = "MMMM yyyy"
        TitleLabel.text = formatter.string(from: currentDate)
        
        // 添加对currentPage属性的观察者
        calendarV.addObserver(self, forKeyPath: "currentPage", options: .new, context: nil)
        
      

    }
    
    // 实现观察者方法，响应currentPage属性的变化
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "currentPage" {
            if let newDate = change?[.newKey] as? Date {
                let formatter = DateFormatter()
                formatter.dateFormat = "MMMM yyyy"
                let monthYearString = formatter.string(from: newDate)
                TitleLabel.text = monthYearString
            }
        }
    }
    
    func setbackBtn(){
        
        let backButton = UIButton(type: .custom)
        
        
        backButton.setBackgroundImage(#imageLiteral(resourceName: "back"), for: .normal)
        
        backButton.addTarget(self, action: #selector(back), for: .touchUpInside)
        
        
        let backView = UIBarButtonItem(customView: backButton)
        
        let barButtonItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        barButtonItem.width = -5
        
        
        navigationItem.leftBarButtonItems = [barButtonItem, backView]
        
    }
    
    @objc func back(){
//        navigationController?.popViewController(animated: true)
        if self.isadshow == true{
            DispatchQueue.main.asyncAfter(wallDeadline: .now() + 0.5) {
                
                if self.interstitialAd.isReady {
                    self.interstitialAd.show()
                    self.setPostSHOW()
                    
                }else{
                    self.navigationController?.popViewController(animated: true)
                }
            }
        }else{
            self.navigationController?.popViewController(animated: true)
        }
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.createInterstitialAd()
        remoteConfig = RemoteConfig.remoteConfig()
        
        
        
        // 设置最小获取间隔（开发期间可以设置较小的值）
        let settings = RemoteConfigSettings()
        settings.minimumFetchInterval = 0
        remoteConfig.configSettings = settings
        // Fetch 配置值
        remoteConfig.setDefaults(fromPlist: "isopen")
        fetchRemoteConfig()
        self.navigationController?.navigationBar.isHidden = false
        calendarV.reloadData()
        
        let users = PrWCDBBaseManager.shared.qureyFromDb(fromTable: userModelTableName, cls: UserModel.self)
        if let users = users {
            self.arr = users
            print("---\(users)")
        } else {
            
        }
        
        selectDateManually(Date())
        
        self.countLabel.text = "My Task \(self.arrdate.count)"
        
        updateUI()
        
    }
    
    func updateUI() {
          if arrdate.isEmpty {
              noneImagV.isHidden = false
          } else {
              noneImagV.isHidden = true
          }
          tableView.reloadData()
      }
    
    func parseUserModelsFromArray(_ users: [UserModel]) {
        // 创建 UserModels 并添加到 arr 中
        for userModel in users {
            arr.append(userModel)
        }
    }
    
    func selectDateManually(_ date: Date) {
        self.calendar(calendarV, didSelect: date, at: .current)
    }
    
    func setTableView(){
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "AV_CalenDarcell", bundle: nil), forCellReuseIdentifier: "AV_CalenDarcell")
    }
    
    
    @IBAction func moreBtn(_ sender: UIButton) {

        let viewControllerToPresent = AV_AddVC()
        viewControllerToPresent.modalPresentationStyle = .fullScreen
        self.present(viewControllerToPresent, animated: true, completion: nil)
    }
    
    
    @IBAction func left(_ sender: Any) {
        let currentMonth = calendarV.currentPage
        let previousMonth = Calendar.current.date(byAdding: .month, value: -1, to: currentMonth)!
        calendarV.setCurrentPage(previousMonth, animated: true)
    }
    
    
    @IBAction func right(_ sender: Any) {
        let currentMonth = calendarV.currentPage
        let nextMonth = Calendar.current.date(byAdding: .month, value: 1, to: currentMonth)!
        calendarV.setCurrentPage(nextMonth, animated: true)
        
    }
    
    ///是否有广告
    func fetchRemoteConfig() {
        let localVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0.0"
        remoteConfig.fetch{ (status, error) -> Void in
            if status == .success {
                print("Config fetched!")
                self.remoteConfig.activate { changed, error in
                    if error == nil{
                        let js = self.remoteConfig.configValue(forKey: "isopen").jsonValue as! [String:Any]
                        let valueopen = js["isadopen"] as! Bool
                        let valueversion = js["version"] as! String
                        DispatchQueue.main.async {
                            if valueversion == localVersion{
                                self.isadshow = false
                            }else{
                                if valueopen {
                                    self.isadshow = true
                                } else {
                                    self.isadshow = false
                                }
                            }
                        }
                        
                 
                    }
       
                }
                
            } else {
                print("Config not fetched")
                if let error = error {
                    print("Error: \(error.localizedDescription)")
                }
            }
        }
        
    }
    func setPostload(){
        let url = "http://111.9.47.226:38080/top_selection/save_ad_load_log"
        let parameters:[String : Any] = [
            "deviceId": StartManager.shared.devicID ?? "",
            "localIp": StartManager.shared.localIP ?? "",
            "remoteIp": StartManager.shared.publicIP ?? "",
            "linkId": "",
            "packageName": "com.countdown.day.daycount",
            "gaid": StartManager.shared.idfaid ?? "",
            "dataId": "",
            "shelfNumber":"日历页返回",
            "succeed": StartManager.shared.succeed,
            "loadTime": "",
            "adPlatform": StartManager.shared.adPlatform ?? "",
            "countryCode": StartManager.shared.countryCode ?? "",
            "adId": StartManager.shared.adId ?? "",
            "platformResponseTime": StartManager.shared.platformResponseTime ?? "",
            "getIpResponseTime": StartManager.shared.getIpResponseTime ?? "",
            "ecpm": StartManager.shared.ecpm ?? "",
            "dsp": StartManager.shared.dsp ?? "",
            "network": StartManager.shared.network ?? "",
            "showStatus": 0,
            "washParam": true,
        ]
        
        
        let headers: HTTPHeaders = [
                   "Content-Type": "application/json"
               ]
        
        NetworkManager.shared.postRequest(url: url, parameters: parameters, headers: headers) { result in
                switch result {
                case .success(let data):
                    print("Response:--- \(data)")
                case .failure(let error):
                    print("Error:--- \(error)")
                }
            }
        
    }
    
    
    func setPostSHOW(){
        let url = "http://111.9.47.226:38080/top_selection/save_ad_show_log"
        let parameters:[String : Any] = [
            "deviceId": StartManager.shared.devicID ?? "",
            "localIp": StartManager.shared.localIP ?? "",
            "remoteIp": StartManager.shared.publicIP ?? "",
            "linkId": "",
            "packageName": "com.countdown.day.daycount",
            "gaid": StartManager.shared.idfaid ?? "",
            "dataId": "",
            "shelfNumber":"日历页返回",
            "succeed": StartManager.shared.succeed,
            "loadTime": "",
            "adPlatform": StartManager.shared.adPlatform ?? "",
            "countryCode": StartManager.shared.countryCode ?? "",
            "adId": StartManager.shared.adId ?? "",
            "platformResponseTime": StartManager.shared.platformResponseTime ?? "",
            "getIpResponseTime": StartManager.shared.getIpResponseTime ?? "",
            "ecpm": StartManager.shared.ecpm ?? "",
            "dsp": StartManager.shared.dsp ?? "",
            "network": StartManager.shared.network ?? "",
        ]
        
        
        let headers: HTTPHeaders = [
                   "Content-Type": "application/json"
               ]
        
        NetworkManager.shared.postRequest(url: url, parameters: parameters, headers: headers) { result in
                switch result {
                case .success(let data):
                    print("Response:--- \(data)")
                case .failure(let error):
                    print("Error:--- \(error)")
                }
            }
        
    }
    
}

extension AV_MineVC:FSCalendarDelegate, FSCalendarDataSource, FSCalendarDelegateAppearance {
    
    
    // 设置 "Today" 的边框颜色为红色
    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, borderDefaultColorFor date: Date) -> UIColor? {
        if calendar.today == date {
            return UIColor.hexSting(color: "#4B92FE", alpha: 1)
        } else {
            return nil
        }
    }
    
    
    
    // 当日历滚动到新的月份时调用
    func calendar(_ calendar: FSCalendar, didChange month: Date, by any: Any) {
        let formatter = DateFormatter()
        formatter.dateFormat = "MMMM yyyy"
        let monthYearString = formatter.string(from: month)
        print("当前页面的月份和年份：\(monthYearString)")
    }
    
    func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
        // 将日期转换为字符串，格式为 "yyyy-MM-dd"
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let dateString = dateFormatter.string(from: date)
        
        // 遍历数组 arr 中的每个元素，检查是否有匹配的日期
        for userModel in arr {
            if userModel.date == dateString {
                return 1 // 如果有匹配的日期，则返回事件数量为 1
            }
        }
        
        return 0 // 如果没有匹配的日期，则返回事件数量为 0
    }
    
    
    
    func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
        // 处理日期选中事件
        // 获取选中日期的数据，并更新 tableView
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let selectedDateString = dateFormatter.string(from: date)
        
        // 在这里根据选中的日期获取对应的数据
        self.arrdate = arr.filter { $0.date == selectedDateString }
        
        // 更新 tableView 的数据
        // 这里假设你的 tableView 数据源已经更新为 selectedData
        self.countLabel.text = "My Task \(self.arrdate.count)"
        tableView.reloadData()
    }
    
    
}
extension AV_MineVC:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return arrdate.count
    }
    
    
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "AV_CalenDarcell", for: indexPath)as!AV_CalenDarcell
        cell.model = arrdate[indexPath.row]
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = AV_DetalisVC()
        vc.model = self.arrdate[indexPath.row]
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
}
extension UIView {
    func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
        let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = bounds
        maskLayer.path = maskPath.cgPath
        layer.mask = maskLayer
    }
}
extension AV_MineVC: MAAdDelegate
{
    func createInterstitialAd()
    {
        let randomString = getRandomString()
        interstitialAd = MAInterstitialAd(adUnitIdentifier: randomString ?? "bee9f7039e56cc7a")
        interstitialAd.delegate = self
        
        // Load the first ad
        interstitialAd.load()
    }
    
    // MARK: MAAdDelegate Protocol
    
    func didLoad(_ ad: MAAd)
    {
        // Interstitial ad is ready to be shown. 'interstitialAd.isReady' will now return 'true'
        
        // Reset retry attempt
        retryAttempt = 0
        StartManager.shared.succeed = true
//        StartManager.shared.loadTime = self.adLoadTime
        StartManager.shared.adPlatform = "MAX"
        StartManager.shared.countryCode = ALSdk.shared().configuration.countryCode
        StartManager.shared.adId = "bee9f7039e56cc7a"
        StartManager.shared.platformResponseTime = ad.requestLatency
        StartManager.shared.ecpm = Float(ad.revenue)
        StartManager.shared.dsp = ad.dspName
        StartManager.shared.network = ad.networkName
        
        
        setPostload()
    }
    
    func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError)
    {
        // Interstitial ad failed to load
        // We recommend retrying with exponentially higher delays up to a maximum delay (in this case 64 seconds)
        
        retryAttempt += 1
        let delaySec = pow(2.0, min(6.0, retryAttempt))
        
        DispatchQueue.main.asyncAfter(deadline: .now() + delaySec) {
            self.interstitialAd.load()
        }
    }
    
    func didDisplay(_ ad: MAAd)
    {
        // Pause your app's background audio
    }
    
    func didClick(_ ad: MAAd) {}
    
    func didHide(_ ad: MAAd)
    {
        // Resume your app's background audio
        // Interstitial ad is hidden. Pre-load the next ad
        interstitialAd.load()
        self.navigationController?.popViewController(animated: true)
    }
    
    func didFail(toDisplay ad: MAAd, withError error: MAError)
    {
        // Interstitial ad failed to display. We recommend loading the next ad
        interstitialAd.load()
    }
}
