package com.persagy.server.services.assistant

import com.persagy.server.datacenter.models.entities.assistant.ObjInfos
import com.persagy.server.datacenter.models.entities.tool.ObjectBaseRequest
import com.persagy.server.services.dict.PropertyDefProjectService
import com.persagy.base.extensions.toJson
import com.persagy.base.extensions.toMap
import com.persagy.database.SFilter
import com.persagy.mybatis.SMybatisDao
import com.persagy.service.SObjectService
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*

/**
 * 信息点服务
 * @author  蔡云飞
 */
object ObjInfoService :  SObjectService<ObjInfos>(SMybatisDao(ObjInfos::class.java)) {

    private val SIMPLEDATEFORMAT_DC = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    /**
     * @Description: 查找创建或更新信息点
     * @Param: entity,flag,objType,type
     */
    fun createInfo(entity: Any, flag: Boolean,objType: String,type: String){
        var request = ObjectBaseRequest()
        val infos = JSONObject(entity.toJson())
        val map = entity.toMap()
        val iterator = infos.keys()
        while (iterator.hasNext()) {
            val key = iterator.next()
            val value = infos.get(key as String)
            if (value!=null&&value.toString()!="null"){
                request.addInfo(key, value, false)
            }
        }
        val pro = PropertyDefProjectService.select(SFilter.eq("projectId",map["projectId"].toString()), SFilter.eq("type",type), SFilter.or(SFilter.eq("inputMode","L"), SFilter.eq("inputMode","M"))).exec()
        val requestInfos = request.infos
        if(requestInfos!=null){
            if(pro!=null){

                for (propertyDefProjectInfo in pro) {
                    val infoPointCode = propertyDefProjectInfo.infoPointCode
                    if(requestInfos.containsKey(infoPointCode)){
                        var objInfos = ObjInfos()
                        objInfos.objType = objType
                        objInfos.projectId = map["projectId"].toString()
                        objInfos.objId = map["id"].toString()
                        objInfos.infoId = infoPointCode
                        objInfos.value = requestInfos[infoPointCode].toString()
                        if(flag){
                            objInfos.time = SIMPLEDATEFORMAT_DC.format(Date())
                            insert(objInfos)
                        }else{
                            objInfos.time = SIMPLEDATEFORMAT_DC.format(map["lastUpdate"].toString())
                            update(objInfos)
                        }
                    }
                }
            }
        }
    } // Fun

} // Object ObjInfoService