package com.persagy.revit.backstage.state

import com.persagy.database.SFilter
import com.persagy.revit.backstage.request.task.TaskCmd
import com.persagy.revit.models.modelFile.ModelFile
import com.persagy.revit.services.BaseDataService
import com.persagy.revit.services.message.MessageService
import com.persagy.revit.services.modelCheck.TaskService
import com.persagy.revit.services.monitor.ModelMonitorService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.*

@Component
class UploadedState_1 : ModelState {

    companion object {
        // 日志
        private val logger = LoggerFactory.getLogger(UploadedState_1::class.java)
        val projection = arrayListOf("status", "taskInfo")
    } // Companion object

    val dataService = BaseDataService

    @Autowired
    lateinit var messageService: MessageService

    @Autowired
    lateinit var taskService : TaskService

    @Autowired
    lateinit var monitorService: ModelMonitorService

    var modelList : ArrayList<ModelFile>? = null

    /**
     * 准备数据
     */
    override fun prepareModel() {
        modelList = dataService.modelFileService.select(SFilter.eq("status", 1), SFilter.eq("removed", false)).exec()
    }


    /**
     * 将模型发往revit调度器做DataCheck处理
     */
    override fun handle() {
        try {
            if (modelList == null || modelList!!.isEmpty()) {
                return
            }
            if (!taskService.addTask(modelList!!, TaskCmd.DataCheck)) {
                logger.warn("状态1处理失败!")
                return
            }
            var checkTime = Date()
            modelList?.forEach { modelFile ->
                modelFile.status = 10
                dataService.modelFileService.update(modelFile, projection)
                monitorService.beginCheck(modelFile.id!!, checkTime)
                val message = messageService.buildRefreshMessage(modelFile.projectId, modelFile.userId ?: "")
                messageService.sendMessage(message)
            }
//            val request = SUpdateRequest<ModelFile>()
//            request.content = modelList
//            request.projection = arrayListOf("status", "taskInfo")
//            dataService.modelFileService.updateList(request)
        }catch (e : Exception){
            e.printStackTrace()
            logger.error(e.message)
        }
    }
}
