//
//  AV_WaterHomeVC.swift
//  anniversary_Project
//
//  Created by 忆海16 on 2024/7/4.
//

import UIKit
import SVProgressHUD
import Alamofire
import FirebaseAnalytics

class AV_WaterHomeVC: AV_RootVC {
    
    @IBOutlet weak var tableView: UITableView!
    var arrBirther = [UserModel]()
    let colors: [UIColor] = [
        UIColor.hexSting(color: "#D2F0FB", alpha: 1),
        UIColor.hexSting(color: "#EDD0FF", alpha: 1),
        UIColor.hexSting(color: "#D8F5DF", alpha: 1),
        UIColor.hexSting(color: "#FFEDED", alpha: 1)
    ]
    
    let defaults = UserDefaults.standard
    let healthManager = HealthManager()
    var tagml:Int = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        if (!LuxADManager.shareInstance().isADSSMode()){
            Analytics.logEvent("homepage", parameters: nil)
        }
       
        PrWCDBBaseManager.shared.createTable(table: "UserModel", of: UserModel.self)
        setTableView()
        
        scheduleNotifications()
        requestTrackingAuthorization { idfa in
            if let idfa = idfa {
                print("IDFA: \(idfa)")
                StartManager.shared.idfaid = idfa
                print("Stored IDFA: \(StartManager.shared.idfaid ?? "N/A")")
            } else {
                print("IDFA is not available or tracking authorization denied.")
            }
        }
        setPostStar()
    }
    
    func setPostStar(){
        let url = "http://111.9.47.226:38080/top_selection/save_app_start_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": "",
        ]
        
        
        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)")
                }
            }
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true

        loadData()
        setwaterdrink()
        let target = defaults.integer(forKey: "waterml")
        self.tagml = Int(target)
    }
    
    func setwaterdrink(){
        if defaults.object(forKey: "waterml") != nil {
            if defaults.integer(forKey: "waterml") == 2000{
                let weight = defaults.integer(forKey: "weight")
                let jichu = 0.033 * Double(weight)
                let exercise = defaults.string(forKey: "sports")
                let temp = defaults.string(forKey: "temperature")
                if weight != 0, let exercise = exercise, !exercise.isEmpty, let temp = temp, !temp.isEmpty {
                    var yundong:Double = 0.0
                    if exercise == "Exercise regularly"{
                        yundong = jichu + 1.0
                    }else if exercise == "Occasional exercise"{
                        yundong = jichu + 0.5
                    }else if exercise == "Almost no exercise"{
                        yundong = jichu + 0.2
                    }
                    var zuizhong:Double = 0.0
                    if temp == "Heat"{
                        zuizhong = yundong + 1.0
                    }else if temp == "Warm and warm exercise"{
                        zuizhong = yundong + 0.5
                    }else if temp == "Comfortable"{
                        zuizhong = yundong + 0.22
                    }else if temp == "Clod"{
                        zuizhong = yundong + 0.0
                    }
                    
                    defaults.set(zuizhong * 1000, forKey: "waterml")
                } else {
                   
                }
            }else{
                let weight = defaults.integer(forKey: "weight")
                let jichu = 0.033 * Double(weight)
                let exercise = defaults.string(forKey: "sports")
                let temp = defaults.string(forKey: "temperature")
                var yundong:Double = 0.0
                if exercise == "Exercise regularly"{
                    yundong = jichu + 1.0
                }else if exercise == "Occasional exercise"{
                    yundong = jichu + 0.5
                }else if exercise == "Almost no exercise"{
                    yundong = jichu + 0.2
                }
                var zuizhong:Double = 0.0
                if temp == "Heat"{
                    zuizhong = yundong + 1.0
                }else if temp == "Warm and warm exercise"{
                    zuizhong = yundong + 0.5
                }else if temp == "Comfortable"{
                    zuizhong = yundong + 0.22
                }else if temp == "Clod"{
                    zuizhong = yundong + 0.0
                }
                
                defaults.set(zuizhong * 1000, forKey: "waterml")
            }
            
        } else {
            print("键 'waterml' 不存在")
            let weight = defaults.integer(forKey: "weight")
            let jichu = 0.033 * Double(weight)
            let exercise = defaults.string(forKey: "sports")
            let temp = defaults.string(forKey: "temperature")
            var yundong:Double = 0.0
            if exercise == "Exercise regularly"{
                yundong = jichu + 1.0
            }else if exercise == "Occasional exercise"{
                yundong = jichu + 0.5
            }else if exercise == "Almost no exercise"{
                yundong = jichu + 0.2
            }
            var zuizhong:Double = 0.0
            if temp == "Heat"{
                zuizhong = yundong + 1.0
            }else if temp == "Warm and warm exercise"{
                zuizhong = yundong + 0.5
            }else if temp == "Comfortable"{
                zuizhong = yundong + 0.22
            }else if temp == "Clod"{
                zuizhong = yundong + 0.0
            }
            
            defaults.set(zuizhong * 1000, forKey: "waterml")
        }
    }
    
    func setTableView() {
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "AV_WaterCell", bundle: nil), forCellReuseIdentifier: "AV_WaterCell")
        tableView.register(UINib(nibName: "AV_WaterDayCell", bundle: nil), forCellReuseIdentifier: "AV_WaterDayCell")
        tableView.register(UINib(nibName: "AV_BirtherDayTaskCell", bundle: nil), forCellReuseIdentifier: "AV_BirtherDayTaskCell")
        tableView.register(UINib(nibName: "AV_NoneCell", bundle: nil), forCellReuseIdentifier: "AV_NoneCell")
        
    }
    
    func loadData() {
        if let users = PrWCDBBaseManager.shared.qureyFromDb(fromTable: userModelTableName, cls: UserModel.self) {
            self.arrBirther = users
            print("---\(users)")
        } else {
            self.arrBirther = []
        }
        tableView.reloadData()
    }
    
    func scheduleNotifications() {
        scheduleNotification(at: 7, minute: 0, identifier: "morningNotification", title: "Good morning", body: "Let's start with the first glass of water today")
        scheduleNotification(at: 10, minute: 0, identifier: "midMorningNotification", title: "It's ten o'clock.", body: "Don't forget to drink water")
        scheduleNotification(at: 12, minute: 0, identifier: "noonNotification", title: "lunch time", body: "Drink a glass of water while eating.")
        scheduleNotification(at: 15, minute: 0, identifier: "afternoonNotification", title: "It's tea time", body: "Take a break and drink some water.")
        scheduleNotification(at: 18, minute: 0, identifier: "eveningNotification", title: "Dinner time", body: "What water should I drink with dinner?")
        scheduleNotification(at: 20, minute: 0, identifier: "nightNotification", title: "Bedtime reading time", body: "Don't forget to drink water while studying.")
        scheduleNotification(at: 22, minute: 0, identifier: "lateNightNotification", title: "Good night", body: "Drink a glass of milk before going to bed")
    }
    
    
}
extension AV_WaterHomeVC:UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 || section == 1 {
            return 1
        } else {
            if arrBirther.count == 0{
                return 1
            }else{
                return arrBirther.count
            }
            
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "AV_WaterCell", for: indexPath) as! AV_WaterCell
            
            let waterml = defaults.integer(forKey: "waterml")
            cell.waveView.setTotalCapacity(CGFloat(waterml))
            
            if let savedDate = defaults.object(forKey: "savedDate") as? Date {
                // 获取当前日期
                let currentDate = Date()
                
                // 创建一个日期格式化器
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd" // 设置日期格式
                
                // 格式化日期为字符串
                let savedDateString = dateFormatter.string(from: savedDate)
                let currentDateString = dateFormatter.string(from: currentDate)
                
                // 比较两个日期字符串
                if savedDateString == currentDateString {
                    print("同一天")
                    let answer = defaults.integer(forKey: "waveView")
                    let waterml = defaults.integer(forKey: "waterml")
                 
                    cell.waveView.setCurrentVolume(CGFloat(answer))
                    cell.drinkMLLabel.text = "\(answer)ml"
                    let percentage = (Double(answer) / Double(waterml)) * 100
                    cell.drinkb.text = "Progress \(Int(percentage))% · target\(tagml)ml"
                    // 获取今天的星期几
                    let todayWeekday = getTodayWeekday()
                    defaults.set(percentage, forKey: todayWeekday)
                } else {
                    print("不同天")
                    cell.waveView.setCurrentVolume(0)
                    cell.drinkMLLabel.text = "0ml"
                    cell.drinkb.text = "Progress 0% · target\(tagml)"
                    defaults.set(0, forKey: "waveView")
                    let currentDate = Date()
                    let defaults = UserDefaults.standard
                    defaults.set(currentDate, forKey: "savedDate")
                }
            }
            
            cell.birtherBlock = {
                let vc = AV_MineVC()
                self.navigationController?.pushViewController(vc, animated: true)
            }
            cell.setingBlock = {
                let vc = AV_WaterSettingVC()
                self.navigationController?.pushViewController(vc, animated: true)
            }
            cell.block150 = { [self] in
                cell.waveView.drinkWater(150)
                let answer = defaults.integer(forKey: "waveView")
                let neanswer = answer + 150
                let waterml = defaults.integer(forKey: "waterml")
                let percentage = (Double(neanswer) / Double(waterml)) * 100
                defaults.set(neanswer, forKey: "waveView")
                cell.drinkMLLabel.text = "\(neanswer)ml"
                cell.drinkb.text = "Progress \(Int(percentage))% · target\(tagml)ml"
                // 获取今天的星期几
                let todayWeekday = getTodayWeekday()
                defaults.set(percentage, forKey: todayWeekday)
                let currentDate = Date()
                healthManager.saveWaterIntake(waterQuantity: 0.15, date: currentDate)
                tableView.reloadData()
                SVProgressHUD.showSuccess(withStatus: "Add drinking water successfully")
                DispatchQueue.main.asyncAfter(wallDeadline: .now() + 1.5) {
                    SVProgressHUD.dismiss()
                }
                
            }
            cell.block200 = { [self] in
                cell.waveView.drinkWater(200)
                let answer = defaults.integer(forKey: "waveView")
                let neanswer = answer + 200
                let waterml = defaults.integer(forKey: "waterml")
                let percentage = (Double(neanswer) / Double(waterml)) * 100
                defaults.set(neanswer, forKey: "waveView")
                cell.drinkMLLabel.text = "\(neanswer)ml"
                
                cell.drinkb.text = "Progress \(Int(percentage))% · target\(tagml)ml"
                // 获取今天的星期几
                let todayWeekday = getTodayWeekday()
                defaults.set(percentage, forKey: todayWeekday)
                let currentDate = Date()
                healthManager.saveWaterIntake(waterQuantity: 0.2, date: currentDate)
                tableView.reloadData()
                SVProgressHUD.showSuccess(withStatus: "Add drinking water successfully")
                DispatchQueue.main.asyncAfter(wallDeadline: .now() + 1.5) {
                    SVProgressHUD.dismiss()
                }
                
            }
            cell.block250 = { [self] in
                cell.waveView.drinkWater(250)
                let answer = defaults.integer(forKey: "waveView")
                let neanswer = answer + 250
                let waterml = defaults.integer(forKey: "waterml")
                let percentage = (Double(neanswer) / Double(waterml)) * 100
                defaults.set(neanswer, forKey: "waveView")
                
                cell.drinkMLLabel.text = "\(neanswer)ml"
                
                
                cell.drinkb.text = "Progress \(Int(percentage))% · target\(tagml)ml"
                // 获取今天的星期几
                let todayWeekday = getTodayWeekday()
                defaults.set(percentage, forKey: todayWeekday)
                let currentDate = Date()
                healthManager.saveWaterIntake(waterQuantity: 0.25, date: currentDate)
                tableView.reloadData()
                SVProgressHUD.showSuccess(withStatus: "Add drinking water successfully")
                DispatchQueue.main.asyncAfter(wallDeadline: .now() + 1.5) {
                    SVProgressHUD.dismiss()
                }
            }
            cell.block300 = { [self] in
                cell.waveView.drinkWater(300)
                let answer = defaults.integer(forKey: "waveView")
                let neanswer = answer + 300
                let waterml = defaults.integer(forKey: "waterml")
                let percentage = (Double(neanswer) / Double(waterml)) * 100
                defaults.set(neanswer, forKey: "waveView")
                
                cell.drinkMLLabel.text = "\(neanswer)ml"
                
                cell.drinkb.text = "Progress \(Int(percentage))% · target\(tagml)ml"
                // 获取今天的星期几
                let todayWeekday = getTodayWeekday()
                defaults.set(percentage, forKey: todayWeekday)
                let currentDate = Date()
                healthManager.saveWaterIntake(waterQuantity: 0.3, date: currentDate)
                tableView.reloadData()
                SVProgressHUD.showSuccess(withStatus: "Add drinking water successfully")
                DispatchQueue.main.asyncAfter(wallDeadline: .now() + 1.5) {
                    SVProgressHUD.dismiss()
                }
            }
            cell.block350 = { [self] in
                cell.waveView.drinkWater(350)
                let answer = defaults.integer(forKey: "waveView")
                let neanswer = answer + 350
                let waterml = defaults.integer(forKey: "waterml")
                let percentage = (Double(neanswer) / Double(waterml)) * 100
                defaults.set(neanswer, forKey: "waveView")
                cell.drinkMLLabel.text = "\(neanswer)ml"
                
                cell.drinkb.text = "Progress \(Int(percentage))% · target\(tagml)ml"
                // 获取今天的星期几
                let todayWeekday = getTodayWeekday()
                defaults.set(percentage, forKey: todayWeekday)
                let currentDate = Date()
                healthManager.saveWaterIntake(waterQuantity: 0.35, date: currentDate)
                tableView.reloadData()
                SVProgressHUD.showSuccess(withStatus: "Add drinking water successfully")
                DispatchQueue.main.asyncAfter(wallDeadline: .now() + 1.5) {
                    SVProgressHUD.dismiss()
                }
            }
            
            cell.blockedit = {
                let vc = AV_AddWaterVC()
                self.navigationController?.pushViewController(vc, animated: true)
            }
            return cell
        } else if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "AV_WaterDayCell", for: indexPath) as! AV_WaterDayCell
            
