/*
 * *********************************************************************************************************************
 *
 *          !!
 *        .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.service.objects

import com.alibaba.fastjson.JSONArray
import com.persagy.base.extensions.toJson
import com.persagy.database.SFilter
import com.persagy.database.SQueryBuilder
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.Opt
import com.persagy.server.dao.mappers.CustomSql
import com.persagy.server.datacenter.models.entities.dict.EquipFamily
import com.persagy.server.datacenter.models.entities.dictnew.DefClass
import com.persagy.server.datacenter.models.entities.objects.Equipment
import com.persagy.server.datacenter.models.entities.objects.Property
import com.persagy.server.datacenter.models.entities.objects.ZoneSpace
import com.persagy.server.datacenter.models.entities.rel.REq2Sp
import com.persagy.server.datacenter.models.entities.rel.RSpinBd
import com.persagy.server.datacenter.models.entities.rel.RSpinFl
import com.persagy.server.datacenter.models.response.EquipAssetComponentsReqponse
import com.persagy.server.models.ComponentProperty
import com.persagy.server.models.EquipComDel
import com.persagy.server.models.PropertySupplement
import com.persagy.server.models.VEquipComponentCount
import com.persagy.server.models.requests.EquipUpDateEnclosure
import com.persagy.server.models.requests.EquipUpDateEnclosureRequest
import com.persagy.server.service.CustomSqlService
import com.persagy.server.service.EquipAssetComponentsReqponseService
import com.persagy.server.service.REqInShService
import com.persagy.server.service.RSyEqService
import com.persagy.server.service.base.Service
import com.persagy.server.utils.DataVerification
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.SCreateRequest
import com.persagy.service.models.requests.SQueryRequest
import com.persagy.service.models.responses.SBaseResponse
import com.persagy.service.models.responses.SCountResponse
import com.persagy.service.models.responses.SCreateResponse
import com.persagy.service.models.responses.SQueryResponse
import com.persagy.service.utils.SSpringContextUtil
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.RequestBody


/**
 * 设备信息服务
 *
 * @author 张维新
 */
object EquipmentService : Service<Equipment>(SMybatisDao(Equipment::class.java)) {

    /** 日志 */
    private val logger = LoggerFactory.getLogger(EquipmentService::class.java)
    @Autowired
    lateinit var mapper: CustomSql
    /** 自定义sql */
    val customSqlService by lazy {
        SSpringContextUtil.getBean(CustomSqlService::class.java) as CustomSqlService
    }

    val rEq2SpService = SBaseService(SMybatisDao(REq2Sp::class.java))
    val rSpInFlService = SObjectService(SMybatisDao(RSpinFl::class.java))
    val rSpinBdService = SObjectService(SMybatisDao(RSpinBd::class.java))
    /** 平台集团对象类型 */
    private val defClassService = SObjectService(SMybatisDao(DefClass::class.java))

    /**
     * 查询之前操作
     */
    override fun onQueryBefore(queryBuilder: SQueryBuilder<Equipment>) {
        queryBuilder.tableName = "v_equipment"
        return
    }

    /**
     * 查询统计之前的操作
     */
    override fun onCountBefore(queryBuilder: SQueryBuilder<Equipment>) {
        queryBuilder.tableName = "v_equip_property_component"
        return
    }

    /**
     * 查询设备信息 关联的部件 资产信息
     *
     * @param   request     查询信息条件
     * @return              查询结果
     */
    fun getEquipAssetComponent(request: SQueryRequest): SQueryResponse<EquipAssetComponentsReqponse> {
        return try {
            val pageQuery = EquipAssetComponentsReqponseService.pageQuery(request, arrayListOf(SFilter.eq("projectId", SPageContext.getHeader("projectId")!!)))
            DataVerification.getEquipAssetComponentsToolsTwo(pageQuery.content!!)
            if(pageQuery.result == SResponseType.success&&pageQuery.content!!.size>0){
                val content = pageQuery.content!![0]
                val exec1 =defClassService.select(SFilter.eq("projectId",Opt.projectId!!),SFilter.eq("equipmentCode",content.classCode!!)).exec()
                if (exec1!=null&&exec1.size>0){
                    pageQuery.message = "1"
                }else{
                    pageQuery.message = "0"
                }
                content.componentCategory = exec1
            }
            pageQuery
        } catch (e: Throwable) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, e.message!!)
        }
    } // Function getEquipAssetComponent()

    /**
     * 查询当前设备下的部件分类数量
     *
     * @param   request     查询信息条件
     * @return              查询结果
     */
    fun getComponentCount(request: SQueryRequest): SQueryResponse<VEquipComponentCount> {
        return try {
            logger.debug("getEquipAssetComponent =${request.toJson()}")
            val service = SBaseService(SMybatisDao(VEquipComponentCount::class.java))
            val queryBuilder = service.select(request.filters)
//                    .filter(SFilter.eq("ProjectId", SPageContext.getHeader("projectId")!!))
            if (null != request.projection) {
                queryBuilder.projection(request.projection!!)
            }
            if (null != request.orders) {
                queryBuilder.order(request.orders!!)
            }
            val sPageQueryInfo = queryBuilder.pageQuery(request.pageNumber, request.pageSize)
            SQueryResponse(sPageQueryInfo)
        } catch (e: Throwable) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, e.message!!)
        }
    } // Function getEquipAssetComponent()

    /**
     * 查询部件关联的资产
     *
     * @param   request     查询条件
     */
    fun getComponentProperty(request: SQueryRequest): SQueryResponse<ComponentProperty> {
        return try {
            logger.debug("getEquipAssetComponent =${request.toJson()}")
            val service = SBaseService(SMybatisDao(ComponentProperty::class.java))
            val queryBuilder = service.select(request.filters)
                    .filter(SFilter.eq("ProjectId", SPageContext.getHeader("projectId")!!))
            if (null != request.projection) {
                queryBuilder.projection(request.projection!!)
            }
            if (null != request.orders) {
                queryBuilder.order(request.orders!!)
            }
            val sPageQueryInfo = queryBuilder.pageQuery(request.pageNumber, request.pageSize)
            SQueryResponse(sPageQueryInfo)
        } catch (e: Throwable) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, e.message!!)
        }
    } // Function getComponentProperty()

