/*
 * ********************************************************************************************************************
 *
 *                     :*$@@%$*:                         ;:                ;;    ;;
 *                   :@@%!  :!@@%:                       %!             ;%%@@%$ =@@@@@@@%;     @%@@@%%%%@@@@@
 *                  :@%;       :$=                       %%$$$%$$         ;$$  ;$@=   !@$
 *                  =@!                                  %!              @ $=;%   !@@@%:      !$$$$$$$$$$$$$$=
 *                  =@*                                  %!              @ $= % %@=   =%@!      %=
 *             *$%%! @@=        ;=$%%%$*:                %!              @ $= % =%%%%%%@$      *%:         =%
 *           %@@!:    !@@@%=$@@@@%!  :*@@$:              %!              @ $= % $*     ;@      @*          :%*
 *         ;@@!          ;!!!;:         ;@%:      =======@%========*     @ $$ % $%*****$@     :@$=*********=@$
 *         $@*   ;@@@%=!:                *@*
 *         =@$    ;;;!=%@@@@=!           =@!
 *          %@$:      =@%: :*@@@*       %@=                    Copyright (c) 2016-2019.  北京上格云技术有限公司
 *           ;%@@$=$@@%*       *@@@$=%@@%;
 *              ::;::             ::;::                                              All rights reserved.
 *
 * ********************************************************************************************************************
 */

package com.persagy.server.services.objects


import cn.sagacloud.server.datacenter.utils.IdUtils
import cn.sagacloud.server.datacenter.utils.ShaftNameUtil
import com.persagy.base.extensions.toDouble
import com.persagy.base.extensions.toJson
import com.persagy.database.SFilter
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.datacenter.models.entities.dict.DictSpaceProject
import com.persagy.server.datacenter.models.entities.graphtype.RelationTypeProject
import com.persagy.server.datacenter.models.entities.objects.Building
import com.persagy.server.datacenter.models.entities.objects.ZoneSpace
import com.persagy.server.datacenter.models.entities.rel.RSpinBd
import com.persagy.server.datacenter.models.entities.rel.RSpinFl
import com.persagy.server.datacenter.models.requests.DCSQueryRequest
import com.persagy.server.datacenter.models.requests.UpDataFloorAndBuildingRequests
import com.persagy.server.datacenter.models.response.SpaceSQueryResponse
import com.persagy.server.scanbuilding.UserLog
import com.persagy.server.services.assistant.ObjInfoService
import com.persagy.server.services.base.ServiceSpace
import com.persagy.server.services.dict.DClassDefService
import com.persagy.server.services.rel.RSpInBdService
import com.persagy.server.services.rel.RSpInFlService
import com.persagy.service.SBaseService
import com.persagy.service.SObjectService
import com.persagy.service.SPageContext
import com.persagy.service.models.enums.SResponseType
import com.persagy.service.models.requests.SUpdateRequest
import com.persagy.service.models.responses.SBaseResponse
import com.persagy.service.models.responses.SQueryResponse
import org.json.JSONObject
import org.slf4j.LoggerFactory

/**
 * 空间父类
 *
 * @author 邓婷婷
 */
object ZoneSpaceBaseService : ServiceSpace<ZoneSpace>(SMybatisDao(ZoneSpace::class.java)) {

    /** 日志 */
    private val logger = LoggerFactory.getLogger(EquipmentService::class.java)
    /** 业务空间类型服务 */
    var dictSpaceProjectService = SObjectService(SMybatisDao(DictSpaceProject::class.java))
    /** 关系总览服务 */
    val relationTypeProjectservice = SBaseService(SMybatisDao(RelationTypeProject::class.java))


