//
//  SpeakElePracticeViewCtr.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/21.
//

import UIKit

class SpeakElePracticeViewCtr: SpeakEleBaseViewCtr {

    // MARK: - ib
    @IBOutlet weak var SpeakSectionL: UILabel!
    @IBOutlet weak var SpeakProgressL: UILabel!
    @IBOutlet weak var SpeakCollection: UICollectionView!
    
    private let viewModel = SpeakPracticeNetViewModel()
    private let collectViewModel = SpeakEleProfileNetViewModel()
    /// 课程
    private var Session:[SpeakPracticeLessonModel] = []
    private var currentLess:SpeakPracticeLessonModel?
    private var selectIdx:Int = -1
    
    override func viewDidLoad() {
        super.viewDidLoad()
        SpeakWordTranslateData.data.loadData()
    }
    
    override func setup() {
        SpeakCollection.delegate = self
        SpeakCollection.dataSource = self
        SpeakCollection.isPagingEnabled = true
        SpeakCollection.register(UINib(nibName: SpeakElePracticeViewCell.id, bundle: nil), forCellWithReuseIdentifier: SpeakElePracticeViewCell.id)
        SpeakProgressL.contentInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
        SpeakProgressL.clipsToBounds = true
    }

    @IBAction func SpeakSelectTaps(_ sender: Any) {
        let learnedW = SpeakPracticeLearnedWViewCtr()
        learnedW.data = self.Session
        self.navigationController?.pushViewController(learnedW, animated: true)
        learnedW.view.callblack = { [weak self] data in
            if let da = data as? SpeakPracticeLessonModel {
                if self?.currentLess?.lessonId != da.lessonId {
                    for (i,v) in (self?.Session ?? []).enumerated() {
                        if v.lessonId == da.lessonId {
                            self?.selectIdx = i
                            break
                        }
                    }
                    self?.currentLess = da
                    self?.SpeakselectSession()
                }
            }
        }
    }
    
    @IBAction func SpeakReviewTaps(_ sender: Any) {
        if self.currentLess != nil {
            let review = SpeakElePracticeReviewViewCtr()
            review.leasionName = self.currentLess?.lessonName ?? ""
            review.datasource = dataSource.map({ bd in
                var temp = bd
                temp.isFront = nil
                return temp
            })
            review.leassion = self.currentLess?.lessonId ?? 0
            review.view.callblack = {[weak self] data in
                self?.viewModel.learnedLesson {[weak self] (success, data:[SpeakPracticeLessonModel]?) in
                    if success {
                        self?.Session = data ?? []
                        self?.currentLess = data?[safe:self?.selectIdx ?? 0]
                    }
                }
                self?.viewModel.leassionWord(param: ["lessonId":self?.currentLess?.lessonId ?? ""]) {[weak self] (su, data:[SpeakPracticeWordModel]? ) in
                    if su {
                        self?.dataSource = data ?? []
                        let name = SpeakElePublicManager.share.userInfo.targetLanguage ?? ""
                        SpeakCache.cache.SaveModel(cache: self?.dataSource, state: .PracticeCache, name: name)
                        
                        let model = SpeakPracticeLesLocalModel(lesson: self?.Session, select: self?.selectIdx)
                        SpeakCache.cache.SaveModel(cache: model, state: .PracticeCache, name: "Lesson")
//                        self?.setPage(current: 1 )
//                        self?.SpeakCollection.reloadData()
                        self?.loadCache()
                    }
                }
            }
            self.parent?.navigationController?.pushViewController(review, animated: true)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        titleView.isHidden = true
        let model:SpeakPracticeLesLocalModel? = SpeakCache.cache.LoadMode(state: .PracticeCache, name: "Lesson")
        self.Session = model?.lesson ?? []
        self.selectIdx = model?.select ?? 0
        if self.selectIdx >= 0 && self.selectIdx < (model?.lesson?.count ?? 0) && (model?.lesson?.count ?? 0) > 0 {
            self.currentLess = self.Session[self.selectIdx]
        }
        let name = SpeakElePublicManager.share.userInfo.targetLanguage ?? ""
        let data:[SpeakPracticeWordModel] = SpeakCache.cache.LoadMode(state: .PracticeCache, name: name) ?? []
        if self.Session.count <= 0 {
            self.getLeasion()
        }else{
            SpeakSectionL.text = currentLess?.lessonName
            if data.count != self.dataSource.count {
                self.dataSource = data
                setPage(current: 1)
                self.SpeakCollection.reloadData()
            }else{
                for (i,var v) in self.dataSource.enumerated() {
                    if let cell = SpeakCollection.cellForItem(at: IndexPath(row: i, section: 0)) as? SpeakElePracticeViewCell {
                        v.isCollected = data[i].isCollected
                        cell.data = v
                    }
                }
            }
        }
    }
    private var dataSource:[SpeakPracticeWordModel] = []
}

extension SpeakElePracticeViewCtr :UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
 