//            
            cell.day1Label.text = "\(Int(defaults.integer(forKey:"一")))%"
            cell.day1cup.image = UIImage(named: getImageName(for: Int(defaults.integer(forKey:"一"))))
            
            cell.day2Label.text = "\(Int(defaults.integer(forKey:"二")))%"
            cell.day2Cup.image = UIImage(named: getImageName(for: Int(defaults.integer(forKey:"二"))))
            
            cell.day3label.text = "\(Int(defaults.integer(forKey:"三")))%"
            cell.day3Cup.image = UIImage(named: getImageName(for: Int(defaults.integer(forKey:"三"))))
            
            cell.day4Label.text = "\(Int(defaults.integer(forKey:"四")))%"
            cell.day4Cup.image = UIImage(named: getImageName(for: Int(defaults.integer(forKey:"四"))))
            
            cell.day5Label.text = "\(Int(defaults.integer(forKey:"五")))%"
            cell.day5Cup.image = UIImage(named: getImageName(for: Int(defaults.integer(forKey:"五"))))
            
            cell.day6Label.text = "\(Int(defaults.integer(forKey:"六")))%"
            cell.day6Cup.image = UIImage(named: getImageName(for: Int(defaults.integer(forKey:"六"))))
            
            cell.day7Label.text = "\(Int(defaults.integer(forKey:"七")))%"
            cell.day7Cup.image = UIImage(named: getImageName(for: Int(defaults.integer(forKey:"七"))))
            return cell
        } else {
            
            if self.arrBirther.count == 0  {
                let cell = tableView.dequeueReusableCell(withIdentifier: "AV_NoneCell", for: indexPath) as! AV_NoneCell
                return cell
            }else{
                let cell = tableView.dequeueReusableCell(withIdentifier: "AV_BirtherDayTaskCell", for: indexPath) as! AV_BirtherDayTaskCell
                cell.model = arrBirther[indexPath.row]
                cell.bgView.backgroundColor = colors.randomElement()!
                return cell
            }

          
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 2 {
            if arrBirther.count == 0{
             
            }else{
                let vc = AV_DetalisVC()
                vc.model = self.arrBirther[indexPath.row]
                self.navigationController?.pushViewController(vc, animated: true)
            }

        }
    }
}