    /**
     * 查询业务空间
     */
    fun querySpaces (request: DCSQueryRequest): SpaceSQueryResponse {
        return try {

//            val queryParser = SSyntaxParser(ByteArrayInputStream(request.filters!!.toByteArray()))
//            val filters  = queryParser.parserFilters()
//            logger.debug("filters1=${filters.toJson()}")
//            for (f in filters){
//                if (f.first  == "FloorId"){
//                    f.second
//                    logger.debug("filters= ${f.second} **************************************************************")
//                }
//            }






            val projectId = SPageContext.getHeader("ProjectId")

//            if(request.zoneType.isNullOrEmpty()&&request.zoneTypeList.isNullOrEmpty()){
//                val sQueryResponse = SQueryResponse<ZoneSpace>(SResponseType.failure)
//                sQueryResponse.message = "空间类型不能为空"
//                return sQueryResponse
//            }
            var spaceSQueryResponse = SpaceSQueryResponse()

            val listId = ArrayList<String>()
            if(!request.buildingId.isNullOrEmpty()&&!request.floorId.isNullOrEmpty()&&request.floorId != "isnull"){
                var rSpInFlList: ArrayList<RSpinFl>? = null
                if (!request.zoneType.isNullOrEmpty()){
                     rSpInFlList =  RSpInFlService.select(SFilter.eq("projectId",projectId!!),SFilter.eq("floorId",request.floorId!!),SFilter.eq("objectType",request.zoneType!!)).exec()
                }else if (!request.zoneTypeList.isNullOrEmpty()){
                     rSpInFlList =  RSpInFlService.select(SFilter.eq("projectId",projectId!!),SFilter.eq("floorId",request.floorId!!),SFilter.inList("objectType",request.zoneTypeList!!)).exec()
                }else{
                    rSpInFlList =  RSpInFlService.select(SFilter.eq("projectId",projectId!!),SFilter.eq("floorId",request.floorId!!)).exec()
                }
                if (rSpInFlList!=null&&rSpInFlList!!.size>0){

                    for (rSpInFl in rSpInFlList){
                        listId.add(rSpInFl.spaceId!!)
                    }
                }
                if (listId.size>0){
                    var listSFilter = ArrayList<SFilter>()
                    listSFilter.add(SFilter.eq("projectId",projectId!!))
                    listSFilter.add(SFilter.inList("id",listId))
                    if (!request.zoneType.isNullOrEmpty()){
                        listSFilter.add(SFilter.eq("objectType",request.zoneType!!))
                    }else if (!request.zoneTypeList.isNullOrEmpty()){
                        listSFilter.add(SFilter.inList("objectType",request.zoneTypeList!!))
                    }
                  val  pageQuery = pageQuery(request, listSFilter)
                    spaceSQueryResponse.message = pageQuery.message
                    spaceSQueryResponse.total = pageQuery.total
                    spaceSQueryResponse.result = pageQuery.result
                    spaceSQueryResponse.pageNumber = pageQuery.pageNumber
                    spaceSQueryResponse.pageSize = pageQuery.pageSize
                    spaceSQueryResponse.content = pageQuery.content
                    spaceSQueryResponse
                }

            }else if(!request.buildingId.isNullOrEmpty()&&!request.floorId.isNullOrEmpty()&&request.floorId == "isnull"){

               val floorList = FloorService.select(SFilter.eq("projectId",projectId!!),SFilter.eq("buildId",request.buildingId!!)).exec()
               if (floorList.size>0){
                   val listFloorId = ArrayList<String>()
                   for (floor in floorList){
                       listFloorId.add(floor.id!!)
                   }
                   if (!request.zoneType.isNullOrEmpty()){
                       val listSpId = ArrayList<String>()
                       val rSpInFlList = RSpInFlService.select(SFilter.eq("projectId", projectId!!), SFilter.inList("floorId", listFloorId),SFilter.eq("objectType",request.zoneType!!)).exec()
                       if (rSpInFlList.size>0){

                           for (rSpInFl in rSpInFlList){
                               listSpId.add(rSpInFl.spaceId!!)
                           }

                           val rSpInBdList = RSpInBdService.select(SFilter.eq("projectId", projectId), SFilter.eq("buildingId", request.buildingId!!), SFilter.eq("objectType", request.zoneType!!), SFilter.not(SFilter.inList("spaceId", listSpId))).exec()
                           if (rSpInBdList.size>0){
                               for (rSpInBd in rSpInBdList){
                                   listId.add(rSpInBd.spaceId!!)
                               }
                           }

                       }else{
                           val rSpInBdList = RSpInBdService.select(SFilter.eq("projectId", projectId), SFilter.eq("buildingId", request.buildingId!!), SFilter.eq("objectType", request.zoneType!!)).exec()

                           if (rSpInBdList.size>0){
                               for (rSpInBd in rSpInBdList){
                                   listId.add(rSpInBd.spaceId!!)
                               }
                           }
                       }

                       if (listId.size>0){
                           var listSFilter = ArrayList<SFilter>()
                           listSFilter.add(SFilter.eq("projectId",projectId!!))
                           listSFilter.add(SFilter.inList("id",listId))
                           listSFilter.add(SFilter.eq("objectType",request.zoneType!!))
                          val pageQuery = pageQuery(request, listSFilter)
                           spaceSQueryResponse.message = pageQuery.message
                           spaceSQueryResponse.total = pageQuery.total
                           spaceSQueryResponse.result = pageQuery.result
                           spaceSQueryResponse.pageNumber = pageQuery.pageNumber
                           spaceSQueryResponse.pageSize = pageQuery.pageSize
                           spaceSQueryResponse.content = pageQuery.content
                       }
                   }else {
                       val listSpId = ArrayList<String>()
                       var rSpInFlList: ArrayList<RSpinFl>? = null
                       if (!request.zoneTypeList.isNullOrEmpty()){
                            rSpInFlList = RSpInFlService.select(SFilter.eq("projectId", projectId!!), SFilter.inList("floorId", listFloorId),SFilter.inList("objectType",request.zoneTypeList!!)).exec()
                       }else{
                            rSpInFlList = RSpInFlService.select(SFilter.eq("projectId", projectId!!), SFilter.inList("floorId", listFloorId)).exec()
                       }

                       if (rSpInFlList.size>0){

                           for (rSpInFl in rSpInFlList){
                               listSpId.add(rSpInFl.spaceId!!)
                           }

                           val rSpInBdList = RSpInBdService.select(SFilter.eq("projectId", projectId), SFilter.eq("buildingId", request.buildingId!!), SFilter.eq("objectType", request.zoneType!!), SFilter.not(SFilter.inList("spaceId", listSpId))).exec()
                           if (rSpInBdList.size>0){
                               for (rSpInBd in rSpInBdList){
                                   listId.add(rSpInBd.spaceId!!)
                               }
                           }

                       }else{
                           var rSpInBdList: ArrayList<RSpinBd>
                           if (!request.zoneTypeList.isNullOrEmpty()){
                               rSpInBdList = RSpInBdService.select(SFilter.eq("projectId", projectId), SFilter.eq("buildingId", request.buildingId!!), SFilter.inList("objectType", request.zoneTypeList!!)).exec()
                           }else{
                               rSpInBdList = RSpInBdService.select(SFilter.eq("projectId", projectId), SFilter.eq("buildingId", request.buildingId!!)).exec()
                           }

                           if (rSpInBdList.size>0){
                               for (rSpInBd in rSpInBdList){
                                   listId.add(rSpInBd.spaceId!!)
                               }
                           }
                       }

                       if (listId.size>0){
                           var listSFilter = ArrayList<SFilter>()
                           listSFilter.add(SFilter.eq("projectId",projectId!!))
                           listSFilter.add(SFilter.inList("id",listId))
                           if (!request.zoneTypeList.isNullOrEmpty()){
                               listSFilter.add(SFilter.inList("objectType",request.zoneTypeList!!))
                           }
                         val   pageQuery = pageQuery(request, listSFilter)
                           spaceSQueryResponse.message = pageQuery.message
                           spaceSQueryResponse.total = pageQuery.total
                           spaceSQueryResponse.result = pageQuery.result
                           spaceSQueryResponse.pageNumber = pageQuery.pageNumber
                           spaceSQueryResponse.pageSize = pageQuery.pageSize
                           spaceSQueryResponse.content = pageQuery.content
                       }
                   }
               }else{
                   var rSpInFlList: ArrayList<RSpinBd>
                   if (!request.zoneType.isNullOrEmpty()){
                        rSpInFlList = RSpInBdService.select(SFilter.eq("projectId", projectId), SFilter.eq("buildingId", request.buildingId!!),SFilter.eq("objectType",request.zoneType!!)).exec()
                   }else if (!request.zoneTypeList.isNullOrEmpty()){
                        rSpInFlList = RSpInBdService.select(SFilter.eq("projectId", projectId), SFilter.eq("buildingId", request.buildingId!!),SFilter.inList("objectType",request.zoneTypeList!!)).exec()
                   }else{
                        rSpInFlList = RSpInBdService.select(SFilter.eq("projectId", projectId), SFilter.eq("buildingId", request.buildingId!!)).exec()
                   }

                   if (rSpInFlList.size>0){
                       for (rSpInFl in rSpInFlList){
                           listId.add(rSpInFl.spaceId!!)
                       }
                   }

                   if (listId.size>0){
                       var listSFilter = ArrayList<SFilter>()
                       listSFilter.add(SFilter.eq("projectId",projectId!!))
                       listSFilter.add(SFilter.inList("id",listId))
                       if (!request.zoneType.isNullOrEmpty()){
                           listSFilter.add(SFilter.eq("objectType",request.zoneType!!))
                       }else  if (!request.zoneTypeList.isNullOrEmpty()){
                           listSFilter.add(SFilter.inList("objectType",request.zoneTypeList!!))
                       }

                     val  pageQuery = pageQuery(request, listSFilter)
                       spaceSQueryResponse.message = pageQuery.message
                       spaceSQueryResponse.total = pageQuery.total
                       spaceSQueryResponse.result = pageQuery.result
                       spaceSQueryResponse.pageNumber = pageQuery.pageNumber
                       spaceSQueryResponse.pageSize = pageQuery.pageSize
                       spaceSQueryResponse.content = pageQuery.content
                   }

               }
            }else if (!request.buildingId.isNullOrEmpty()&&request.floorId.isNullOrEmpty()&&request.buildingId != "isnull"){
                var rSpInFlList: ArrayList<RSpinBd>
                if (!request.zoneType.isNullOrEmpty()){
                    rSpInFlList = RSpInBdService.select(SFilter.eq("projectId", projectId!!), SFilter.eq("buildingId", request.buildingId!!),SFilter.eq("objectType",request.zoneType!!)).exec()
                }else if (!request.zoneTypeList.isNullOrEmpty()){
                    rSpInFlList = RSpInBdService.select(SFilter.eq("projectId", projectId!!), SFilter.eq("buildingId", request.buildingId!!),SFilter.inList("objectType",request.zoneTypeList!!)).exec()
                }else{
                    rSpInFlList = RSpInBdService.select(SFilter.eq("projectId", projectId!!), SFilter.eq("buildingId", request.buildingId!!)).exec()
                }

                if (rSpInFlList.size>0){
                    for (rSpInFl in rSpInFlList){
                        listId.add(rSpInFl.spaceId!!)
                    }
                }
                if (listId.size>0){
                    var listSFilter = ArrayList<SFilter>()
                    listSFilter.add(SFilter.eq("projectId",projectId!!))
                    listSFilter.add(SFilter.inList("id",listId))
                    if (!request.zoneType.isNullOrEmpty()){
                        listSFilter.add(SFilter.eq("objectType",request.zoneType!!))
                    }else if (!request.zoneTypeList.isNullOrEmpty()){
                        listSFilter.add(SFilter.inList("objectType",request.zoneTypeList!!))
                    }
                   val pageQuery = pageQuery(request, listSFilter)
                    spaceSQueryResponse.message = pageQuery.message
                    spaceSQueryResponse.total = pageQuery.total
                    spaceSQueryResponse.result = pageQuery.result
                    spaceSQueryResponse.pageNumber = pageQuery.pageNumber
                    spaceSQueryResponse.pageSize = pageQuery.pageSize
                    spaceSQueryResponse.content = pageQuery.content
                }

            }else if (!request.buildingId.isNullOrEmpty()&&request.floorId.isNullOrEmpty()&&request.buildingId == "isnull"){
                logger.debug("未明确建筑****************************************************************************")
                val buildingList = BuildingService.select(SFilter.eq("projectId", projectId!!)).exec()

                if (buildingList.size>0){
                    logger.debug("未明确建筑4****************************************************************************")
                    for (building in buildingList){
                        val rSpInBdList : ArrayList<RSpinBd>
                        if (!request.zoneType.isNullOrEmpty()){
                            rSpInBdList = RSpInBdService.select(SFilter.eq("projectId", projectId!!), SFilter.eq("buildingId", building.id!!), SFilter.eq("objectType", request.zoneType!!)).exec()
                        }else if (!request.zoneTypeList.isNullOrEmpty()){
                            rSpInBdList = RSpInBdService.select(SFilter.eq("projectId", projectId!!), SFilter.eq("buildingId", building.id!!), SFilter.inList("objectType", request.zoneTypeList!!)).exec()
                        }else{
                            rSpInBdList =RSpInBdService.select(SFilter.eq("projectId", projectId!!), SFilter.eq("buildingId", building.id!!)).exec()
                        }

                        logger.debug("未明确建筑长度：${rSpInBdList.size}")
                            for (rSpInBd in rSpInBdList){
                                /** 需要被排除的空间id */
                                listId.add(rSpInBd.spaceId!!)
                            }
                    }

                            logger.debug("未明确建筑2****************************************************************************")
                            var listSFilter = ArrayList<SFilter>()
                            listSFilter.add(SFilter.eq("projectId",projectId!!))
                            if (listId.size>0) {
                                listSFilter.add(SFilter.not(SFilter.inList("id", listId)))
                            }
                            if (!request.zoneType.isNullOrEmpty()){
                                listSFilter.add(SFilter.eq("objectType",request.zoneType!!))
                            }else if (!request.zoneTypeList.isNullOrEmpty()){
                                listSFilter.add(SFilter.inList("objectType",request.zoneTypeList!!))
                            }
                           val pageQuery = pageQuery(request, listSFilter)
                    spaceSQueryResponse.message = pageQuery.message
                    spaceSQueryResponse.total = pageQuery.total
                    spaceSQueryResponse.result = pageQuery.result
                    spaceSQueryResponse.pageNumber = pageQuery.pageNumber
                    spaceSQueryResponse.pageSize = pageQuery.pageSize
                    spaceSQueryResponse.content = pageQuery.content
                    spaceSQueryResponse
                }else{
                    logger.debug("未明确建筑3****************************************************************************")
                        var listSFilter = ArrayList<SFilter>()
                        listSFilter.add(SFilter.eq("projectId",projectId!!))
                    if (!request.zoneType.isNullOrEmpty()){
                        listSFilter.add(SFilter.eq("objectType",request.zoneType!!))
                    }else if (!request.zoneTypeList.isNullOrEmpty()){
                        listSFilter.add(SFilter.inList("objectType",request.zoneTypeList!!))
                    }
                      val  pageQuery = pageQuery(request, listSFilter)
                    spaceSQueryResponse.message = pageQuery.message
                    spaceSQueryResponse.total = pageQuery.total
                    spaceSQueryResponse.result = pageQuery.result
                    spaceSQueryResponse.pageNumber = pageQuery.pageNumber
                    spaceSQueryResponse.pageSize = pageQuery.pageSize
                    spaceSQueryResponse.content = pageQuery.content
                }

            }else if (request.buildingId.isNullOrEmpty()&&request.floorId.isNullOrEmpty()){
                var listSFilter = ArrayList<SFilter>()
                listSFilter.add(SFilter.eq("projectId",projectId!!))
                if (!request.zoneType.isNullOrEmpty()){
                    listSFilter.add(SFilter.eq("objectType",request.zoneType!!))
                }else if (!request.zoneTypeList.isNullOrEmpty()){
                    listSFilter.add(SFilter.inList("objectType",request.zoneTypeList!!))
                }
              val   pageQuery = pageQuery(request, listSFilter)
                spaceSQueryResponse.message = pageQuery.message
                spaceSQueryResponse.total = pageQuery.total
                spaceSQueryResponse.result = pageQuery.result
                spaceSQueryResponse.pageNumber = pageQuery.pageNumber
                spaceSQueryResponse.pageSize = pageQuery.pageSize
                spaceSQueryResponse.content = pageQuery.content
            }

            if (spaceSQueryResponse.content.isNullOrEmpty()){
                spaceSQueryResponse.content = ArrayList<ZoneSpace>()
            }

            spaceSQueryResponse.zoneType = request.zoneType
            spaceSQueryResponse.floorId = request.floorId
            return spaceSQueryResponse
        } catch (e: Exception) {
            e.printStackTrace()
            val spaceSQueryResponse = SpaceSQueryResponse()
            spaceSQueryResponse.result = SResponseType.failure
            spaceSQueryResponse.message = e.message.toString()
            return spaceSQueryResponse
        }
    } // Fun