//    /**
//     * 所有部件的分类数量 对应的设备分类
//     *
//     * @param   request      条件
//     */
//    fun  getVAllComponentCategoryCount(request: SQueryRequest): SQueryResponse<VAllComponentCategoryCount>{
//        return try {
//            logger.debug("getVAllComponentCategoryCount =${request.toJson()}")
//            val service = SBaseService(SMybatisDao(VAllComponentCategoryCount::class.java))
//            val queryBuilder =service.select(request.filters)
//            if (null != request.projection) {
//                queryBuilder.projection(request.projection!!)
//            }
//            if (null != request.orders) {
//                queryBuilder.order(request.orders!!)
//            }
//            val sPageQueryInfo = queryBuilder.pageQuery(request.pageNumber, request.pageSize)
//            SQueryResponse(sPageQueryInfo)
//        } catch (e: Throwable) {
//            e.printStackTrace()
//            SQueryResponse(SResponseType.failure, e.message!!)
//        }
//    } // Function getComponentProperty()

    /**
     * 批量创建资产
     *
     * @param   request     查询条件
     */
    fun batchCreationProperty(request: SQueryRequest): SCreateResponse<Equipment> {
        return try {
            val queryBuilder = select(request.filters)
                    .filter(SFilter.eq("ProjectId", SPageContext.getHeader("projectId")!!))
            queryBuilder.tableName = "v_equip_property_component"
            if (null != request.projection) {
                queryBuilder.projection(request.projection!!)
            }
            if (null != request.orders) {
                queryBuilder.order(request.orders!!)
            }
            val pageInfo = queryBuilder.pageQuery(request.pageNumber, request.pageSize)
            pageInfo.content
            if (pageInfo.content != null && pageInfo.content!!.size < 1000) {
                val content = pageInfo.content
                val creationProperty = creationProperty(content)
                SCreateResponse(SResponseType.success)
            } else {
                val content = pageInfo.content
                creationProperty(content)
                batchCreationProperty(request)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            SCreateResponse(SResponseType.failure, e.message!!)
        }
    } // Function batchCreation()

    /**
     * 批量创建设备
     *
     * @param   listEquip   设备列表
     */
    private fun creationProperty(listEquip: ArrayList<Equipment>?): SCreateResponse<Property> {
        val listProperty = ArrayList<Property>()
        val sCreateRequest = SCreateRequest<Property>()
        val projectId = SPageContext.getHeader("projectId")
        try {
            if (!listEquip.isNullOrEmpty()) {
                val service = SBaseService(SMybatisDao(EquipFamily::class.java))
                for (equip in listEquip!!) {
                    val family = service.select("equipCode = '${equip.classCode}'").entity()
                    val property = Property()
                    property.projectId = equip.projectId
                    property.buildingId = equip.buildingId
                    property.floorId = equip.floorId
                    property.family = family?.family
                    property.bimLocation = equip.bimLocation
                    property.bimId = equip.bimId
                    property.equipId = equip.id
                    listProperty.add(property)
                }
                sCreateRequest.content = listProperty
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return PropertyService.createList(sCreateRequest)
    } // Function creationProperty()


    /**
     * 查询不在当前系统下的设备
     *
     * @param   sysId       系统id
     * @param   request     查询条件
     */
    fun queryBeforeEquipSy(sysId: String, request: SQueryRequest): SQueryResponse<Equipment> {

        return try {
            val projectId = SPageContext.getHeader("projectId")
            val rSyEqList = RSyEqService.select(SFilter.eq("SysID", sysId), SFilter.eq("projectId", projectId!!)).exec()
            val list = ArrayList<String>()
            val listf = ArrayList<SFilter>()
            for (rSyEq in rSyEqList){
                list.add(rSyEq.equipId!!)
            }
            if (list.size>0){
                listf.add(SFilter.eq("projectId",projectId))
                listf.add(SFilter.not(SFilter.inList("id",list)))
            }else{
                listf.add(SFilter.eq("projectId",projectId))
            }
            pageQuery(request,listf)
//            val queryBuilder = select(request.filters)
//            queryBuilder.tableName = "f_equip_unsys('${SPageContext.getHeader("projectId")}','$sysId')"
//            if (null != request.projection) {
//                queryBuilder.projection(request.projection!!)
//            }
//            if (null != request.orders) {
//                queryBuilder.order(request.orders!!)
//            }
//            val sPageQueryInfo = queryBuilder.pageQuery(request.pageNumber, request.pageSize)
//            SQueryResponse(sPageQueryInfo)
        } catch (e: Throwable) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, e.message!!)
        }
    }// Function queryBeforeEquipSy()


    /**
     * 查询不在当前空间下的设备
     */
    fun pageQueryEquip(type: String, spaceId: String, request: SQueryRequest): SQueryResponse<Equipment> {
        return try {
            val projectId = SPageContext.getHeader("projectId")

            val rEqInSpList = rEq2SpService.select(SFilter.eq("Id2", spaceId), SFilter.eq("projectId",projectId!!),SFilter.eq("type","eq2sp_in")).exec()
            val list = ArrayList<String>()
            val listf= ArrayList<SFilter>()
            for (rEqForSpBase in rEqInSpList){
                list.add(rEqForSpBase.id1!!)
            }

            if (list.size>0){
                listf.add(SFilter.eq("projectId",projectId))
                listf.add(SFilter.not(SFilter.inList("id",list)))
            }else{
                listf.add(SFilter.eq("projectId",projectId))
            }
            pageQuery(request,listf)

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

    /**
     * 查询没有服务于当前空间的设备
     */
    fun pageQueryForEquip(type: String, spaceId: String, @RequestBody request: SQueryRequest): SQueryResponse<Equipment> {
        return try {
            val projectId = SPageContext.getHeader("projectId")

            val rEqForSpBaseList = rEq2SpService.select(SFilter.eq("Id2", spaceId),SFilter.eq("projectId", projectId!!),SFilter.eq("type","eq2sp_for")).exec()
            val list = ArrayList<String>()
            val listf= ArrayList<SFilter>()
            for (rEqForSpBase in rEqForSpBaseList){
                list.add(rEqForSpBase.id1!!)
            }

            if (list.size>0){
                listf.add(SFilter.eq("projectId",projectId))
                listf.add(SFilter.not(SFilter.inList("equipId",list)))
            }else{
                listf.add(SFilter.eq("projectId",projectId))
            }
            pageQuery(request,listf)
        } catch (e : Exception){
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, e.message ?: e.message ?: "未知异常！")
        }
    } // Function pageQueryForEquip()

    /**
     * 查询不在当前竖井下的设备
     */
    fun pageQueryShaftEquip(shaftId: String, request: SQueryRequest): SQueryResponse<Equipment> {
        return try {
            val projectId = SPageContext.getHeader("projectId")

            val rEqInSpList = REqInShService.select(SFilter.eq("shaftId", shaftId), SFilter.eq("projectId",projectId!!)).exec()
            val list = ArrayList<String>()
            val listf= ArrayList<SFilter>()
            for (rEqInSp in rEqInSpList){
                list.add(rEqInSp.equipId!!)
            }

            if (list.size>0){
//                request.filters+"; projectId = '$projectId'; not equipId in [${list.toJson()}] "
                listf.add(SFilter.eq("projectId",projectId))
                listf.add(SFilter.not(SFilter.inList("equipId",list)))
            }else{
//                request.filters+"; projectId = '$projectId'"
                listf.add(SFilter.eq("projectId",projectId))
            }
//            logger.debug("request11111 =${request.toJson()}")
            val pageQuery = pageQuery(request, listf)
            pageQuery
//            val queryBuilder = select(request.filters)
//
//            queryBuilder.tableName = "f_uneq_in_space('$projectId','$type','$spaceId')"
//            /** 排序条件 */
//            if (null != request.orders) {
//                queryBuilder.order(request.orders!!)
//            }
//
//            /** 去重 */
//            if (null != request.distinct && request.distinct!!) {
//                queryBuilder.distinct()
//            }
//
//            /** 映射标志 */
//            if (null != request.projection) {
//                queryBuilder.projection(request.projection!!)
//            }
//            val pageInfo = queryBuilder.pageQuery(request.pageNumber,request.pageSize)
//            SQueryResponse(pageInfo)
        } catch (e : Exception){
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, e.message ?: e.message ?: "未知异常！")
        }
    } // Function pageQuery()


    /**
     * 根据空间轮廓 计算设备的坐标是否在空间内
     */
    fun unSpaceForEqPoint(type: String, spaceId: String, request: SQueryRequest): SQueryResponse<Equipment>{

        return try {
            val zoneSpaceBaseTable = SObjectService(SMybatisDao(ZoneSpace::class.java))

            val sQueryRequest = SQueryRequest()
            val projectId = SPageContext.getHeader("projectId")
            val queryBuilder = select(sQueryRequest.filters)
            val space = zoneSpaceBaseTable.select(SFilter.eq("id", spaceId)).entity()
//            RSpInBdService.select(SFilter.eq("spaceId",spaceId), SFilter.eq("objectType",type),SFilter.eq("projectId",type)).entity()

            var floorId: String? = null
            var buildingId: String? = null
            val entity = rSpInFlService.select(SFilter.eq("projectId", projectId!!),SFilter.eq("spaceId", spaceId!!)).entity()
            if (entity!=null){
                buildingId = entity.buildingId
                floorId = entity.floorId
            }
            /** 解析器，获取filters中的字段值 */
//            val parser = SSyntaxParser(ByteArrayInputStream(request.filters!!.toByteArray()))
//            val filterList = parser.parserFilters()
//            val filterList = queryBuilder.filterList
//            for (filter in filterList){
//                if (filter.first.toString() == "BuildingId"){
//                    buildingId = filter.second.toString()
//                }else if (filter.first.toString() == "FloorId"){
//                    floorId = filter.second.toString()
//                }
//            }

            logger.debug("buildingId = $buildingId")
            if (!buildingId.isNullOrEmpty()&&!floorId.isNullOrEmpty()){
                val entity = rSpInFlService.select(SFilter.eq("buildingId", buildingId!!), SFilter.eq("floorId", floorId!!), SFilter.eq("spaceId", spaceId!!)).entity()
                if (entity!=null){
                    queryBuilder.tableName = "f_uneq_for_space_point('$projectId','$type','$spaceId','${buildingId}','${floorId}')"

//            val pageInfo = queryBuilder.pageQuery(request.pageNumber,request.pageSize)
                    val exec = queryBuilder.exec()

                    logger.debug("数量= ${exec!!.toJson()}")
                    if (exec!!.size>0){
                        val list = ArrayList<String>()
                        val listF = ArrayList<SFilter>()
                        for (content in exec){
                            list.add(content.id!!)
                        }
                        logger.debug("数量= ${list.size} *************************")
                        if (list.size>0){
                            listF.add(SFilter.eq("projectId",projectId!!))
                            listF.add(SFilter.inList("id",list))
                        }
                        SQueryRequest()
                        val pageQuery = pageQuery(request,listF)
                        pageQuery
                    }else{
                        SQueryResponse(SResponseType.success)
                    }
                }else{
                    SQueryResponse(SResponseType.success)
                }


            }else{
                SQueryResponse(SResponseType.success)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure,  e.message.toString() )
        }

    }  // Function pageQuery()

    /**
     * 根据空间轮廓 计算设备的坐标是否在空间内
     */
    fun unSpaceInEqPoint(type: String, spaceId: String, request: SQueryRequest): SQueryResponse<Equipment>{

        return try {
            val zoneSpaceBaseTable = SObjectService(SMybatisDao(ZoneSpace::class.java))
            val sQueryRequest = SQueryRequest()
            val projectId = SPageContext.getHeader("projectId")
            val queryBuilder = select(request.filters)

            var floorId: String? = null
            var buildingId: String? = null
            val entity = rSpInFlService.select(SFilter.eq("projectId", projectId!!),SFilter.eq("spaceId", spaceId!!)).entity()
            if (entity!=null){
                buildingId = entity.buildingId
                floorId = entity.floorId
            }
//            val filterList = queryBuilder.filterList
//            for (filter in filterList){
//                if (filter.first.toString() == "BuildingId"){
//                    buildingId = filter.second.toString()
//                }else if (filter.first.toString() == "FloorId"){
//                    floorId = filter.second.toString()
//                }
//            }

            if (!buildingId.isNullOrEmpty()&&!floorId.isNullOrEmpty()){
                val entity = rSpInFlService.select(SFilter.eq("buildingId", buildingId!!), SFilter.eq("floorId", floorId!!), SFilter.eq("spaceId", spaceId!!)).entity()
                if (entity!=null){
                    val space = zoneSpaceBaseTable.select(SFilter.eq("RoomID", spaceId)).entity()
                    queryBuilder.tableName = "f_uneq_in_space_point('$projectId','$type','$spaceId','${buildingId}','${floorId}')"

                    val exec = queryBuilder.exec()
//            val pageInfo = queryBuilder.pageQuery(request.pageNumber,request.pageSize)

                    if (exec!!.size>0){
                        val list = ArrayList<String>()
                        val listF = ArrayList<SFilter>()
                        for (content in exec){
                            list.add(content.id!!)
                        }
                        if (list.size>0){
                            listF.add(SFilter.eq("projectId",projectId!!))
                            listF.add(SFilter.inList("id",list))
                        }
                        val pageQuery = pageQuery(request, listF)
                        pageQuery
                }else{
                        val sQueryResponse = SQueryResponse<Equipment>(SResponseType.success)
                        sQueryResponse.content = ArrayList<Equipment>()
                        sQueryResponse
                }
            }else{
                    SQueryResponse(SResponseType.success)
            }
            }else{
                SQueryResponse(SResponseType.success)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure,  e.message.toString() )
        }

    }  // Function unSpaceInEqPoint()




    /**
     * 查询不在当前空间下的设备
     */
    fun pageQueryEquipComputRelationship(type: String, spaceId: String,sign: String, @RequestBody request: SQueryRequest): SQueryResponse<Equipment> {
        return try {
            val projectId = SPageContext.getHeader("projectId")
            val queryBuilder = select(request.filters)

            if (sign == "in"){
                queryBuilder.tableName = "f_uneq_in_space('$projectId','$type','$spaceId')"
            }else if (sign == "for"){
                queryBuilder.tableName = "f_uneq_for_space('$projectId','$type','$spaceId')"
            }

            /** 排序条件 */
            if (null != request.orders) {
                queryBuilder.order(request.orders!!)
            }

            /** 去重 */
            if (null != request.distinct && request.distinct!!) {
                queryBuilder.distinct()
            }

            /** 映射标志 */
            if (null != request.projection) {
                queryBuilder.projection(request.projection!!)
            }
            val pageInfo = queryBuilder.pageQuery(request.pageNumber,request.pageSize)


            SQueryResponse(pageInfo)
        } catch (e : Exception){
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, e.message ?: e.message ?: "未知异常！")
        }
    } // Function pageQuery()

    /**
     * 计算
     */
    fun computational(x: Double, y: Double,spaceId: String){
        val request = SQueryRequest()
        val queryBuilder = select(request.filters)
        queryBuilder.tableName = "is_point_in_polygon('$x','$y','$spaceId')"

        /** 排序条件 */
        if (null != request.orders) {
            queryBuilder.order(request.orders!!)
        }

        /** 去重 */
        if (null != request.distinct && request.distinct!!) {
            queryBuilder.distinct()
        }

        /** 映射标志 */
        if (null != request.projection) {
            queryBuilder.projection(request.projection!!)
        }
        val pageInfo = queryBuilder.pageQuery(request.pageNumber,request.pageSize)
    }

    /**
     * 修改设备的附件,增量方式
     */
    fun equipUpDateEnclosurs(equipUpDateEnclosureRequest: EquipUpDateEnclosureRequest<EquipUpDateEnclosure>) : SBaseResponse {
         return try {
            val projectId = SPageContext.getHeader("projectId")
            val equipUpDateEnclosureList = equipUpDateEnclosureRequest.content
            if (!equipUpDateEnclosureList.isNullOrEmpty()){
                for (equipUpDateEnclosure in equipUpDateEnclosureList){
                    /** id不能为空 */
                    if (equipUpDateEnclosure.equipId.isNullOrEmpty()){
                        val sBaseResponse = SBaseResponse(SResponseType.failure)
                        sBaseResponse.message = "设备id不能为空"
                        sBaseResponse
                    }
                    val equip = select(SFilter.eq("projectId", projectId!!), SFilter.eq("id", equipUpDateEnclosure.equipId!!)).entity()

                    if (equip == null){
                        continue
                    }
                    logger.debug("设备id= ${equip?.id}")
                    if (!equipUpDateEnclosure.pic.isNullOrEmpty()){
                        if (!equip!!.infos.isNullOrEmpty()) {
                            val containsKey1 = equip!!.infos!!.containsKey(Opt.PIC)
                            if (containsKey1) {
                                val any = equip!!.infos!![Opt.PIC] as JSONArray
                                any.addAll(equipUpDateEnclosure.pic!!)
                                equip!!.infos!![Opt.PIC] = any
                            } else {
                                equip!!.infos!![Opt.PIC] = equipUpDateEnclosure.pic!!
                            }
                        }
                    }
                    if (!equipUpDateEnclosure.archive.isNullOrEmpty()){
                        val containsKey1 = equip!!.infos!!.containsKey(Opt.ARCHIVE)
                        if (containsKey1) {
                            val any = equip!!.infos!![Opt.ARCHIVE] as JSONArray
                            any.addAll(equipUpDateEnclosure.archive!!)
                            equip!!.infos!![Opt.ARCHIVE] = any
                        } else {
                            equip!!.infos!![Opt.ARCHIVE] = equipUpDateEnclosure.archive!!
                        }
                    }



                    if (!equipUpDateEnclosure.checkReport.isNullOrEmpty()){

                        val containsKey1 = equip!!.infos!!.containsKey(Opt.CHECKREPORT)
                        if (containsKey1) {
                            val any = equip!!.infos!![Opt.CHECKREPORT] as JSONArray
                            any.addAll(equipUpDateEnclosure.checkReport!!)
                            equip!!.infos!![Opt.CHECKREPORT] = any
                        } else {
                            equip!!.infos!![Opt.CHECKREPORT] = equipUpDateEnclosure.checkReport
                        }
                    }
                    if (!equipUpDateEnclosure.drawing.isNullOrEmpty()){
                        val containsKey1 = equip!!.infos!!.containsKey(Opt.DRAWING)
                        if (containsKey1) {
                            val any = equip!!.infos!![Opt.DRAWING] as JSONArray
                            any.addAll(equipUpDateEnclosure.drawing!!)
                            equip!!.infos!![Opt.DRAWING] = any
                        } else {
                            equip!!.infos!![Opt.DRAWING] = equipUpDateEnclosure.drawing
                        }
                    }
                    if (!equipUpDateEnclosure.installDrawing.isNullOrEmpty()){
                        val containsKey1 = equip!!.infos!!.containsKey(Opt.INSTALLDRAWING)
                        if (containsKey1) {
                            val any = equip!!.infos!![Opt.INSTALLDRAWING] as JSONArray
                            any.addAll(equipUpDateEnclosure.installDrawing!!)
                            equip!!.infos!![Opt.INSTALLDRAWING] = any
                        } else {
                            equip!!.infos!![Opt.INSTALLDRAWING]
                        }
                    }
                    if (!equipUpDateEnclosure.installPic.isNullOrEmpty()){
                        val containsKey1 = equip!!.infos!!.containsKey(Opt.INSTALLPIC)
                        if (containsKey1) {
                            val any = equip!!.infos!![Opt.INSTALLPIC] as JSONArray
                            any.addAll(equipUpDateEnclosure.installPic!!)
                            equip!!.infos!![Opt.INSTALLPIC] = any
                        } else {
                            equip!!.infos!![Opt.INSTALLPIC] = equipUpDateEnclosure.installPic
                        }
                    }

                    if (!equipUpDateEnclosure.insuranceFile.isNullOrEmpty()){
                        val containsKey1 = equip!!.infos!!.containsKey(Opt.INSURANCEFILE)
                        if (containsKey1) {
                            val any = equip!!.infos!![Opt.INSURANCEFILE] as JSONArray
                            any.addAll(equipUpDateEnclosure.insuranceFile!!)
                        } else {
                            equip!!.infos!![Opt.INSURANCEFILE] = equipUpDateEnclosure.insuranceFile
                        }
                    }
                    if (!equipUpDateEnclosure.nameplate.isNullOrEmpty()){

                        val containsKey1 = equip!!.infos!!.containsKey(Opt.NAMEPLATE)
                        if (containsKey1) {
                            val any = equip!!.infos!![Opt.NAMEPLATE] as JSONArray
                            any.addAll(equipUpDateEnclosure.nameplate!!)
                        } else {
                            equip!!.infos!![Opt.NAMEPLATE] = equipUpDateEnclosure.nameplate
                        }
                    }
                    /** 操作说明书 */
                    if (!equipUpDateEnclosure.operationManual.isNullOrEmpty()){
                        val containsKey1 = equip!!.infos!!.containsKey(Opt.OPERATIONMANUAL)
                        if (containsKey1) {
                            val any = equip!!.infos!![Opt.OPERATIONMANUAL] as JSONArray
                            any.addAll(equipUpDateEnclosure.operationManual!!)
                        } else {
                            equip!!.infos!![Opt.OPERATIONMANUAL] = equipUpDateEnclosure.operationManual
                        }
                    }
                    /** 产品合格证 */
                    if (!equipUpDateEnclosure.productCertification.isNullOrEmpty()){
                        val containsKey1 = equip!!.infos!!.containsKey(Opt.PRODUCTCERTIFICATION)
                        if (containsKey1) {
                            val any = equip!!.infos!![Opt.PRODUCTCERTIFICATION] as JSONArray
                            any.addAll(equipUpDateEnclosure.productCertification!!)
                        } else {
                            equip!!.infos!![Opt.PRODUCTCERTIFICATION] = equipUpDateEnclosure.productCertification
                        }
                    }
                    /** 维修保养手册 */
                    if (!equipUpDateEnclosure.maintainManual.isNullOrEmpty()){
                        val containsKey1 = equip!!.infos!!.containsKey(Opt.MAINTAINMANUAL)
                        if (containsKey1) {
                            val any = equip!!.infos!![Opt.MAINTAINMANUAL] as JSONArray
                            any.addAll(equipUpDateEnclosure.maintainManual!!)
                        } else {
                            equip!!.infos!![Opt.MAINTAINMANUAL] = equipUpDateEnclosure.maintainManual
                        }
                    }
                    /** 安装说明书 */
                    if (!equipUpDateEnclosure.installInstruction.isNullOrEmpty()){
                        val containsKey1 = equip!!.infos!!.containsKey(Opt.INSTALLINSTRUCTION)
                        if (containsKey1) {
                            val any = equip!!.infos!![Opt.INSTALLINSTRUCTION] as JSONArray
                            any.addAll(equipUpDateEnclosure.installInstruction!!)
                        } else {
                            equip!!.infos!![Opt.INSTALLINSTRUCTION] = equipUpDateEnclosure.installInstruction
                        }
                    }
                    /** 验收报告 */
                    if (!equipUpDateEnclosure.acceptanceReport.isNullOrEmpty()){
                        val containsKey1 = equip!!.infos!!.containsKey(Opt.ACCEPTANCEREPORT)
                        if (containsKey1) {
                            val any = equip!!.infos!![Opt.ACCEPTANCEREPORT] as JSONArray
                            any.addAll(equipUpDateEnclosure.acceptanceReport!!)
                        } else {
                            equip!!.infos!![Opt.ACCEPTANCEREPORT] = equipUpDateEnclosure.acceptanceReport
                        }
                    }
                    /** 进场验收单 */
                    if (!equipUpDateEnclosure.approachingAcceptance.isNullOrEmpty()){
                        val containsKey1 = equip!!.infos!!.containsKey(Opt.APPROACHINGACCEPTANCE)
                        if (containsKey1) {
                            val any = equip!!.infos!![Opt.APPROACHINGACCEPTANCE] as JSONArray
                            any.addAll(equipUpDateEnclosure.approachingAcceptance!!)
                        } else {
                            equip!!.infos!![Opt.APPROACHINGACCEPTANCE] = equipUpDateEnclosure.approachingAcceptance
                        }
                    }
                    /** 供应合同 */
                    if (!equipUpDateEnclosure.supplierContract.isNullOrEmpty()){
                        val containsKey1 = equip!!.infos!!.containsKey(Opt.SUPPLIERCONTRACT)
                        if (containsKey1) {
                            val any = equip!!.infos!![Opt.SUPPLIERCONTRACT] as JSONArray
                            any.addAll(equipUpDateEnclosure.supplierContract!!)
                        } else {
                            equip!!.infos!![Opt.SUPPLIERCONTRACT] = equipUpDateEnclosure.supplierContract
                        }
                    }
                    /** 检测报告 */
                    if (!equipUpDateEnclosure.testReport.isNullOrEmpty()){
                        val containsKey1 = equip!!.infos!!.containsKey(Opt.TESTREPORT)
                        if (containsKey1) {
                            val any = equip!!.infos!![Opt.TESTREPORT] as JSONArray
                            any.addAll(equipUpDateEnclosure.testReport!!)
                        } else {
                            equip!!.infos!![Opt.TESTREPORT] = equipUpDateEnclosure.testReport
                        }
                    }

                    /** 原厂证明 */
                    if (!equipUpDateEnclosure.originalCertificate.isNullOrEmpty()){
                        val containsKey1 = equip!!.infos!!.containsKey(Opt.ORIGINALCERTIFICATE)
                        if (containsKey1) {
                            val any = equip!!.infos!![Opt.ORIGINALCERTIFICATE] as JSONArray
                            any.addAll(equipUpDateEnclosure.originalCertificate!!)
                        } else {
                            equip!!.infos!![Opt.ORIGINALCERTIFICATE] = equipUpDateEnclosure.originalCertificate
                        }
                    }

                    /** 更新设备 */
                    EquipmentService.update(equip!!,null, SFilter.eq("projectId",projectId!!),SFilter.eq("EquipId",equipUpDateEnclosure.equipId!!))

                }

                try {
                    val jsonObject = org.json.JSONObject()
                    jsonObject.put("type", "7")
                    jsonObject.put("projectId", projectId)
                    val jsonArray = org.json.JSONArray()
                    for (entity in equipUpDateEnclosureList) {
                        val jsonInfos = org.json.JSONObject()
                        jsonInfos.put("id", entity.equipId)
                        jsonArray.put(jsonInfos)
                    }
                    jsonObject.put("infos", jsonArray)

                    /** 发送消息 */
                    messageHandler.sendMessage(jsonObject.toString())
                } catch (e: Exception) {
                    e.printStackTrace()
                }

                val sBaseResponse = SBaseResponse(SResponseType.success)
                sBaseResponse
            }else{
                val sBaseResponse = SBaseResponse(SResponseType.failure)
                sBaseResponse.message = "不能传入空值"
                sBaseResponse
            }
        } catch (e: Exception) {
            e.printStackTrace()
             SBaseResponse(SResponseType.failure)
        }
    } //

    /**
     * 查询待删除设备或部件的数量
     */
    fun equipComDels(equipComDelList: ArrayList<EquipComDel>): SQueryResponse<EquipComDel>{
        return try {
            val projectId = SPageContext.getHeader("projectId")
            if (equipComDelList.isNotEmpty()){
                for (equipComDel in equipComDelList){

                    val count = select(SFilter.eq("projectId", projectId!!),SFilter.eq("modelId", equipComDel.modelId!!), SFilter.eq("taskState", -1)).exec()
                    logger.debug("查询数量=${count.size}")
                    equipComDel.count = count.size
                }
            }

            val sQueryResponse = SQueryResponse<EquipComDel>(SResponseType.success)
            sQueryResponse.content = equipComDelList
            sQueryResponse.total = equipComDelList.size.toLong()
            sQueryResponse
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse( SResponseType.failure)
        }
    } //


    /**
     * 查询待补充的设备
     */
    fun equipPropertySupplys(equipComDelList: ArrayList<EquipComDel>): SQueryResponse<EquipComDel>{
        return try {
            val projectId = SPageContext.getHeader("projectId")
            val propertyService = SObjectService(SMybatisDao(Property::class.java))
            if (equipComDelList.isNotEmpty()){
                for (equipComDel in equipComDelList){
                    var num = 0
                    val FloorComponList = FloorService.select(SFilter.Companion.eq("projectId", projectId!!), SFilter.eq("modelId", equipComDel.modelId!!)).exec()
                    logger.debug("楼层数量=${FloorComponList.size}")
                    if (FloorComponList.size>0){
                        for (floorCompon in FloorComponList){
                            val count = propertyService.select(SFilter.eq("projectId", projectId!!),SFilter.eq("floorId", floorCompon.id!!),
                                    SFilter.isNull("BIMID"), SFilter.not(SFilter.isNull("BIMLocation"))
                                    ,SFilter.isNull("EquipmentId")).exec()
                            logger.debug("查询数量=${count.size}")
                            num += count.size
                        }
                    }
                    equipComDel.count = num
                }
            }
            val sQueryResponse = SQueryResponse<EquipComDel>(SResponseType.success)
            sQueryResponse.content = equipComDelList
            sQueryResponse.total = equipComDelList.size.toLong()
            sQueryResponse
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse( SResponseType.failure)
        }
    } //

    /**
     * 查询待补充的设备
     */
    fun equipPropertySupp(sQueryRequest: SQueryRequest): SQueryResponse<PropertySupplement>{
        return try {
            val service = SObjectService(SMybatisDao(PropertySupplement::class.java))
            val withFilterList = ArrayList<SFilter>()
            withFilterList.add(SFilter.eq("projectId", SPageContext.getHeader("projectId").toString()))
            val pageQuery = service.pageQuery(sQueryRequest,withFilterList)
              pageQuery
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse( SResponseType.failure)
        }
    } //

