/*
 * *********************************************************************************************************************
 *
 *          !!
 *        .F88X
 *        X8888Y
 *      .}888888N;
 *        i888888N;        .:!              .I$WI:
 *          R888888I      .'N88~            i8}+8Y&8"l8i$8>8W~'>W8}8]KW+8IIN"8&
 *          .R888888I    .;N8888~          .X8'  "8I.!,/8"  !%NY8`"8I8~~8>,88I
 *            +888888N;  .8888888Y                                  "&&8Y.}8,
 *            ./888888N;  .R888888Y        .'}~    .>}'.`+>  i}!    "i'  +/'  .'i~  !11,.:">,  .~]!  .i}i
 *              ~888888%:  .I888888l      .]88~`1/iY88Ii+1'.R$8$8]"888888888>  Y8$  W8E  X8E  W8888'188Il}Y88$*
 *              18888888    E8888881    .]W%8$`R8X'&8%++N8i,8N%N8+l8%`  .}8N:.R$RE%N88N%N$K$R  188,FE$8%~Y88I
 *            .E888888I  .i8888888'      .:$8I;88+`E8R:/8N,.>881.`$8E/1/]N8X.Y8N`"KF&&FK!'88*."88K./$88%RN888+~
 *            8888888I  .,N888888~        ~88i"8W,!N8*.I88.}888%F,i$88"F88"  888:E8X.>88!i88>`888*.}Fl1]*}1YKi'
 *          i888888N'      I888Y          ]88;/EX*IFKFK88X  K8R  .l8W  88Y  ~88}'88E&%8W.X8N``]88!.$8K  .:W8I
 *        .i888888N;        I8Y          .&8$  .X88!  i881.:%888>I88  ;88]  +88+.';;;;:.Y88X  18N.,88l  .+88/
 *      .:R888888I
 *      .&888888I                                          Copyright (c) 2009-2020.  博锐尚格科技股份有限公司
 *        ~8888'
 *        .!88~                                                                     All rights reserved.
 *
 * *********************************************************************************************************************
 */

package com.persagy.server.datacenter.services.rel

import com.persagy.base.extensions.toJson
import com.persagy.database.SFilter
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.Opt
import com.persagy.server.datacenter.models.entities.dict.SpaceInfoDic
import com.persagy.server.datacenter.models.entities.rel.RSh2Sp
import com.persagy.server.datacenter.models.entities.rel.RShContainSpBase
import com.persagy.server.datacenter.models.entities.rel.RShContainSpBaseList
import com.persagy.server.datacenter.services.base.RService
import com.persagy.server.datacenter.services.objects.EquipmentService
import com.persagy.server.datacenter.wanda.obj.ZoneSpace
import com.persagy.server.services.rel.RSpContainShBaseList
import com.persagy.service.SBaseService
import com.persagy.service.SPageContext
import com.persagy.service.models.enums.SResponseType
import com.persagy.service.models.requests.SCreateRequest
import com.persagy.service.models.requests.SQueryRequest
import com.persagy.service.models.responses.SBaseResponse
import com.persagy.service.models.responses.SCreateResponse
import com.persagy.service.models.responses.SQueryResponse

/**
 * 竖井下的业务空间关系服务 目前只支持 默认空间同步
 *
 * @author 付国宝
 */
object RShContainSpBaseService: RService<RShContainSpBase>(SMybatisDao(RShContainSpBase::class.java)) {

    val rSh2SpService = RService(SMybatisDao(RSh2Sp::class.java))

    /**
     * 创建竖井下业务空间关系
     *
     * @param    rShContainSpBaseList    竖井和业务空间的关系对象
     */
    fun create(rShContainSpBaseList: SCreateRequest<RShContainSpBase>): SCreateResponse<RShContainSpBase> {
        return try {

            for (rShContainSpBase in rShContainSpBaseList.content){
                val rSh2Sp = RSh2Sp()
                rSh2Sp.id2 = rShContainSpBase.spaceId
                rSh2Sp.id1 = rShContainSpBase.shaftId
                rSh2Sp.projectId = Opt.projectId
                rSh2Sp.sign = 1
                rSh2Sp.zoneType = rShContainSpBase.objectType
                rSh2Sp.type = "sh2sp"
                val isInsert = rSh2SpService.insert(rSh2Sp)
                if (isInsert){
                    /** 发送消息 */
                    rabbitMqService.sendRel(Opt.projectId!!, "sh2sp","11",rShContainSpBase.shaftId!!,rShContainSpBase.spaceId!!)
                }
            }

            val sCreateResponse = SCreateResponse<RShContainSpBase>(SResponseType.success)
            sCreateResponse
        } catch (e: Exception) {
            e.printStackTrace()
            SCreateResponse(SResponseType.failure,e.message.toString())
        }
    }

