//
//  TSDiyKeyboardViewVC.swift
//  AIEmoji
//
//  Created by 100Years on 2025/1/21.
//
import JXSegmentedView
import SwiftUI
import Combine
class TSDiyKeyboardViewVC: TSBaseVC {
    
    var templateModel:DiyPaperTemplateModel
    var keyBoardModel:DiyStickerCategory
    init(templateModel:DiyPaperTemplateModel,keyBoardModel: DiyStickerCategory) {
        self.templateModel = templateModel
        self.keyBoardModel = keyBoardModel
        super.init()
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var viewModel: TSDiyKeyboardVM = {
        let viewModel = TSDiyKeyboardVM(templateModel: templateModel, keyStickerModel: keyBoardModel)
        return viewModel
    }()
    
    lazy var diyCanvasView : DiyPaperTemplateBaseView = {
        let diyCanvasView = viewModel.templateModel.templateViewType.init()
        diyCanvasView.backgroundColor = .gray
        diyCanvasView.clipsToBounds = true
        diyCanvasView.initialUI(with: viewModel.templateModel)
        return diyCanvasView
    }()

    /// 键盘
    let clickKeyPublisher = PassthroughSubject<DiyStickerModel, Never>()
    lazy var hostVc: UIHostingController<TSKeyboardView> = {
        let vc = UIHostingController(rootView: TSKeyboardView(keyBoardModelArray: viewModel.getAmericanKeyboardStyleArray(),clickKeyPublisher: clickKeyPublisher))
        vc.view.backgroundColor = .white
        return vc
    }()
    
    
    override func createView() {
        setNavBarViewHidden(true)
        
        contentView.addSubview(diyCanvasView)
        diyCanvasView.snp.updateConstraints { make in
            make.top.equalTo(25)
            make.width.equalTo(239)
            make.height.equalTo(515)
            make.centerX.equalToSuperview()
        }
        
        contentView.addSubview(hostVc.view)
        hostVc.view.snp.makeConstraints { make in
            make.leading.trailing.equalTo(0)
            make.bottom.equalTo(0)
            make.height.equalTo(200+k_Height_safeAreaInsetsBottom())
        }
    }
    
    override func dealThings() {
        clickKeyPublisher.receive(on: kMainQueue).sink{ [weak self] model in
            guard let self = self else { return }
            viewModel.addAlreadyEnteredModel(model: model,diyCanvasView: diyCanvasView)
        }.store(in: &cancellable)
    }
    
    
    func getDiyImage() -> UIImage? {
        diyCanvasView.cleanSubviewsEditStatus()
        return diyCanvasView.toImage()
    }
    
}

extension TSDiyKeyboardViewVC: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
