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.*

/**
 *
 *
 * @author jxing
 */
@Component
class CheckPassedState_2 : ModelState {

    companion object {
        // 日志
        private val logger = LoggerFactory.getLogger(CheckPassedState_2::class.java)
    } // Companion object

    val dataService = BaseDataService

    @Autowired
    lateinit var taskService : TaskService

    @Autowired
    lateinit var messageService: MessageService

    @Autowired
    lateinit var monitorService: ModelMonitorService

    var modelList : ArrayList<ModelFile>? = null

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

    /**
     * 将模型发给调度器做DataExport处理
     */
    override fun handle() {
        try {
            if (modelList.isNullOrEmpty()) {
                return
            }
            // 先给模型文件版本号和接收时间
            // addVersionChangeName(modelList!!)
            // 添加任务到调度器
            if (!taskService.addTask(modelList!!, TaskCmd.DataExport)) {
                logger.warn("状态2处理失败!")
                return
            }
            val exportTime = Date()
            modelList?.forEach { modelFile ->
                modelFile.status = 20
                dataService.modelFileService.update(modelFile, UploadedState_1.projection)
                monitorService.beginExport(modelFile.id!!, exportTime)
                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)
        }
    }
}