    private func setFavaret(_ fw:Bool , indexPath:IndexPath) -> Void {
        let d = self.dataSource[indexPath.row].wordId
        collectViewModel.collect(param: ["businessId":d,
                                         "type":2,
                                         "isCollect":fw]) {[weak self] su, data in
            self?.dataSource[indexPath.row].isCollected = su ? fw : !fw
            let cell = self?.SpeakCollection.cellForItem(at: indexPath) as? SpeakElePracticeViewCell
            cell?.data = self?.dataSource[indexPath.row]
        }
    }
    
    private func getLeasion() -> Void {
        viewModel.learnedLesson {[weak self] (success, data:[SpeakPracticeLessonModel]?) in
            if success {
                self?.Session = data ?? []
                self?.currentLess = data?[safe:self?.selectIdx ?? 0]
                self?.SpeakselectSession()
            }
        }
    }
    
    private func SpeakselectSession() -> Void {
        SpeakSectionL.text = currentLess?.lessonName
        viewModel.leassionWord(param: ["lessonId":self.currentLess?.lessonId ?? ""]) {[weak self] (su, data:[SpeakPracticeWordModel]? ) in
            if su {
                self?.dataSource = data ?? []
                
                let name = SpeakElePublicManager.share.userInfo.targetLanguage ?? ""
                SpeakCache.cache.SaveModel(cache: self?.dataSource, state: .PracticeCache, name: name)
                
                let model = SpeakPracticeLesLocalModel(lesson: self?.Session, select: self?.selectIdx)
                SpeakCache.cache.SaveModel(cache: model, state: .PracticeCache, name: "Lesson")
                
                self?.setPage(current: 1 )
                self?.SpeakCollection.reloadData()
                self?.loadCache()
            }
        }
    }
    
    private func loadCache() -> Void {
        if IAPViewModel.share.isSubscribed {
            DispatchQueue.global().async {[weak self] in
                for data in self?.dataSource ?? [] {
                    self?.viewModel.cardTranslate(param: ["word":data.word ?? ""]) { (su , res:SpeakPracticeWordDetailModel?) in
                        if su {
                            SpeakWordTranslateData.data.WordTranslate?[data.wordId ?? 0] = res
                            SpeakDayEveryManager.manager.SpeakDayData.PracticeFreeNum! -= 1
                            SpeakDayEveryManager.manager.update()
                        }
                    }
                }
            }
        }
    }
    
    private func setPage( current:Int) -> Void {
        SpeakProgressL.attributedText = "\(current)".attributed().color(.init(hex: 0x000000,alpha: 0.9)).build().combined(with: [" / \(dataSource.count)".attributed().color(.init(hex: 0x000000 ,alpha: 0.26)).build()])
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SpeakElePracticeViewCell.id, for: indexPath) as! SpeakElePracticeViewCell
        var data = self.dataSource[indexPath.row]
        cell.data = data
        cell.callblack = {[weak self] fw in
            if let i = fw as? String {
                data.isFront = (i == "1" ? true : false)
                self?.dataSource[indexPath.row] = data
            }else{
                self?.setFavaret( (fw as? Bool ?? false) ,indexPath: indexPath)
            }
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 80
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 40, bottom: 0, right: 40)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSizeMake(collectionView.size.width-40*2, collectionView.size.height)
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let point = scrollView.contentOffset
        self.setPage(current: ( Int(round(point.x/scrollView.width)) + 1) )
    }
}
