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

import UIKit
import FSCalendar

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 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(){

        LuxADManager.shareInstance().showADByRandomMode(callback: {
            actionType  in
            self.navigationController?.popViewController(animated: true)
        })
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
     
        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)
        
    }
    
  
    
}

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
    }
}
