//
//  WA_MineVC.swift
//  wallpaper_project
//
//  Created by 忆海16 on 2024/3/14.
//

import UIKit
import SVProgressHUD


class WA_MineVC: WA_RootVC {
    
    @IBOutlet weak var dataView: UIView!
    
    
    @IBOutlet weak var headImagV: UIImageView!
    
    @IBOutlet weak var xxbtn: UIButton!
    
    
    @IBOutlet weak var nameLabel: UILabel!
    
    @IBOutlet weak var loginBtn: UIButton!
    
    
    @IBOutlet weak var clearV: UIView!
    
    
    
    @IBOutlet weak var outV: UIView!
    
    @IBOutlet weak var editHeadBtn: UIButton!
    
    @IBOutlet weak var tableView: UITableView!
    
    
    
    let activityView = UIActivityIndicatorView()
    
    var datacount:Int = 0
    
    var model = [WA_RakModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.xxbtn.layer.cornerRadius = 5
        headImagV.layer.cornerRadius = 30
        setLayercolor()
       
        
        activityView.center = CGPoint(x: self.view.center.x, y: self.view.center.y - kSafeArea_Top - 44)
        // 停止后，隐藏菊花
        activityView.hidesWhenStopped = true
        activityView.color = .black
        activityView.style = UIActivityIndicatorView.Style.whiteLarge
        self.view.addSubview(activityView)
        setTableViewCell()
    }
    
    
    func setLayercolor(){
        
        clearV.layer.shadowColor = UIColor.black.cgColor // 阴影颜色
        clearV.layer.shadowOpacity = 0.5 // 阴影透明度
        clearV.layer.shadowOffset = CGSize(width: 2, height: 2) // 阴影偏移量
        clearV.layer.shadowRadius = 4 // 阴影半径

        // 如果需要圆角效果，也可以添加圆角
        clearV.layer.cornerRadius = 8
        

        
        outV.layer.shadowColor = UIColor.black.cgColor // 阴影颜色
        outV.layer.shadowOpacity = 0.5 // 阴影透明度
        outV.layer.shadowOffset = CGSize(width: 2, height: 2) // 阴影偏移量
        outV.layer.shadowRadius = 4 // 阴影半径

        // 如果需要圆角效果，也可以添加圆角
        outV.layer.cornerRadius = 8
        
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
        setLogin()
    }
    
    
    func setLogin(){
        if isLoggedIn(){
            self.loginBtn.isHidden = true
            self.outV.isHidden = false
            self.nameLabel.isHidden = false
            self.headImagV.image = UIImage(named: "loginhead_s")
            self.editHeadBtn.isHidden = false
            // 检索模型数组
             let retrievedModels = PreferencesManager.shared.retrieveRakModels()
            if retrievedModels != nil{
                self.model = retrievedModels!
            }else{
                
            }
            if self.model.count  == 0{
                self.dataView.isHidden = false
            }else{
                self.dataView.isHidden = true
            }
            self.tableView.reloadData()

        }else{
            self.nameLabel.isHidden = true
            self.editHeadBtn.isHidden = true
            self.headImagV.image = UIImage(named: "loginhead")
            self.outV.isHidden = true
            self.loginBtn.isHidden = false
            var model = [WA_RakModel]()
            self.model = model
            self.dataView.isHidden = false
            self.tableView.reloadData()
        }

    }
    

    @IBAction func editheadBtn(_ sender: Any) {
        var imagePicker = UIImagePickerController()
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            imagePicker.delegate = self
            imagePicker.allowsEditing = true
            imagePicker.sourceType = .photoLibrary
            present(imagePicker, animated: true, completion: nil)
        }

    }
    
    
    
    @IBAction func btnxx(_ sender: Any) {
        let vc = WA_SettingSVC()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    
    @IBAction func btnLogin(_ sender: Any) {
        let vc = WA_LoginVC()
        vc.type = 1
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    @IBAction func clearBtn(_ sender: Any) {
        DispatchQueue.main.asyncAfter(deadline: .now()){
            self.activityView.startAnimating()
            HistoryManager.shared.clearHistory()
            liveManager.shared.clearHistory()
            HistoryjpgManager.shared.clearHistory()
            
            DispatchQueue.global().asyncAfter(deadline: .now() + 2.0){
                DispatchQueue.main.asyncAfter(deadline: .now()){
                    self.activityView.stopAnimating()
                    SVProgressHUD.showInfo(withStatus: "Cache cleaning completed this time")
                    DispatchQueue.global().asyncAfter(deadline: .now() + 1.0) {
                    SVProgressHUD.dismiss()
                    }
                }
            }
        }
        
    }
    
    
    @IBAction func loginOutBtn(_ sender: Any) {
        setLoggedIn(false)
        
        setLogin()
        
    }
    
    func setTableViewCell(){
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "WA_RakingCell", bundle: nil), forCellReuseIdentifier: "WA_RakingCell")
    }
    
    // 将 Base64 字符串转换为图片
    func convertStringToImage(base64String: String) -> UIImage? {
        if let imageData = Data(base64Encoded: base64String) {
            if let image = UIImage(data: imageData) {
                return image
            }
        }
        return nil
    }
}
extension WA_MineVC:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return model.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "WA_RakingCell", for: indexPath)as!WA_RakingCell
        
        let data = self.model[indexPath.row]
        cell.nameLabel.text = data.name
        cell.titleLabel.text = data.content
        cell.headImageV.image = convertStringToImage(base64String: data.head ?? "")
        cell.contentimagV.image = convertStringToImage(base64String: data.img ?? "")
        cell.shView.isHidden = false
        cell.zanLabel.text = "0"
        return cell
        
    }
    
}



// 实现UIImagePickerControllerDelegate协议
extension WA_MineVC: UIImagePickerControllerDelegate & UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let selectedImage = info[.editedImage] as? UIImage {
            // 在这里处理选择的图片，可以将其设置为头像等
            self.headImagV.image = selectedImage
        }
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
}
