//
//  SpeakHomeSignViewCtr.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/8/1.
//

import UIKit

class SpeakHomeSignViewCtr: UIViewController, yQzCalendarViewDelegate  {
    
    // MARK: - ib
    
    @IBOutlet weak var contenV: UIView!
    @IBOutlet weak var SpeakSignSnow: UIButton!
    
    @IBOutlet weak var SpeakCurrentStreak: UILabel!
    @IBOutlet weak var SpeakLongStreak: UILabel!
    
    @IBOutlet weak var SpeakCurStreakT: UILabel!
    @IBOutlet weak var SpeakLongStreakT: UILabel!
    
    @IBOutlet weak var SpeakSignSelectYear: UILabel!
    @IBOutlet weak var SpeakCanderView: yQzCalendarView!
    
    @IBOutlet weak var SpeakTopConst: NSLayoutConstraint!
    
    let viewModel:SpeakHomeViewModel = SpeakHomeViewModel()
    
    var currentDate:Date = Date() {
        didSet{
            SpeakSignSelectYear.text = currentDate.toStr("MMM yyyy")
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        SpeakCurStreakT.adjustsFontSizeToFitWidth = true
        SpeakLongStreakT.adjustsFontSizeToFitWidth = true
        SpeakCurrentStreak.adjustsFontSizeToFitWidth = true
        SpeakLongStreak.adjustsFontSizeToFitWidth = true
        currentDate = Date()
        SpeakCanderView.delegate = self
        NotificationCenter.default.addObserver(self, selector: #selector(updateUI), name: NSNotification.Name.UserInfoUpdate, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(SignUpdateafaafae), name: NSNotification.Name("calendarUpdate"), object: nil)
        updateUI()
        SpeakTopConst.constant = -Dev.screenH
        self.view.layoutIfNeeded()
    }
    
    @objc private func updateUI() -> Void {
        let userInfo = SpeakElePublicManager.share.userInfo
        SpeakSignSnow.setTitle("\(userInfo.snowNum ?? 0)", for: .normal)
        SpeakCurrentStreak.text = "\(userInfo.currentContinuousSignDays ?? 0)"
        SpeakLongStreak.text = "\(userInfo.maxContinuousSignDays ?? 0)"
    }
    
    @objc private func SignUpdateafaafae() -> Void {
        SpeakCanderView.signList = signList
        SpeakCanderView.updateData()
    }
    
    let signList = speakSignListViewModel.share.signList
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        SpeakCanderView.signList = signList
        self.contenV.layoutIfNeeded()
        DispatchQueue.main.async {
            self.view.setNeedsDisplay()
            UIView.animate(withDuration: 0.25) {
                self.SpeakTopConst.constant = 0
                self.view.layoutIfNeeded()
            }
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
    }
    
    @IBAction func SpeakSignUperMonth(_ sender: Any) {
        SpeakCanderView.upper()
        currentDate = currentDate.operation(month: -1)
    }
    
    @IBAction func SpeakSignNextMonth(_ sender: Any) {
        SpeakCanderView.next()
        currentDate = currentDate.operation(month: 1)
    }
    
    func calendarView(change date: Date) {
        currentDate = date
    }
    
    func calendarView(didSelect date: Date) {
        let curr = Int32(Date().toStr("yyyyMMdd") ?? "") ?? 0
        let tap = Int32(date.toStr("yyyyMMdd") ?? "") ?? 0
        let d = date.toStr("yyyy-MM") ?? ""
        let d1 = date.toStr("yyyy-MM-dd") ?? ""
        if let signList = signList?[d] as? [SignListModel] {
            let ar = signList.filter({$0.signDate == d1})
            if curr > tap && ar.count < 1 {
                let alert = SpeakEndorViewCtr()
                alert.modalPresentationStyle = .overFullScreen
                alert.modalTransitionStyle = .crossDissolve
                self.present(alert, animated: true)
                alert.view.callblack = { [weak self] success in
                    guard let sucess = success as? Bool else { return }
                    if sucess {
                        self?.EndorAlert(sucess ,date: d1 , alert)
                    }
                }
            }
        }
    }
    
    func EndorAlert(_ su:Bool, date:String ,_ alert:UIViewController) -> Void {
        if SpeakElePublicManager.share.userInfo.snowNum ?? 0 > 0 {
            viewModel.SignUp(data: date) { su in
                if su {
                    let stateVC = SpeakSnowTypeViewCtr(state: 1)
                    stateVC.modalPresentationStyle = .overFullScreen
                    stateVC.modalTransitionStyle = .crossDissolve
                    alert.present(stateVC, animated: true)
                    if let call = self.view.callblack {
                        call("Update")
                    }
                    stateVC.view.callblack = { result in
                        alert.presentingViewController?.dismiss(animated: true)
                    }
                }else{
                    let stateVC = SpeakSnowTypeViewCtr(state: 0)
                    stateVC.modalPresentationStyle = .overFullScreen
                    stateVC.modalTransitionStyle = .crossDissolve
                    alert.present(stateVC, animated: true)
                    stateVC.view.callblack = { [weak self] result in
                        guard let success = result as? Bool else { return }
                        let block:(()->Void) = {
                            if success {
                                let vc = SpeakSnowNumViewCtr()
                                vc.modalPresentationStyle = .overFullScreen
                                self?.present(vc, animated: true)
                            }
                        }
                        alert.presentingViewController?.dismiss(animated: true) {
                            block()
                        }
                    }
                }
            }
        }else {
            let stateVC = SpeakSnowTypeViewCtr(state: 0)
            stateVC.modalPresentationStyle = .overFullScreen
            stateVC.modalTransitionStyle = .crossDissolve
            alert.present(stateVC, animated: true)
            stateVC.view.callblack = { [weak self] result in
                guard let success = result as? Bool else { return }
                let block:(()->Void) = {
                    if success {
                        let vc = SpeakSnowNumViewCtr()
                        vc.modalPresentationStyle = .overFullScreen
                        vc.modalTransitionStyle = .crossDissolve
                        self?.present(vc, animated: true)
                    }
                }
                alert.presentingViewController?.dismiss(animated: true) {
                    block()
                }
            }
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.view.layoutIfNeeded()
        contenV.cornerRect(radius: 24, [.bottomLeft,.bottomRight])
    }
    
    /// 点击其它区域关闭
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        guard let touchPoint = touches.first?.location(in: self.view) else { return }
        if !CGRectContainsPoint(self.contenV.frame, touchPoint) {
            self.dismiss(animated: true)
        }
    }
    
    deinit{
        self.view.callblack = nil
        NotificationCenter.default.removeObserver(self)
    }
}
