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

import UIKit
import SVProgressHUD
import Photos

class AV_HomeVC: AV_RootVC {

    
    @IBOutlet weak var noneImagV: UIImageView!
    
    
    @IBOutlet weak var serchView: UIView!
    
    
    @IBOutlet weak var serchtextF: UITextField!
    
    
    @IBOutlet weak var tableView: UITableView!
    
    
    @IBOutlet weak var titleLabel: UILabel!
    
    var arr = [UserModel]()
    
    var searchResults: [UserModel] = []
    
    var typesearch:Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()

        serchView.layer.cornerRadius = 25
        setTableViewCell()
        PrWCDBBaseManager.shared.createTable(table: "UserModel", of: UserModel.self)
        serchtextF.delegate = self
        requestPhotoLibraryPermission()
        setNetwork()
       
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
        let users = PrWCDBBaseManager.shared.qureyFromDb(fromTable: userModelTableName, cls: UserModel.self)
                if let users = users {
                    self.arr = users
                    print("---\(users)")
                } else {
                    
                }
      
        titleLabel.text = "My Task \(self.arr.count)"
//            // 更新视图
            updateUI()
    }
    

    
    // 根据输入的文本进行查询
     func search(withText searchText: String) {
         // 查询数据库中匹配的用户数据
         let condition = UserModel.Properties.name.like("%\(searchText)%")
         let results = PrWCDBBaseManager.shared.qureyFromDb(fromTable: userModelTableName, cls: UserModel.self, where: condition)
  
         if let results = results {
             searchResults = results
             // 更新 UI，例如刷新表格视图
             tableView.reloadData()
         }
     }


    func setTableViewCell(){
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "AV_TaskCell", bundle: nil), forCellReuseIdentifier: "AV_TaskCell")
        
    }
    
    func updateUI() {
          if arr.isEmpty {
              noneImagV.isHidden = false
          } else {
              noneImagV.isHidden = true
          }
          tableView.reloadData()
      }
    
    
    
    func requestPhotoLibraryPermission() {
        // 检查相册权限状态
        let status = PHPhotoLibrary.authorizationStatus()
        
        // 根据权限状态进行处理
        switch status {
        case .authorized:
            // 用户已授权访问相册
            print("相册权限已授权")
        case .denied, .restricted:
            // 用户已拒绝访问相册或权限受限
            print("相册权限已拒绝或受限，请在设置中开启权限")
        case .notDetermined:
            // 用户尚未作出选择，请求相册权限
            PHPhotoLibrary.requestAuthorization { [weak self] (newStatus) in
                DispatchQueue.main.async {
                    if newStatus == .authorized {
                        // 用户授权访问相册
                        print("用户已授权访问相册")
                    } else {
                        // 用户未授权访问相册
                        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)")
                    DispatchQueue.main.asyncAfter(deadline: .now()){
                        SVProgressHUD.showInfo(withStatus: "Network connection failed, please try again")
                        DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {
                        SVProgressHUD.dismiss()
                            
                        }
                    }
                } else if let data = data {

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

}

extension AV_HomeVC:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.typesearch == 0{
            return arr.count
        }else{
            return searchResults.count
        }
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "AV_TaskCell", for: indexPath) as! AV_TaskCell
//        cell.dateLabel.text = "May\n20"
        if self.typesearch == 0{
            cell.model = self.arr[indexPath.row]
        }else{
            cell.model = self.searchResults[indexPath.row]
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = AV_DetalisVC()
        if self.typesearch == 0{
            vc.model = self.arr[indexPath.row]
            self.navigationController?.pushViewController(vc, animated: true)
        }else{
            vc.model = self.searchResults[indexPath.row]
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
}
extension AV_HomeVC: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // 获取输入的文本
        guard let text = textField.text else { return true }
        
        // 计算最终输入的文本
        let newText = (text as NSString).replacingCharacters(in: range, with: string)
        
        if newText.count <= 0 {
            self.typesearch = 0
        }else{
            self.typesearch = 1
        }
        
        // 执行搜索操作
        search(withText: newText)
        
        return true
    }
}