    /**
     * 查询业务空间的建筑楼层数量
     */
    fun spBuildingFloor(): SQueryResponse<Building>{
       return try {
            /** 项目id */
            val projectId = SPageContext.getHeader("ProjectId")

            val buildingList = BuildingService.select(SFilter.eq("projectId", projectId!!)).order("localName").exec()
            if (buildingList.size>0){
                for (building in buildingList){

                   val floorList = FloorService.select(SFilter.eq("projectId", projectId!!),SFilter.eq("buildId", building.id!!)).order("sequenceId desc").exec()
                    if (floorList.size>0){
                        building .floor = floorList
                    }
                }

                for (building in buildingList){

                   if (building.floor!=null&&building.floor!!.size>0){
                       for (floor in building.floor!!){

                           val rSpInFlList = RSpInFlService.select(SFilter.eq("projectId", projectId!!),SFilter.eq("floorId", floor.id!!)).exec()
                           if (rSpInFlList.size>0){
                               val setId = HashSet<String>()
                               for (rSpInFl in rSpInFlList){
                                   setId.add(rSpInFl.spaceId!!)
                               }
                               val spaceList = select(SFilter.eq("projectId", projectId!!), SFilter.inList("id", setId.toList()), SFilter.eq("state", 1)).exec()
                               floor.count = spaceList.size
                           }
                       }
                   }
                }

            }
            val sQueryResponse = SQueryResponse<Building>(SResponseType.success)
            sQueryResponse.content=buildingList
            sQueryResponse.total = buildingList.size.toLong()
           sQueryResponse
        } catch (e: Exception) {
            e.printStackTrace()
           SQueryResponse<Building>(SResponseType.failure,e.message.toString())
        }
    }

