package com.persagy.server.services.rel

import com.persagy.server.datacenter.models.entities.rel.REqSyList
import com.persagy.server.datacenter.models.entities.rel.RSyEq
import com.persagy.server.datacenter.models.entities.rel.RSyEqList
import com.persagy.server.services.base.RService
import com.persagy.server.services.objects.EquipmentService
import com.persagy.base.extensions.toJson
import com.persagy.database.SFilter
import com.persagy.mybatis.SMybatisDao
import com.persagy.service.SPageContext
import com.persagy.service.models.enums.SResponseType
import com.persagy.service.models.responses.SBaseResponse
import com.persagy.service.models.responses.SCreateResponse
import org.json.JSONObject
import org.slf4j.LoggerFactory

/**
 * 系统下的设备设施关系服务
 *
 * @author 张维新
 */
object RSyEqService : RService<RSyEq>(SMybatisDao(RSyEq::class.java)) {

    private val logger = LoggerFactory.getLogger(RSyEqService::class.java)

    /**
     * 创建系统下设备关系
     *
     * @param   rSyEq   系统和设备的关系对象
     */
    fun create(rSyEq: RSyEq): SCreateResponse<RSyEq> {
        return try {
            val projectId = SPageContext.getHeader("ProjectId")
//            rSyEq.id = IdUtils.uuidCreate()
            rSyEq.projectId = projectId
            val isInsert = replace(rSyEq)
            if (isInsert){
                val jsonObject = JSONObject()
                jsonObject.put("type", "11")
                jsonObject.put("projectId", projectId)
                jsonObject.put("id", rSyEq.sysId)
                jsonObject.put("obj_type", "SystemEquip")
                jsonObject.put("linkId",rSyEq.equipId)
                /** 发送消息 */
                messageHandler.sendMessage(jsonObject.toString())
//                kafkaService.sendNotice("datacenterrel", RelationNotice(projectId!!, "SystemEquip", "11", IdUtils.uuidCreate(),  rSyEq.sysId!!,
//                        rSyEq.equipId!!),false)
                SCreateResponse(SResponseType.success)
            }else{
                SCreateResponse(SResponseType.failure)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            SCreateResponse(SResponseType.failure,e.message.toString())
        }
    } // Function create()

    /**
     * 根据对象删除
     *
     * @param   rSyEq      关系对象实例
     * @return
     */
     fun deletes(rSyEq: RSyEq): SBaseResponse {
        return try {
            val projectId = SPageContext.getHeader("ProjectId")
                val isDelete = delete(rSyEq)
                /** 删除成功 */
                if (isDelete) {

                    try {
                        /** 处理关系标记 */
                        val listtype = ArrayList<String>()
                        listtype.add("syeq2bd")
                        listtype.add("sy2fl")
                        listtype.add("sy2sh")
                        listtype.add("sy2sp")
                        for (type in listtype){
                            val entity = EquipmentService.relationTypeProjectservice.select(SFilter.eq("projectId", projectId!!), SFilter.eq("relationType", type)).entity()
                            if (entity!=null){
                                entity.computationalState = 2
                                EquipmentService.relationTypeProjectservice.update(entity)
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }

                    val sBaseResponse = SBaseResponse(SResponseType.success)
                    sBaseResponse.message = rSyEq.toJson()

                    val jsonObject = JSONObject()
                    jsonObject.put("type", "12")
                    jsonObject.put("projectId", projectId)
                    jsonObject.put("id", rSyEq.sysId)
                    jsonObject.put("obj_type", "SystemEquip")
                    jsonObject.put("linkId",rSyEq.equipId)
                    /** 发送消息 */
                    messageHandler.sendMessage(jsonObject.toString())
//                    kafkaService.sendNotice("datacenterrel", RelationNotice(projectId!!, "SystemEquip", "12", IdUtils.uuidCreate(),  rSyEq.sysId!!, rSyEq.equipId!!),false)
                    sBaseResponse
                } else {
                    SBaseResponse(SResponseType.failure)
                }
        } catch (e: Exception) {
            e.printStackTrace()
            return SBaseResponse(SResponseType.failure, e.message!!)
        }
    } // Function deletes()

    /**
     * 创建系统下设备关系
     *
     * @param   rSyEqList   系统和设备的关系对象列表
     */
    fun createSy(rSyEqList: RSyEqList): SCreateResponse<RSyEq> {
        return try {
            val projectId = SPageContext.getHeader("ProjectId")
            /** 成功集合 */
            val successList = ArrayList<Any>()
            /** 失败集合 */
            val failureList = ArrayList<Any>()
            try {
                delete("sysID = '${rSyEqList.sysId}'")
            } catch (e: Exception) {
                e.printStackTrace()
            }
            if (rSyEqList.listEquipId!=null&&rSyEqList.listEquipId!!.isNotEmpty()){
                for (eqId in rSyEqList.listEquipId!!){
                    val rSyEq = RSyEq()
                    rSyEq.equipId = eqId
                    rSyEq.sysId =  rSyEqList.sysId
                    rSyEq.projectId = projectId
                    val replace = replace(rSyEq)
                    if (replace){
                        successList.add(rSyEq)
                    }else{
                        failureList.add(rSyEq)
                    }
                }
                if (successList.size>0){
                    val jsonObject = JSONObject()
                    jsonObject.put("type", "13")
                    jsonObject.put("projectId", projectId)
                    jsonObject.put("id", rSyEqList.sysId)
                    jsonObject.put("obj_type", "SystemEquip")
                    jsonObject.put("linkId",successList.toJson())
                    /** 发送消息 */
                    messageHandler.sendMessage(jsonObject.toString())
//                    kafkaService.sendNotice("datacenterrel", RelationNotice(projectId!!, "SystemEquip", "13", IdUtils.uuidCreate(),  rSyEqList.sysId!!, null),false)

                    val sCreateResponse = SCreateResponse<RSyEq>(SResponseType.success)
                    if (failureList.size>0){
                        sCreateResponse.message ="失败对象："+failureList.toJson()
                    }
                    sCreateResponse
                }else{
                    SCreateResponse(SResponseType.failure)
                }
            }else{
                SCreateResponse(SResponseType.success)
            }

        } catch (e: Exception) {
            e.printStackTrace()
            SCreateResponse(SResponseType.failure,e.message.toString())
        }
    } // Function createSy()

    /**
    * 创建系统下设备关系
    *
    * @param   rSyEqList   系统和设备的关系对象列表
    */
    fun createsEq(rSyEqList: REqSyList): SCreateResponse<RSyEq> {
        return try {
            val projectId = SPageContext.getHeader("ProjectId")
            /** 成功集合 */
            val successList = ArrayList<Any>()
            /** 失败集合 */
            val failureList = ArrayList<Any>()

            try {
                delete("EquipID = '${rSyEqList.equipId}'")
            } catch (e: Exception) {
                e.printStackTrace()
            }

            if (rSyEqList.sysIdList!=null&&rSyEqList.sysIdList!!.isNotEmpty()){
                for (eqId in rSyEqList.sysIdList!!){
                    val rSyEq = RSyEq()
                    rSyEq.equipId = rSyEqList.equipId
                    rSyEq.sysId = eqId
                    rSyEq.projectId = projectId
                    val replace = replace(rSyEq)
                    if (replace){
                        successList.add(rSyEq)
                    }else{
                        failureList.add(rSyEq)
                    }
                }
                if (successList.size>0){
                    val jsonObject = JSONObject()
                    jsonObject.put("type", "13")
                    jsonObject.put("projectId", projectId)
                    jsonObject.put("id", rSyEqList.equipId)
                    jsonObject.put("obj_type", "SystemEquip")
                    jsonObject.put("linkId",successList.toJson())
                    /** 发送消息 */
                    messageHandler.sendMessage(jsonObject.toString())
//                    kafkaService.sendNotice("datacenterrel", RelationNotice(projectId!!, "SystemEquip", "13", IdUtils.uuidCreate(),  rSyEqList.equipId!!, null),false)


                    if (failureList.size>0){
                        val sCreateResponse = SCreateResponse<RSyEq>(SResponseType.success)
                        sCreateResponse.message ="失败对象："+failureList.toJson()
                        sCreateResponse
                    }else{
                        val sCreateResponse = SCreateResponse<RSyEq>(SResponseType.success)
                        sCreateResponse
                    }
                }else{
                    SCreateResponse(SResponseType.failure)
                }
            }else{
                SCreateResponse(SResponseType.success)
            }


        } catch (e: Exception) {
            e.printStackTrace()
            SCreateResponse(SResponseType.failure,e.message.toString())
        }
    } // Function createsEq()

    /**
     * 创建系统下设备关系
     *
     * @param   rSyEqList   系统和设备的关系对象列表
     */
    fun createSyEq(rSyEqList: RSyEqList): SCreateResponse<RSyEq> {
        return try {
            logger.debug("设备和系统00001=${rSyEqList.toJson()}")
            val projectId = SPageContext.getHeader("ProjectId")

            /** 失败集合 */
            val failureList = ArrayList<RSyEq>()
            if (rSyEqList.listEquipId!=null&&rSyEqList.listEquipId!!.isNotEmpty()){

                /** 成功集合 */
                val successList = ArrayList<RSyEq>()
                for (eqId in rSyEqList.listEquipId!!){
                    val rSyEq = RSyEq()
                    logger.debug("设备和系统11 =${eqId}")
                    rSyEq.equipId = eqId
                    rSyEq.sysId =  rSyEqList.sysId
                    rSyEq.projectId = projectId
                    logger.debug("设备和系统12 =${rSyEq.toJson()}")
                    val replace = replace(rSyEq)
                    if (replace){
                        val rSyEq = RSyEq()
                        logger.debug("设备和系统11 =${eqId}")
                        rSyEq.equipId = eqId
                        rSyEq.sysId =  rSyEqList.sysId
                        rSyEq.projectId = projectId
                        successList.add(rSyEq)
                    }else{
                        failureList.add(rSyEq)
                    }
                }
                logger.debug("设备和系统14 =${successList.toJson()}")
                if (successList.size>0){
//                    val listId = ArrayList<String>()
//                    for (success   in successList){
//                        val rSyEq = success as RSyEq
//                        listId.add(rSyEq.equipId!!)
//                    }
                    logger.debug("设备和系统 =${successList.toJson()}")
                    val jsonObject = JSONObject()
                    jsonObject.put("type", "14")
                    jsonObject.put("projectId", projectId)
                    jsonObject.put("id", rSyEqList.sysId)
                    jsonObject.put("obj_type", "SystemEquip")
                    jsonObject.put("linkId",successList.toJson())
                    /** 发送消息 */
                    messageHandler.sendMessage(jsonObject.toString())
//                    kafkaService.sendNotice("datacenterrel", RelationNotice(projectId!!, "SystemEquip", "14", IdUtils.uuidCreate(),  rSyEqList.sysId!!, null),false)
                    val sCreateResponse = SCreateResponse<RSyEq>(SResponseType.success)
                    if (failureList.size>0){
                        sCreateResponse.message ="失败对象："+failureList.toJson()
                    }

                    try {
                        /** 处理关系标记 */
                        val listtype = ArrayList<String>()
                        listtype.add("syeq2bd")
                        listtype.add("sy2fl")
                        listtype.add("sy2sh")
                        listtype.add("sy2sp")
                        for (type in listtype){
                            val entity = EquipmentService.relationTypeProjectservice.select(SFilter.eq("projectId", projectId!!), SFilter.eq("relationType", type)).entity()
                            if (entity!=null){
                                entity.computationalState = 2
                                EquipmentService.relationTypeProjectservice.update(entity)
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }

                    sCreateResponse
                }else{
                    SCreateResponse(SResponseType.failure)
                }
            }else{
                SCreateResponse(SResponseType.success)
            }

        } catch (e: Exception) {
            e.printStackTrace()
            SCreateResponse(SResponseType.failure,e.message.toString())
        }
    } // Function createSy()

    /**
     * 删除前的操作
     */
    override fun onDeleteBefore(entity: RSyEq): Boolean {

        return if (entity.sysId.isNullOrEmpty()||entity.equipId.isNullOrEmpty()){
            false
        }else{
            super.onDeleteBefore(entity)
        }
    } // Function onDeleteBefore()

    /**
     * 创建关系
     */
    override fun onCreateSuccess(entityList: ArrayList<RSyEq>) {
        super.onCreateSuccess(entityList)
        val projectId = SPageContext.getHeader("ProjectId")
        for (rSyEq in entityList){
            val jsonObject = JSONObject()
            jsonObject.put("type", "11")
            jsonObject.put("projectId", projectId)
            jsonObject.put("id", rSyEq.sysId)
            jsonObject.put("obj_type", "SystemEquip")
            jsonObject.put("linkId",rSyEq.equipId)

            /** 发送消息 */
            messageHandler.sendMessage(jsonObject.toString())
//            kafkaService.sendNotice("datacenterrel", RelationNotice(projectId!!, "SystemEquip", "11", IdUtils.uuidCreate(),  rSyEq.sysId!!, rSyEq.equipId),false)
        }

    } // Function onCreateSuccess()

    /**
     * 删除关系
     */
    override fun onDeleteSuccess(entityList: ArrayList<RSyEq>) {
        super.onDeleteSuccess(entityList)
        val projectId = SPageContext.getHeader("ProjectId")
        for (rSyEq in entityList){
            val jsonObject = JSONObject()
            jsonObject.put("type", "12")
            jsonObject.put("projectId", projectId)
            jsonObject.put("id", rSyEq.sysId)
            jsonObject.put("obj_type", "SystemEquip")
            jsonObject.put("linkId",rSyEq.equipId)
            /** 发送消息 */
            messageHandler.sendMessage(jsonObject.toString())
//            kafkaService.sendNotice("datacenterrel", RelationNotice(projectId!!, "SystemEquip", "12", IdUtils.uuidCreate(),  rSyEq.sysId!!, rSyEq.equipId),false)
        }
    } // Function onDeleteSuccess()


} // Object RSyEqService