//
//  AV_SelectGenderVC.swift
//  anniversary_Project
//
//  Created by 忆海16 on 2024/7/3.
//

import UIKit
import Photos
import Alamofire

class AV_SelectGenderVC: AV_RootVC {
    
    @IBOutlet weak var tableView: UITableView!
    
    var headarr = ["Man","Woman","Pregnant","Lactation","Other"]
    var namearr = ["Man","Woman","Pregnant","Lactation","Other"]
    
    var selectedIndex: IndexPath?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setTableViewcell()
//        ["日", "一", "二", "三", "四", "五", "六"]
        let defaults = UserDefaults.standard
        let weekdays = ["日", "一", "二", "三", "四", "五", "六"]
        for day in weekdays {
            defaults.set(0, forKey: day)
        }

        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.")
            }
        }
        stePermissions()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.navigationController?.navigationBar.isHidden = true
        
    }
    
    func setTableViewcell(){
        tableView.delegate = self
        tableView.dataSource = self
        
        tableView.register(UINib(nibName: "AV_SelectGenderCell", bundle: nil), forCellReuseIdentifier: "AV_SelectGenderCell")
        
    }
    
    @IBAction func skipBtn(_ sender: Any) {
        let defaults = UserDefaults.standard
        defaults.set(2000, forKey: "waterml")
        
        if defaults.object(forKey: "waveView") != nil {
            print("键 'answer' 存在")
        } else {
            print("键 'answer' 不存在")
            defaults.set(0, forKey: "waveView")
        }
        let appDelegate = UIApplication.shared.delegate
        appDelegate?.window??.rootViewController = AV_NAVVC(rootViewController: AV_WaterHomeVC())

    }
    
    
    @IBAction func nextBtn(_ sender: Any) {
        let vc = AV_selectWeightVC()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func stePermissions(){
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            if granted {
                print("Permission granted")
            } else if let error = error {
                print("Permission denied: \(error.localizedDescription)")
            }
        }
        requestPhotoLibraryPermission()
        setNetwork()
        // 使用示例
        let healthManager = HealthManager()

        // 请求授权
        healthManager.requestAuthorization { (success, error) in
            if success {
                print("HealthKit authorization granted")
                
            } else if let error = error {
                print("HealthKit authorization failed with error: \(error.localizedDescription)")
            }
        }
    }
    
    func requestPhotoLibraryPermission() {
        // 检查相册权限状态
        let status = PHPhotoLibrary.authorizationStatus()
        
        // 根据权限状态进行处理
        switch status {
        case .authorized:
            // 用户已授权访问相册
            print("相册权限已授权")
        case .denied, .restricted:
            // 用户已拒绝访问相册或权限受限
            print("相册权限已拒绝或受限，请在设置中开启权限")
        case .notDetermined:
            // 用户尚未作出选择，请求相册权限
            PHPhotoLibrary.requestAuthorization {  (newStatus) in
                DispatchQueue.main.async {
                    if newStatus == .authorized {
                        // 用户授权访问相册
                        print("用户已授权访问相册")
                    } else {
                        // 用户未授权访问相册
                        print("用户未授权访问相册")
                    }
                }
            }
        case .limited:
            print("用户已授权此应用程序访问有限的照片库")
        @unknown default:
            // 处理未知权限状态
            print("未知的相册权限状态")
        }
    }
    
    func setNetwork(){
        // 创建一个URL对象
        if let url = URL(string: "https://www.baidu.com/") {
            // 创建一个URLSession对象
            let session = URLSession.shared
            
            // 创建一个网络请求任务
            let task = session.dataTask(with: url) { (data, response, error) in
                if let error = error {
                    print("网络请求出错：\(error)")

                }
            }
            
            // 开始网络请求任务
            task.resume()
        } else {
            print("URL无效")
        }
    }

    
}
extension AV_SelectGenderVC:UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 5
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "AV_SelectGenderCell", for: indexPath) as! AV_SelectGenderCell
        
        cell.headImagV.image = UIImage(named: self.headarr[indexPath.row])
        cell.nameLabel.text = self.namearr[indexPath.row]
        
        if indexPath == selectedIndex {
            
            cell.animateGradient(to: [UIColor.hexSting(color: "#69CCFB", alpha: 1).cgColor, //
                                      UIColor.hexSting(color: "#69CCFB", alpha: 1).cgColor])
        } else {
            cell.animateGradient(to: [UIColor.hexSting(color: "#F7F8F9", alpha: 1).cgColor, UIColor.hexSting(color: "F7F8F9", alpha: 1).cgColor])
        }
        
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        
        let previousSelectedIndex = selectedIndex
        
        // 更新选定的索引
        if selectedIndex == indexPath {
            selectedIndex = nil // 如果再次点击同一行则取消选择
        } else {
            selectedIndex = indexPath
        }
        
        //  重新加载先前选定的单元格和当前选定的单元格
        var indexPathsToReload: [IndexPath] = [indexPath]
        if let previous = previousSelectedIndex {
            indexPathsToReload.append(previous)
        }
        
        tableView.reloadRows(at: indexPathsToReload, with: .automatic)
        
        if indexPath.row == 0{
            let defaults = UserDefaults.standard
            defaults.set("Man", forKey: "people")
        }else if indexPath.row == 1{
            let defaults = UserDefaults.standard
            defaults.set("Woman", forKey: "people")
        }else if indexPath.row == 2{
            let defaults = UserDefaults.standard
            defaults.set("Pregnancy", forKey: "people")
        }else if indexPath.row == 3{
            let defaults = UserDefaults.standard
            defaults.set("Lactation", forKey: "people")
        }
        
    }
    
}