    /**
     * 查询业务空间所有类型
     */
    fun zoneTypequery(request: DCSQueryRequest):SQueryResponse<DictSpaceProject> {
        try {
            /** 项目id */
            val projectId = SPageContext.getHeader("ProjectId")

            val dictSpaceType = dictSpaceProjectService.select(SFilter.eq("projectId", projectId!!)).exec()
            if (dictSpaceType.size < 1) {
                val dClassDefList = DClassDefService.select(SFilter.eq("parentId", "Space"), SFilter.not(SFilter.eq("id", "Ispace"))).exec()
                if (dClassDefList.size > 0) {
                    for (dClassDef in dClassDefList) {
                        val dictSpaceProject = DictSpaceProject()
                        dictSpaceProject.projectId = projectId
                        dictSpaceProject.id = dClassDef.id
                        dictSpaceProject.name = dClassDef.name
                        dictSpaceProject.parentId = dClassDef.parentCode
                        dictSpaceProject.sign = 1
                        dictSpaceProjectService.replace(dictSpaceProject)
                    }
//                    val dictSpaceProject = DictSpaceProject()
//                    dictSpaceProject.projectId = projectId
//                    dictSpaceProject.id = "OtherZone"
//                    dictSpaceProject.name = "其它"
//                    dictSpaceProject.parentId = "Space"
//                    dictSpaceProject.sign = 1
//                    dictSpaceProjectService.replace(dictSpaceProject)
                }
            }

            if (request.floorId.isNullOrEmpty()) {
                val pageQuery = dictSpaceProjectService.pageQuery(request, arrayListOf(SFilter.eq("projectId", projectId!!), SFilter.eq("parentId","Space")))
                return pageQuery
            } else {
                val pageQuery = dictSpaceProjectService.pageQuery(request, arrayListOf(SFilter.eq("projectId", projectId!!), SFilter.eq("parentId","Space")))
                val contentList = pageQuery.content
                if (contentList != null && contentList.size > 0) {

                    for (content in contentList) {
                        if (content.name == "其它") {
                            if (content.zoneType != null && content.zoneType!!.size > 0) {
                                for (type in content.zoneType!!) {
                                    val rSpInFlList = RSpInFlService.select(SFilter.eq("projectId", projectId!!), SFilter.eq("floorId", request.floorId!!), SFilter.eq("objectType", type.id!!)).exec()
                                    if (rSpInFlList.size > 0) {
                                        val idSet = ArrayList<String>()
                                        for (rSpInFl in rSpInFlList) {
                                            idSet.add(rSpInFl.spaceId!!)
                                        }
                                        val zoneSpaceBaseList = ZoneSpaceBaseService.select(SFilter.eq("projectId", projectId), SFilter.inList("id", idSet.toList()), SFilter.eq("state", 1)).exec()
                                        if (zoneSpaceBaseList.size > 0) {
                                            type.count = zoneSpaceBaseList.size
                                        }
                                    }
                                }
                            }
                        } else {
                            val rSpInFlList = RSpInFlService.select(SFilter.eq("projectId", projectId!!), SFilter.eq("floorId", request.floorId!!), SFilter.eq("objectType", content.id!!)).exec()
                            if (rSpInFlList.size > 0) {
                                val idSet = ArrayList<String>()
                                for (rSpInFl in rSpInFlList) {
                                    idSet.add(rSpInFl.spaceId!!)
                                }
                                val zoneSpaceBaseList = ZoneSpaceBaseService.select(SFilter.eq("projectId", projectId), SFilter.inList("id", idSet.toList()), SFilter.eq("state", 1)).exec()
                                if (zoneSpaceBaseList.size > 0) {
                                    content.count = zoneSpaceBaseList.size
                                }
                            }
                        }
                    }
                }
                return pageQuery
            }
        } catch (e: Exception) {
            e.printStackTrace()
            return SQueryResponse<DictSpaceProject>(SResponseType.failure,e.message.toString())
        }
    } // Fun