//    /**
//     * 模型质量报告 待删除的设备
//     */
//    fun equipCommDelss(idList: ArrayList<String>): SQueryResponse<EquipmentDel>{
//        return try {
//        val projectId = SPageContext.getHeader("projectId")
//        val equipCommDels = customSqlService.equipCommDels(projectId!!, idList)
//            logger.debug("equipDel =${equipCommDels.toJson()}")
//        val sQueryResponse = SQueryResponse<EquipmentDel>(SResponseType.success)
//        sQueryResponse.content = equipCommDels
//        sQueryResponse.total = equipCommDels.size.toLong()
//        sQueryResponse
//    } catch (e: Exception) {
//        e.printStackTrace()
//        SQueryResponse( SResponseType.failure)
//    }
//    } //

    /**
     * 台账中待删除的对象 数量统计
     */
    fun delObj(): SCountResponse {
        return try {
            val projectId = SPageContext.getHeader("projectId")
            val propertyList = PropertyService.select(SFilter.eq("projectId", projectId!!), SFilter.eq("taskState", -1)).exec()

            var count = 0
            if (propertyList.isNotEmpty()){
                val setId = HashSet<String>()
                for (property in propertyList){
                    if (!property.equipId.isNullOrEmpty()){
                        setId.add(property.equipId!!)
                    }
                }
                if (setId.size > 0){
                    val equipmentList = select(SFilter.eq("projectId", projectId!!), SFilter.eq("taskState", -1), SFilter.not(SFilter.inList("id", setId.toList()))).exec()
                    count = propertyList.size+equipmentList.size
                }else{
                    val equipmentList = select(SFilter.eq("projectId", projectId!!), SFilter.eq("taskState", -1)).exec()
                    count = propertyList.size+equipmentList.size
                }

            }else{
                val equipmentList = select(SFilter.eq("projectId", projectId!!), SFilter.eq("taskState", -1)).exec()
                count = equipmentList.size
            }
            val sQueryResponse = SCountResponse(count.toLong(),SResponseType.success)
            sQueryResponse
        } catch (e: Exception) {
            e.printStackTrace()
            SCountResponse(0,SResponseType.success,e.message.toString())
        }

    } // Fun delObj()

    /**
     * 项目下的所有设备类型以及名称
     *
     * @return 返回对象列表
     */
    fun  equipTypeName(): SQueryResponse<DefClass>{
       return try {
            val sQueryResponse = SQueryResponse<DefClass>(SResponseType.success)
            val projectId = SPageContext.getHeader("projectId")
            val equipTypeList = customSqlService.equipType(projectId!!)
            sQueryResponse.total = equipTypeList.size.toLong()
            sQueryResponse.content = equipTypeList
           sQueryResponse
        } catch (e: Exception) {
            e.printStackTrace()
           SQueryResponse(SResponseType.failure,e.message!!)
        }
    }




} // Object EquipmentService