package cn.sagacloud.server.algorithm.backstage.state

import cn.sagacloud.server.algorithm.backstage.request.task.TaskCmd
import cn.sagacloud.server.algorithm.services.modelCheck.TaskService
import cn.sagacloud.server.algorithm.models.modelFile.ModelFile
import cn.sagacloud.server.algorithm.services.BaseDataService
import cn.sagacloud.server.algorithm.services.message.MessageService
import cn.sagacloud.server.algorithm.services.monitor.ModelMonitorService
import com.sybotan.database.SFilter
import com.sybotan.database.enums.SDirection
import com.sybotan.service.models.requests.SUpdateRequest
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.*
import kotlin.collections.ArrayList

/**
 *
 *
 * @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)
        }
    }
}