    override fun onCreateBefore(entity: ZoneSpace): Boolean {
        if (entity.objectType.isNullOrEmpty()){
            return false
        }

        val projectId = SPageContext.getHeader("ProjectId")
        /** id */
        if (!entity.id.isNullOrEmpty()) {
            val isWith = entity.id!!.startsWith("Sp")
            if (!isWith) {
                entity.id = IdUtils.spaceIdCreate(projectId!!)
            }
        } else {
            entity.id = IdUtils.spaceIdCreate(projectId!!)
        }
        entity.projectId = projectId
        /** 空间名字 */
        if (entity.name.isNullOrEmpty()) {
            entity.name = ShaftNameUtil.shaftName("空间-")
        }
        try {
            if (entity.height==null||entity.height ==0.0){
                if (!entity.floorId.isNullOrEmpty()){
                    val entity1 = FloorService.select(SFilter.eq("id", entity.floorId!!)).entity()
                    if (entity1!=null){
                        if (!entity1.structureInfo.isNullOrEmpty()){
                            val containsKey = entity1.structureInfo!!.containsKey("Height")
                            if (containsKey){
                                entity.height = entity1.structureInfo!!["Height"].toString()!!.toDouble()
                            }
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return true
    }

    override fun onCreateSuccess(entityList: ArrayList<ZoneSpace>) {
        super.onCreateSuccess(entityList)
        for (zoneSpace in entityList) {
            ObjInfoService.createInfo(zoneSpace,true,"Sp",zoneSpace.objectType!!)
        }
        val projectId = SPageContext.getHeader("ProjectId")
        try {
            for (space in entityList){
                if (!space.buildingId.isNullOrEmpty()&&!space.floorId.isNullOrEmpty()){
                    val rSpinBd = RSpinBd()
                    rSpinBd.buildingId = space.buildingId
                    rSpinBd.objectType = space.objectType
                    rSpinBd.projectId = space.projectId
                    rSpinBd.spaceId = space.id
                    rSpinBd.sign = 1
                    RSpInBdService.insert(rSpinBd)
                    val rSpinFl = RSpinFl()
                    rSpinFl.buildingId = space.buildingId
                    rSpinFl.floorId = space.floorId
                    rSpinFl.projectId = space.projectId
                    rSpinFl.objectType = space.objectType
                    rSpinFl.spaceId = space.id
                    rSpinFl.sign = 1
                    RSpInFlService.insert(rSpinFl)
                }else if (!space.buildingId.isNullOrEmpty()&&space.floorId.isNullOrEmpty()){
                    val rSpinBd = RSpinBd()
                    rSpinBd.buildingId = space.buildingId
                    rSpinBd.objectType = space.objectType
                    rSpinBd.projectId = space.projectId
                    rSpinBd.spaceId = space.id
                    rSpinBd.sign = 1
                    RSpInBdService.insert(rSpinBd)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        try {
            /** 处理关系标记 */
            val listtype = ArrayList<String>()
//            listtype.add("sp2sp_SpaceNeighborhood_1")
//            listtype.add("sp2sp_SpaceNeighborhood_2")
//            listtype.add("sp2sp_SpaceNeighborhood_3")
//            listtype.add("sp2sp_SpaceNeighborhood_4")
            listtype.add("sp2sp_SpaceNeighborhood_5")
            listtype.add("sp2sp_TrafficNetwork_1")
//            listtype.add("sp2sp_TrafficNetwork_2")
//            listtype.add("sp2sp_TrafficNetwork_3")
            listtype.add("sp2sp_ConvectionNetwork_1")
            listtype.add("sp2sp_ConvectionNetwork_2")
            listtype.add("sp2sp_ConvectionNetwork_3")
            listtype.add("sp2sp_RadiationNetwork_1")
            listtype.add("sp2sp_RadiationNetwork_2")
            for (type in listtype){
                val entity = relationTypeProjectservice.select(SFilter.eq("projectId", projectId!!), SFilter.eq("relationType", type)).entity()
                if (entity!=null){
                    entity.computationalState = 2
                    relationTypeProjectservice.update(entity)
                }
            }
            val zoneSpace = entityList[0]

            val relationType = relationTypeProjectservice.select(SFilter.eq("projectId", projectId!!), SFilter.eq("relationType", "eq2sp_in"),SFilter.eq("zoneType", zoneSpace.objectType!!)).entity()
            if (relationType!=null){
                    relationType.computationalState = 2
                    relationTypeProjectservice.update(relationType)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onUpdateBefore(entity: ZoneSpace): Boolean {

        val list = ArrayList<String>()
        list.add("id")
        list.add("name")
        ZoneSpaceBaseService.update(entity,list)

        return !entity.objectType.isNullOrEmpty()
    }

    override fun onUpdateSuccess(entityList: ArrayList<ZoneSpace>) {
        super.onUpdateSuccess(entityList)
        for (zoneSpace in entityList) {
            ObjInfoService.createInfo(zoneSpace,false,"Sp",zoneSpace.objectType!!)
        }

        try {
            val projectId = SPageContext.getHeader("ProjectId")
            val comming = SPageContext.getHeader("comming")
            val account = SPageContext.getHeader("Account")
            for (entity in entityList){
                try {
                    if (!comming.isNullOrEmpty()){
                        if (comming == "app"){
                            val user = LocationPointServices.userService.select(SFilter.eq("projectId", projectId!!), SFilter.eq("phone", account!!)).entity()
                            val userLog = UserLog()
                            userLog.comming = "app"
                            userLog.action = "更新空间"
                            userLog.id = IdUtils.uuidCreate()
                            userLog.note = "项目ID: "+projectId+" 用户ID："+user!!.id+" 手机号："+ account+" 请求来源："+comming+ " "+entity.toJson()
                            userLog.phone = account
                            userLog.projectId = projectId
                            userLog.userId = user!!.id
                            userLog.name = user.name
                            userLog.objectId = entity.id
                            LocationPointServices.userLogService.insert(userLog)
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    /**
     * 修改空间对象的楼层建筑信息
     *
     * @param   upDataFloorAndBuildingRequestsList
     *
     */
    fun upDataFloorORBuilding(upDataFloorAndBuildingRequestsList :ArrayList<UpDataFloorAndBuildingRequests>): SBaseResponse {
        try {
            val projectId = SPageContext.getHeader("ProjectId")

            if (upDataFloorAndBuildingRequestsList.isNullOrEmpty()) {
                val sBaseResponse = SBaseResponse(SResponseType.failure)
                sBaseResponse.message = "不可以传入空数据"
                return sBaseResponse
            }
            for (upDataFloorAndBuildingRequests in upDataFloorAndBuildingRequestsList) {

                val spaceId = upDataFloorAndBuildingRequests.spaceId
                val id = upDataFloorAndBuildingRequests.id
                val type = upDataFloorAndBuildingRequests.type

                try {
                    if (!id.isNullOrEmpty()) {
                        if (id.startsWith("Fl")) {
                            val floor = FloorService.select(SFilter.eq("projectId", projectId!!), SFilter.eq("FloorID", id)).entity()

                            if (floor!=null){
                                /** 清除空间和建筑楼层的的数据 */
                                RSpInBdService.delete(SFilter.eq("projectId",projectId!!),SFilter.eq("spaceId",spaceId!!))
                                RSpInFlService.delete(SFilter.eq("projectId",projectId!!),SFilter.eq("spaceId",spaceId!!))
                                val rSpinFl = RSpinFl()
                                rSpinFl.floorId = floor.id
                                rSpinFl.projectId = projectId
                                rSpinFl.spaceId = spaceId
                                rSpinFl.objectType = type
                                rSpinFl.sign = 1
                                RSpInFlService.replace(rSpinFl)

                                val rSpinBd = RSpinBd()
                                rSpinBd.objectType = type
                                rSpinBd.buildingId = floor.buildId
                                rSpinBd.spaceId = spaceId
                                rSpinBd.sign = 1
                                rSpinBd.projectId = projectId
                                RSpInBdService.replace(rSpinBd)
                            }

                        } else if (id.startsWith("Bd")) {
                            /** 清除空间和建筑楼层的的数据 */
                            RSpInBdService.delete(SFilter.eq("projectId",projectId!!),SFilter.eq("spaceId",spaceId!!))
                            RSpInFlService.delete(SFilter.eq("projectId",projectId!!),SFilter.eq("spaceId",spaceId!!))
                            val rSpinBd = RSpinBd()
                            rSpinBd.objectType = type
                            rSpinBd.buildingId = id
                            rSpinBd.spaceId = spaceId
                            rSpinBd.sign = 1
                            rSpinBd.projectId = projectId
                            RSpInBdService.replace(rSpinBd)
                        }
                    } else {
                        /** 清除空间和建筑楼层的的数据 */
                        RSpInBdService.delete(SFilter.eq("projectId",projectId!!),SFilter.eq("spaceId",spaceId!!))
                        RSpInFlService.delete(SFilter.eq("projectId",projectId!!),SFilter.eq("spaceId",spaceId!!))
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                val zoneSpace = ZoneSpace()
                zoneSpace.id = spaceId
                if (!id.isNullOrEmpty()) {
                    if (id.startsWith("Fl")) {
                        zoneSpace.floorId = id
                        val floor = FloorService.select(SFilter.eq("projectId", projectId!!), SFilter.eq("FloorID", id)).entity()
                        zoneSpace.buildingId = floor?.buildId
                        val list = ArrayList<String>()
                        list.add("FloorId")
                        list.add("BuildingId")
                       update(zoneSpace, list)
                    } else if (id.startsWith("Bd")) {
                        val list = ArrayList<String>()
                        list.add("FloorId")
                        list.add("BuildingId")
                        zoneSpace.buildingId = id
                        zoneSpace.floorId = null
                        update(zoneSpace, list)
                    }
                } else {
                    /** 清空建筑楼层 */
                    val list = ArrayList<String>()
                    list.add("FloorId")
                    list.add("BuildingId")
                    zoneSpace.buildingId = null
                    zoneSpace.floorId = null
                    update(zoneSpace, list)
                }
                if (type == "AirConditioningZone"||type == "CleanZone"||type == "DomesticWaterSupplyZone"
                        ||type == "FireZone"||type == "FunctionZone"||type == "GeneralZone"
                        ||type == "HeatingZone"||type == "LightingZone"||type == "NetworkZone"
                        ||type == "PowerSupplyZone"||type == "SecurityZone"||type == "TenantZone" ){
                    /** 发送消息 */
                    sendMessages(projectId!!, spaceId!!, id)
                }
            }
            return SBaseResponse(SResponseType.success)
        } catch (e: Exception) {
            e.printStackTrace()
            return SBaseResponse(SResponseType.failure)
        }

    } // Function upDataFloorORBuilding

    /**
     * 发送消息
     *
     * @param   projectId   项目id
     * @param   spaceId     业务空间id
     * @param   id          楼层或建筑id
     */
    fun sendMessages(projectId: String, spaceId: String,id: String?){
        try {
            val jsonObject = JSONObject()
            jsonObject.put("type", "20")
            jsonObject.put("projectId", projectId)
            jsonObject.put("id", spaceId)
            jsonObject.put("linkId",id)
            /** 发送消息 */
            messageHandler.sendMessage(jsonObject.toString())
        } catch (e: Exception) {
            e.printStackTrace()
        }
    } // Function sendMessages

    fun upDateOutline(request: SUpdateRequest<ZoneSpace>): SBaseResponse{
        val projectId = SPageContext.getHeader("ProjectId")
        if (!request.projection.isNullOrEmpty()){
            request.projection!!.clear()
        }
        val list = ArrayList<String>()
        list.add("Outline")
        request.projection = list
        val zoneSpace = request.content!![0]
        val updateList = ZoneSpaceBaseService.updateList(request)

        try {
            /** 处理关系标记 */
            val listtype = ArrayList<String>()
//            listtype.add("sp2sp_SpaceNeighborhood_1")
//            listtype.add("sp2sp_SpaceNeighborhood_2")
//            listtype.add("sp2sp_SpaceNeighborhood_3")
//            listtype.add("sp2sp_SpaceNeighborhood_4")
            listtype.add("sp2sp_SpaceNeighborhood_5")
//            listtype.add("sp2sp_TrafficNetwork_1")
//            listtype.add("sp2sp_TrafficNetwork_2")
            listtype.add("sp2sp_TrafficNetwork_3")
            listtype.add("sp2sp_ConvectionNetwork_1")
            listtype.add("sp2sp_ConvectionNetwork_2")
            listtype.add("sp2sp_ConvectionNetwork_3")
            listtype.add("sp2sp_RadiationNetwork_1")
            listtype.add("sp2sp_RadiationNetwork_2")
            for (type in listtype){
                val entity = relationTypeProjectservice.select(SFilter.eq("projectId", projectId!!), SFilter.eq("relationType", type)).entity()
                if (entity!=null){
                    entity.computationalState = 2
                    relationTypeProjectservice.update(entity)
                }
            }
            val relationType = relationTypeProjectservice.select(SFilter.eq("projectId", projectId!!), SFilter.eq("relationType", "eq2sp_in"),SFilter.eq("zoneType", zoneSpace.objectType!!)).entity()
            if (relationType!=null){
                    relationType.computationalState = 2
                    relationTypeProjectservice.update(relationType)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return updateList
    }

    /**
     * @Description:删除成功之后
     */
    override fun onDeleteSuccess(entityList: ArrayList<ZoneSpace>) {
        super.onDeleteSuccess(entityList)
        try {
            val projectId = SPageContext.getHeader("ProjectId")
            for (entity in entityList) {
                ObjInfoService.delete(SFilter.eq("projectId",projectId!!), SFilter.eq("objId",entity.id!!), SFilter.eq("objType","Sp"))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

} // Object ZoneSpaceBaseService