    /**
     * 根据对象删除
     *
     * @param    rShContainSpBase    关系对象实例
     * @return
     */
    fun deletes(type: String, rShContainSpBaseList: ArrayList<RShContainSpBase>): SBaseResponse {
        return try {

            for (rShContainSpBase in rShContainSpBaseList){
                val rSh2Sp = RSh2Sp()
                rSh2Sp.id2 = rShContainSpBase.spaceId
                rSh2Sp.id1 = rShContainSpBase.shaftId
                rSh2Sp.projectId = Opt.projectId
                rSh2Sp.zoneType = type
                rSh2Sp.type = "sh2sp"
                val isDelete = rSh2SpService.delete(rSh2Sp)
                if (isDelete) {
                    /** 发送消息 */
                    rabbitMqService.sendRel(Opt.projectId!!, "sh2sp","12",rShContainSpBase.shaftId!!,rShContainSpBase.spaceId!!)
                }
            }
            val sBaseResponse = SBaseResponse(SResponseType.success)
            sBaseResponse

        } catch (e: Exception) {
            e.printStackTrace()
            return SBaseResponse(SResponseType.failure, e.message!!)
        }
    }

    /**
     * 创建竖井下业务空间关系
     *
     * @param    rShContainSpBaseList    竖井和业务空间的关系对象列表
     */
    fun createSh(rShContainSpBaseList: RShContainSpBaseList): SCreateResponse<RShContainSpBase> {
        return try {
            /** 成功集合 */
            val successList = ArrayList<Any>()
            /** 失败集合 */
            val failureList = ArrayList<Any>()
            rSh2SpService.delete("id1 = '${rShContainSpBaseList.shaftId}'")
            val projectId = SPageContext.getHeader("projectId")
            for (spaceId in rShContainSpBaseList.spaceIdList!!){
                val rSh2Sp = RSh2Sp()
                rSh2Sp.id1 = rShContainSpBaseList.shaftId
                rSh2Sp.id2 = spaceId
                rSh2Sp.projectId = projectId
                rSh2Sp.zoneType = rShContainSpBaseList.zoneType
                rSh2Sp.sign = 1
                rSh2Sp.type = "sh2sp"
                val replace = rSh2SpService.replace(rSh2Sp)
                if (replace){
                    successList.add(spaceId)
                }else{
                    failureList.add(rSh2Sp)
                }
            }
            if (successList.size>0){
                /** 发送消息 */
                rabbitMqService.sendRel(Opt.projectId!!, "sh2sp","13",rShContainSpBaseList.shaftId!!,successList.toJson()!!)
                val sCreateResponse = SCreateResponse<RShContainSpBase>(SResponseType.success)
                if (failureList.size>0){
                    sCreateResponse.message ="失败对象："+failureList.toJson()
                }
                sCreateResponse
            }else{
                SCreateResponse(SResponseType.failure)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            SCreateResponse(SResponseType.failure,e.message.toString())
        }
    } // Function createSh()

    /**
     * 创建竖井下业务空间关系
     *
     * @param    rShContainSpBaseList    竖井和业务空间的关系对象列表
     */
    fun createsSp(rShContainSpBaseList: RSpContainShBaseList): SCreateResponse<RShContainSpBase> {
        return try {
            /** 成功集合 */
            val successList = ArrayList<Any>()
            /** 失败集合 */
            val failureList = ArrayList<Any>()
            rSh2SpService.delete("id2 = '${rShContainSpBaseList.spaceId}'")

            for (shaftId in rShContainSpBaseList.shaftIdList!!){
                val rSh2Sp = RSh2Sp()
                rSh2Sp.id2 = rShContainSpBaseList.spaceId
                rSh2Sp.id1 = shaftId
                rSh2Sp.projectId = Opt.projectId
                rSh2Sp.zoneType = rShContainSpBaseList.zoneType
                rSh2Sp.sign = 1
                rSh2Sp.type = "sh2sp"
                val replace = rSh2SpService.replace(rSh2Sp)
                if (replace){
                    successList.add(shaftId)
                }else{
                    failureList.add(rSh2Sp)
                }
            }
            if (successList.size>0){
                /** 发送消息 */
                rabbitMqService.sendRel(Opt.projectId!!, "sh2sp","13",rShContainSpBaseList.spaceId!!,successList.toJson()!!)
                if (failureList.size>0){
                    val sCreateResponse = SCreateResponse<RShContainSpBase>(SResponseType.success)
                    sCreateResponse.message ="失败对象："+failureList.toJson()
                    sCreateResponse
                }else{
                    val sCreateResponse = SCreateResponse<RShContainSpBase>(SResponseType.success)
                    sCreateResponse
                }
            }else{
                SCreateResponse(SResponseType.failure)
            }
        } catch (e:Exception){
            e.printStackTrace()
            SCreateResponse(SResponseType.failure,e.message.toString())
        }
    } // Function createsSp()

    /**
     * 创建竖井下业务空间关系
     *
     * @param    rShContainSpBaseList    竖井和业务空间的关系对象列表
     */
    fun createShSps(type: String?,rShContainSpBaseList: RShContainSpBaseList): SCreateResponse<RShContainSpBaseList> {
        return try {

            /** 成功集合 */
            val successList = ArrayList<Any>()
            /** 失败集合 */
            val failureList = ArrayList<Any>()
            val projectId = SPageContext.getHeader("projectId")
            if (!rShContainSpBaseList.spaceIdList.isNullOrEmpty()&&!type.isNullOrEmpty()){
                for (spaceId in rShContainSpBaseList.spaceIdList!!){
                    val rSh2Sp = RSh2Sp()
                    rSh2Sp.id1 = rShContainSpBaseList.shaftId
                    rSh2Sp.id2 = spaceId
                    rSh2Sp.projectId = projectId
                    rSh2Sp.zoneType = type
                    rSh2Sp.sign = 1
                    rSh2Sp.type = "sh2sp"
                    val replace = rSh2SpService.replace(rSh2Sp)
                    if (replace){
                        successList.add(spaceId)
                    }else{
                        failureList.add(rSh2Sp)
                    }
                }
                if (successList.size>0){
                    /** 发送消息 */
                    rabbitMqService.sendRel(Opt.projectId!!, "sh2sp","14",rShContainSpBaseList.shaftId!!,successList.toJson()!!)
                    try {
                        /** 处理关系标记 */
                        val listType = ArrayList<String>()
                        listType.add("sh2bd")
                        listType.add("eq2sh")
                        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 sCreateResponse = SCreateResponse<RShContainSpBaseList>(SResponseType.success)
                    if (failureList.size>0){
                        sCreateResponse.message ="失败对象："+failureList.toJson()
                    }
                    sCreateResponse
                }else{
                    SCreateResponse(SResponseType.failure)
                }
            }else{
                val sCreateResponse = SCreateResponse<RShContainSpBaseList>(SResponseType.success)
                sCreateResponse.message = "空间类型和空间列表不能为空"
                sCreateResponse
            }
        } catch (e: Exception) {
            e.printStackTrace()
            SCreateResponse(SResponseType.failure,e.message.toString())
        }
    }


    /**
     * 创建竖井下业务空间关系
     *
     * @param    rSpContainShBaseList    竖井和业务空间的关系对象列表
     */
    fun createSpShs(type: String,rSpContainShBaseList: RSpContainShBaseList): SCreateResponse<RSpContainShBaseList> {
        return try {
            /** 成功集合 */
            val successList = ArrayList<Any>()
            /** 失败集合 */
            val failureList = ArrayList<Any>()
            val projectId = SPageContext.getHeader("projectId")

            if (!rSpContainShBaseList.shaftIdList.isNullOrEmpty()){
                for (shaftId in rSpContainShBaseList.shaftIdList!!){
                    val rSh2Sp = RSh2Sp()
                    rSh2Sp.id2 = rSpContainShBaseList.spaceId
                    rSh2Sp.id1 = shaftId
                    rSh2Sp.projectId = projectId
                    rSh2Sp.zoneType = type
                    rSh2Sp.sign = 1
                    rSh2Sp.type = "sh2sp"
                    val replace = rSh2SpService.replace(rSh2Sp)
                    if (replace){
                        successList.add(rSh2Sp)
                    }else{
                        failureList.add(rSh2Sp)
                    }
                }
                if (successList.size>0){
                    /** 发送消息 */
                    rabbitMqService.sendRel(Opt.projectId!!, "sh2sp","14",rSpContainShBaseList.spaceId!!,successList.toJson()!!)

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

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

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

    /**
     * 创建竖井下业务空间关系
     *
     * @param    rShContainSpBaseList    竖井和业务空间的关系对象列表
     */
    fun createShSpsReplace(type: String,buildingId: String,floorId: String,rShContainSpBaseList: RShContainSpBaseList): SCreateResponse<RShContainSpBaseList> {
        return try {
            val projectId = SPageContext.getHeader("projectId")
            val allSpaceIdList = ArrayList<String>()//和竖井关联的并且为当前空间类型的业务空间id列表
            val spaceIdList = ArrayList<String>()//和竖井关联且为当前空间类型、所在建筑楼层为当前建筑楼层的的业务空间id列表
            val allSpaceIdFilterList = ArrayList<SFilter>()
            val zoneSpaceBaseTableService = SBaseService(SMybatisDao(ZoneSpace::class.java))


            //查出和当前竖井关联并为当前空间类型的的业务空间id
            val list1 =  rSh2SpService.select(SFilter.eq("projectId",projectId!!),SFilter.eq("Id1",rShContainSpBaseList.shaftId!!),SFilter.eq("zoneType",type)).projection("id2").distinct().exec()
            for(rShContainSpBase in list1){
                allSpaceIdList.add(rShContainSpBase.id2!!)
            }
            allSpaceIdFilterList.add(SFilter.eq("projectId",projectId))
            allSpaceIdFilterList.add(SFilter.eq("classCode",type))
            allSpaceIdFilterList.add(SFilter.eq("buildingId",buildingId))
            allSpaceIdFilterList.add(SFilter.eq("floorId",floorId))
            if (allSpaceIdList.size>0){
                allSpaceIdFilterList.add(SFilter.inList("id",allSpaceIdList))
            }
            var spaceList = zoneSpaceBaseTableService.select(allSpaceIdFilterList).projection("id").exec()
            for(zoneSpaceBaseTable in spaceList){
                spaceIdList.add(zoneSpaceBaseTable.id!!)
            }

            /** 成功集合 */
            val successList = ArrayList<Any>()
            /** 失败集合 */
            val failureList = ArrayList<Any>()
            if (spaceIdList.size>0){
                for(oldSpaceId in spaceIdList){
                    rSh2SpService.delete("Id1 = '${rShContainSpBaseList.shaftId}' and Id2 = '${oldSpaceId}' and type = 'sh2sp'")
                }
            }
            if (!rShContainSpBaseList.spaceIdList.isNullOrEmpty()){
                for (spaceId in rShContainSpBaseList.spaceIdList!!){
                    val rSh2Sp = RSh2Sp()
                    rSh2Sp.id1 = rShContainSpBaseList.shaftId
                    rSh2Sp.id2 = spaceId
                    rSh2Sp.projectId = projectId
                    rSh2Sp.sign = 1
                    rSh2Sp.zoneType = type
                    rSh2Sp.type = "sh2sp"
                    val replace = rSh2SpService.replace(rSh2Sp)
                    if (replace){
                        successList.add(rSh2Sp)
                    }else{
                        failureList.add(rSh2Sp)
                    }
                }
                if (successList.size>0){
                    try {
                        /** 处理关系标记 */
                        val listType = ArrayList<String>()
                        listType.add("sh2bd")
                        listType.add("eq2sh")
                        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 sCreateResponse = SCreateResponse<RShContainSpBaseList>(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())
        }
    }

    /**
     * 查询空间类型和名称
     */
    fun spaceTypeQuery(projectId: String, shaftId: String): SQueryResponse<SpaceInfoDic> {
        return try {
            var request = SQueryRequest()
            val service = SBaseService(SMybatisDao(SpaceInfoDic::class.java))
            val queryBuilder = service.select(request.filters)
            queryBuilder.tableName = "public.f_get_sh_space_type('$projectId','$shaftId')"
            val pageQuery = queryBuilder.pageQuery(1, 1000)
            SQueryResponse(pageQuery)
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, e.message!!)
        }
    } //  Fun spaceTypeQuery


}