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

package com.persagy.server.service.objects

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
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.datacenter.models.entities.assistant.TaskPic
import com.persagy.server.datacenter.models.entities.dict.EquipFamily
import com.persagy.server.datacenter.models.entities.dict.ExplainAllCategories
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.web.bind.annotation.RequestBody


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

    /** 日志 */
    private val logger = LoggerFactory.getLogger(EquipmentService::class.java)

    /** 自定义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))

    /**
     * 查询之前操作
     */
    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 service = SBaseService(SMybatisDao(EquipAssetComponentsReqponse::class.java))
            val explainAllCategoriesService = SBaseService(SMybatisDao(ExplainAllCategories::class.java))
            val queryBuilder = service.select(request.filters)
                    .filter(SFilter.eq("ProjectId", SPageContext.getHeader("ProjectId")!!))
            queryBuilder.tableName = "v_equip_property"
            if (null != request.projection) {
                queryBuilder.projection(request.projection!!)
            }
            if (null != request.orders) {
                queryBuilder.order(request.orders!!)
            }
            val pageQuery = EquipAssetComponentsReqponseService.pageQuery(request, arrayListOf(SFilter.eq("ProjectId", SPageContext.getHeader("ProjectId")!!)))
//            val equipAssetComponentsList = queryBuilder.pageQuery(request.pageNumber, request.pageSize)
            var list = ArrayList<EquipAssetComponentsReqponse>()
//            logger.debug("list01 =${equipAssetComponentsList.toJson()}")
            list = DataVerification.getEquipAssetComponentsToolsTwo(pageQuery.content!!)
//            logger.debug("getEquipAssetComponent =${request.toJson()}")
            /** 设备关联资产服务 */
//            val sPageQueryInfo = SPageQueryInfo<EquipAssetComponentsReqponse>(request.pageNumber, request.pageSize)
//            sPageQueryInfo.content = list
//            sPageQueryInfo.total = equipAssetComponentsList.total
//            SQueryResponse(sPageQueryInfo)
            if(pageQuery.result == SResponseType.success&&pageQuery.content!!.size>0){
                val content = pageQuery.content!![0]
                val exec1 = explainAllCategoriesService.select(SFilter.eq("parentId", content.category!!)).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.category}'").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("equipId",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("equipId",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("RoomID", 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("equipId",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("equipId", equipUpDateEnclosure.equipId!!)).entity()

                    if (equip == null){
                        continue
                    }
                    logger.debug("设备id= ${equip?.id}")
                    if (!equipUpDateEnclosure.Pic.isNullOrEmpty()){

                        if (!equip!!.ledgerParam.isNullOrEmpty()){
                            val containsKey = equip.ledgerParam!!.containsKey("PhotoDoc")
                            if (containsKey){
                                logger.debug("PhotoDoc存在")
//                                logger.debug("PhotoDoc数据=${equip.ledgerParam!!["PhotoDoc"]}")
                                val photoDocMap = equip.ledgerParam!!["PhotoDoc"] as JSONObject
                                val containsKeyPic = photoDocMap.containsKey("Pic")
                                if (containsKeyPic){
                                    val any = photoDocMap["Pic"] as JSONArray
                                    any.addAll(equipUpDateEnclosure.Pic!!)
                                    logger.debug("图片数据=${any.toJson()}")
                                }else{
                                    photoDocMap["Pic"] = equipUpDateEnclosure.Pic!!
                                }
                            }else{
                                logger.debug("PhotoDoc不存在")
                                val mapPic = HashMap<String,ArrayList<TaskPic>>()
                                mapPic.put("Pic",equipUpDateEnclosure.Pic!!)
                                equip.ledgerParam!!.put("PhotoDoc",mapPic)
                            }
                        }else{
                            val mapPic = HashMap<String,ArrayList<TaskPic>>()
                            mapPic.put("Pic",equipUpDateEnclosure.Pic!!)
                            val mapPhotoDoc = HashMap<String,Any?>()
                            mapPhotoDoc.put("PhotoDoc",mapPic)
                            equip.ledgerParam = mapPhotoDoc
                        }
                    }
                    if (!equipUpDateEnclosure.archive.isNullOrEmpty()){
                        if (!equip!!.ledgerParam.isNullOrEmpty()){

//                            val itemJSONObj = JSONObject.parseObject(JSON.toJSONString(equip.ledgerParam))
//                            val containsKey = itemJSONObj.containsKey("PhotoDoc")

                            val containsKey = equip.ledgerParam!!.containsKey("PhotoDoc")
                            if (containsKey){
                                logger.debug("PhotoDoc存在 ")
//                                val photoDocMap = equip.ledgerParam!!["PhotoDoc"]
                                val photoDocMap = JSONObject.parseObject(JSON.toJSONString(equip.ledgerParam!!["PhotoDoc"]))
                                val containsKeyPic = photoDocMap.containsKey("Archive")
                                if (containsKeyPic){
                                    logger.debug("Archive存在: ${equip.toJson()} ")
                                    val any = photoDocMap["Archive"] as JSONArray
                                    any.addAll(equipUpDateEnclosure.archive!!)
                                    logger.debug("图片数据=${any.toJson()}")
                                }else{
                                    logger.debug("Archive不存在: ${equip.toJson()} ")
                                    photoDocMap["Archive"] = equipUpDateEnclosure.archive!!
                                    logger.debug("Archive不存在2: ${photoDocMap.toJson()} ")
                                    equip.ledgerParam!!["PhotoDoc"] = photoDocMap
                                }
                            }else{
                                logger.debug("PhotoDoc不存在")
                                val mapPic = HashMap<String,ArrayList<TaskPic>>()
                                mapPic.put("Archive",equipUpDateEnclosure.archive!!)
                                equip.ledgerParam!!.put("PhotoDoc",mapPic)
                            }
                        }else{
                            val mapPic = HashMap<String,ArrayList<TaskPic>>()
                            mapPic.put("Archive",equipUpDateEnclosure.archive!!)
                            val mapPhotoDoc = HashMap<String,Any?>()
                            mapPhotoDoc.put("PhotoDoc",mapPic)
                            equip.ledgerParam = mapPhotoDoc
                        }
                    }
                    if (!equipUpDateEnclosure.checkReport.isNullOrEmpty()){
                        if (!equip!!.ledgerParam.isNullOrEmpty()){
                            val containsKey = equip.ledgerParam!!.containsKey("Siteinstall")
                            if (containsKey){
                                logger.debug("Siteinstall存在")
//                                logger.debug("Siteinstall数据=${equip.ledgerParam!!["Siteinstall"]}")
//                                val photoDocMap = equip.ledgerParam!!["Siteinstall"] as JSONObject
                                val photoDocMap = JSONObject.parseObject(JSON.toJSONString(equip.ledgerParam!!["Siteinstall"]))
                                val containsKeyPic = photoDocMap.containsKey("CheckReport")
                                if (containsKeyPic){
                                    val any = photoDocMap["CheckReport"] as JSONArray
                                    any.addAll(equipUpDateEnclosure.checkReport!!)
                                    logger.debug("图片数据=${any.toJson()}")
                                }else{
                                    photoDocMap["CheckReport"] = equipUpDateEnclosure.checkReport!!
                                    equip.ledgerParam!!.put("Siteinstall",photoDocMap)
                                }
                            }else{
                                logger.debug("Siteinstall不存在")
                                val mapPic = HashMap<String,ArrayList<TaskPic>>()
                                mapPic.put("CheckReport",equipUpDateEnclosure.checkReport!!)
                                equip.ledgerParam!!.put("Siteinstall",mapPic)
                            }
                        }else{
                            val mapPic = HashMap<String,ArrayList<TaskPic>>()
                            mapPic.put("CheckReport",equipUpDateEnclosure.checkReport!!)
                            val mapPhotoDoc = HashMap<String,Any?>()
                            mapPhotoDoc.put("Siteinstall",mapPic)
                            equip.ledgerParam = mapPhotoDoc
                        }

                    }
                    if (!equipUpDateEnclosure.drawing.isNullOrEmpty()){

                        if (!equip!!.ledgerParam.isNullOrEmpty()){
                            val containsKey = equip.ledgerParam!!.containsKey("PhotoDoc")
                            if (containsKey){
                                logger.debug("PhotoDoc存在")
//                                logger.debug("PhotoDoc数据=${equip.ledgerParam!!["PhotoDoc"]}")
//                                val photoDocMap = equip.ledgerParam!!["PhotoDoc"] as JSONObject
                                val photoDocMap = JSONObject.parseObject(JSON.toJSONString(equip.ledgerParam!!["PhotoDoc"]))
                                val containsKeyPic = photoDocMap.containsKey("Drawing")
                                if (containsKeyPic){
                                    val any = photoDocMap["Drawing"] as JSONArray
                                    any.addAll(equipUpDateEnclosure.drawing!!)
                                    logger.debug("图片数据=${any.toJson()}")
                                }else{
                                    photoDocMap["Drawing"] = equipUpDateEnclosure.drawing!!
                                    equip.ledgerParam!!.put("PhotoDoc",photoDocMap)
                                }
                            }else{
                                logger.debug("PhotoDoc不存在")
                                val mapPic = HashMap<String,ArrayList<TaskPic>>()
                                mapPic.put("Drawing",equipUpDateEnclosure.drawing!!)
                                equip.ledgerParam!!.put("PhotoDoc",mapPic)
                            }
                        }else{
                            val mapPic = HashMap<String,ArrayList<TaskPic>>()
                            mapPic.put("Drawing",equipUpDateEnclosure.drawing!!)
                            val mapPhotoDoc = HashMap<String,Any?>()
                            mapPhotoDoc.put("PhotoDoc",mapPic)
                            equip.ledgerParam = mapPhotoDoc
                        }

                    }
                    if (!equipUpDateEnclosure.installDrawing.isNullOrEmpty()){

                        if (!equip!!.ledgerParam.isNullOrEmpty()){
                            val containsKey = equip.ledgerParam!!.containsKey("Siteinstall")
                            if (containsKey){
                                logger.debug("Siteinstall存在")
//                                logger.debug("Siteinstall数据=${equip.ledgerParam!!["Siteinstall"]}")
//                                val photoDocMap = equip.ledgerParam!!["Siteinstall"] as JSONObject
                                val photoDocMap = JSONObject.parseObject(JSON.toJSONString(equip.ledgerParam!!["Siteinstall"]))
                                val containsKeyPic = photoDocMap.containsKey("InstallDrawing")
                                if (containsKeyPic){
                                    val any = photoDocMap["InstallDrawing"] as JSONArray
                                    any.addAll(equipUpDateEnclosure.installDrawing!!)
                                    logger.debug("图片数据=${any.toJson()}")
                                }else{
                                    photoDocMap["InstallDrawing"] = equipUpDateEnclosure.installDrawing!!
                                    equip.ledgerParam!!.put("Siteinstall",photoDocMap)
                                }
                            }else{
                                logger.debug("Siteinstall不存在")
                                val mapPic = HashMap<String,ArrayList<TaskPic>>()
                                mapPic.put("InstallDrawing",equipUpDateEnclosure.installDrawing!!)
                                equip.ledgerParam!!.put("Siteinstall",mapPic)
                            }
                        }else{
                            val mapPic = HashMap<String,ArrayList<TaskPic>>()
                            mapPic.put("InstallDrawing",equipUpDateEnclosure.installDrawing!!)
                            val mapPhotoDoc = HashMap<String,Any?>()
                            mapPhotoDoc.put("Siteinstall",mapPic)
                            equip.ledgerParam = mapPhotoDoc
                        }
                    }
                    if (!equipUpDateEnclosure.installPic.isNullOrEmpty()){
                        if (!equip!!.ledgerParam.isNullOrEmpty()){
                            val containsKey = equip.ledgerParam!!.containsKey("Siteinstall")
                            if (containsKey){
                                logger.debug("Siteinstall存在")
//                                logger.debug("Siteinstall数据=${equip.ledgerParam!!["Siteinstall"]}")
//                                val photoDocMap = equip.ledgerParam!!["Siteinstall"] as JSONObject
                                val photoDocMap = JSONObject.parseObject(JSON.toJSONString(equip.ledgerParam!!["Siteinstall"]))
                                val containsKeyPic = photoDocMap.containsKey("InstallPic")
                                if (containsKeyPic){
                                    val any = photoDocMap["InstallPic"] as JSONArray
                                    any.addAll(equipUpDateEnclosure.installPic!!)
                                    logger.debug("图片数据=${any.toJson()}")
                                }else{
                                    photoDocMap["InstallPic"] = equipUpDateEnclosure.installPic!!
                                    equip.ledgerParam!!.put("Siteinstall",photoDocMap)
                                }
                            }else{
                                logger.debug("Siteinstall不存在")
                                val mapPic = HashMap<String,ArrayList<TaskPic>>()
                                mapPic.put("InstallPic",equipUpDateEnclosure.installPic!!)
                                equip.ledgerParam!!.put("Siteinstall",mapPic)
                            }
                        }else{
                            val mapPic = HashMap<String,ArrayList<TaskPic>>()
                            mapPic.put("InstallPic",equipUpDateEnclosure.installPic!!)
                            val mapPhotoDoc = HashMap<String,Any?>()
                            mapPhotoDoc.put("Siteinstall",mapPic)
                            equip.ledgerParam = mapPhotoDoc
                        }
                    }

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

                        if (!equip!!.ledgerParam.isNullOrEmpty()){
                            val containsKey = equip.ledgerParam!!.containsKey("InsuranceDoc")
                            if (containsKey){
                                logger.debug("InsuranceDoc存在")
//                                logger.debug("InsuranceDoc数据=${equip.ledgerParam!!["InsuranceDoc"]}")
                                val photoDocMap = JSONObject.parseObject(JSON.toJSONString(equip.ledgerParam!!["InsuranceDoc"]))
//                                val photoDocMap = equip.ledgerParam!!["InsuranceDoc"] as JSONObject
                                val containsKeyPic = photoDocMap.containsKey("InsuranceFile")
                                if (containsKeyPic){
                                    val any = photoDocMap["InsuranceFile"] as JSONArray
                                    any.addAll(equipUpDateEnclosure.insuranceFile!!)
                                    logger.debug("图片数据=${any.toJson()}")
                                }else{
                                    photoDocMap["InsuranceFile"] = equipUpDateEnclosure.insuranceFile!!
                                    equip.ledgerParam!!.put("InsuranceDoc",photoDocMap)
                                }
                            }else{
                                logger.debug("InsuranceDoc不存在")
                                val mapPic = HashMap<String,ArrayList<TaskPic>>()
                                mapPic.put("InsuranceFile",equipUpDateEnclosure.insuranceFile!!)
                                equip.ledgerParam!!.put("InsuranceDoc",mapPic)
                            }
                        }else{
                            val mapPic = HashMap<String,ArrayList<TaskPic>>()
                            mapPic.put("InsuranceFile",equipUpDateEnclosure.insuranceFile!!)
                            val mapPhotoDoc = HashMap<String,Any?>()
                            mapPhotoDoc.put("InsuranceDoc",mapPic)
                            equip.ledgerParam = mapPhotoDoc
                        }

                    }
                    if (!equipUpDateEnclosure.nameplate.isNullOrEmpty()){
                        if (!equip!!.ledgerParam.isNullOrEmpty()){
                            val containsKey = equip.ledgerParam!!.containsKey("PhotoDoc")
                            if (containsKey){
                                logger.debug("PhotoDoc存在")
//                                logger.debug("PhotoDoc数据=${equip.ledgerParam!!["PhotoDoc"]}")
//                                val photoDocMap = equip.ledgerParam!!["PhotoDoc"] as JSONObject
                                val photoDocMap = JSONObject.parseObject(JSON.toJSONString(equip.ledgerParam!!["PhotoDoc"]))
                                val containsKeyPic = photoDocMap.containsKey("Nameplate")
                                if (containsKeyPic){
                                    val any = photoDocMap["Nameplate"] as JSONArray
                                    any.addAll(equipUpDateEnclosure.nameplate!!)
                                    logger.debug("图片数据=${any.toJson()}")
                                }else{
                                    photoDocMap["Nameplate"] = equipUpDateEnclosure.nameplate!!
                                    equip.ledgerParam!!.put("PhotoDoc",photoDocMap)
                                }
                            }else{
                                logger.debug("PhotoDoc不存在")
                                val mapPic = HashMap<String,ArrayList<TaskPic>>()
                                mapPic.put("Nameplate",equipUpDateEnclosure.nameplate!!)
                                equip.ledgerParam!!.put("PhotoDoc",mapPic)
                            }
                        }else{
                            val mapPic = HashMap<String,ArrayList<TaskPic>>()
                            mapPic.put("Nameplate",equipUpDateEnclosure.nameplate!!)
                            val mapPhotoDoc = HashMap<String,Any?>()
                            mapPhotoDoc.put("PhotoDoc",mapPic)
                            equip.ledgerParam = mapPhotoDoc
                        }
                    }
                    /** 操作说明书 */
                    if (!equipUpDateEnclosure.operationManual.isNullOrEmpty()){
                        if (!equip!!.ledgerParam.isNullOrEmpty()){
                            val containsKey = equip.ledgerParam!!.containsKey("PhotoDoc")
                            if (containsKey){
                                logger.debug("PhotoDoc存在")
//                                logger.debug("PhotoDoc数据=${equip.ledgerParam!!["PhotoDoc"]}")
                                val photoDocMap = JSONObject.parseObject(JSON.toJSONString(equip.ledgerParam!!["PhotoDoc"]))
//                                val photoDocMap = equip.ledgerParam!!["PhotoDoc"] as JSONObject
                                val containsKeyPic = photoDocMap.containsKey("OperationManual")
                                if (containsKeyPic){
                                    val any = photoDocMap["OperationManual"] as JSONArray
                                    any.addAll(equipUpDateEnclosure.operationManual!!)
                                    logger.debug("图片数据=${any.toJson()}")
                                }else{
                                    photoDocMap["OperationManual"] = equipUpDateEnclosure.operationManual!!
                                    equip.ledgerParam!!.put("PhotoDoc",photoDocMap)
                                }
                            }else{
                                logger.debug("PhotoDoc不存在")
                                val mapPic = HashMap<String,ArrayList<TaskPic>>()
                                mapPic.put("OperationManual",equipUpDateEnclosure.operationManual!!)
                                equip.ledgerParam!!.put("PhotoDoc",mapPic)
                            }
                        }else{
                            val mapPic = HashMap<String,ArrayList<TaskPic>>()
                            mapPic.put("OperationManual",equipUpDateEnclosure.operationManual!!)
                            val mapPhotoDoc = HashMap<String,Any?>()
                            mapPhotoDoc.put("PhotoDoc",mapPic)
                            equip.ledgerParam = mapPhotoDoc
                        }
                    }
                    /** 产品合格证 */
                    if (!equipUpDateEnclosure.productCertification.isNullOrEmpty()){
                        if (!equip!!.ledgerParam.isNullOrEmpty()){
                            val containsKey = equip.ledgerParam!!.containsKey("PhotoDoc")
                            if (containsKey){
                                logger.debug("PhotoDoc存在")
//                                logger.debug("PhotoDoc数据=${equip.ledgerParam!!["PhotoDoc"]}")
//                                val photoDocMap = equip.ledgerParam!!["PhotoDoc"] as JSONObject
                                val photoDocMap = JSONObject.parseObject(JSON.toJSONString(equip.ledgerParam!!["PhotoDoc"]))
                                val containsKeyPic = photoDocMap.containsKey("ProductCertification")
                                if (containsKeyPic){
                                    val any = photoDocMap["ProductCertification"] as JSONArray
                                    any.addAll(equipUpDateEnclosure.productCertification!!)
                                    logger.debug("图片数据=${any.toJson()}")
                                }else{
                                    photoDocMap["ProductCertification"] = equipUpDateEnclosure.productCertification!!
                                    equip.ledgerParam!!.put("PhotoDoc",photoDocMap)
                                }
                            }else{
                                logger.debug("PhotoDoc不存在")
                                val mapPic = HashMap<String,ArrayList<TaskPic>>()
                                mapPic.put("ProductCertification",equipUpDateEnclosure.productCertification!!)
                                equip.ledgerParam!!.put("PhotoDoc",mapPic)
                            }
                        }else{
                            val mapPic = HashMap<String,ArrayList<TaskPic>>()
                            mapPic.put("ProductCertification",equipUpDateEnclosure.productCertification!!)
                            val mapPhotoDoc = HashMap<String,Any?>()
                            mapPhotoDoc.put("PhotoDoc",mapPic)
                            equip.ledgerParam = mapPhotoDoc
                        }
                    }
                    /** 维修保养手册 */
                    if (!equipUpDateEnclosure.maintainManual.isNullOrEmpty()){
                        if (!equip!!.ledgerParam.isNullOrEmpty()){
                            val containsKey = equip.ledgerParam!!.containsKey("OperationMainte")
                            if (containsKey){
                                logger.debug("OperationMainte存在")
//                                logger.debug("OperationMainte数据=${equip.ledgerParam!!["OperationMainte"]}")
//                                val photoDocMap = equip.ledgerParam!!["OperationMainte"] as JSONObject
                                val photoDocMap = JSONObject.parseObject(JSON.toJSONString(equip.ledgerParam!!["OperationMainte"]))
                                val containsKeyPic = photoDocMap.containsKey("MaintainManual")
                                if (containsKeyPic){
                                    val any = photoDocMap["MaintainManual"] as JSONArray
                                    any.addAll(equipUpDateEnclosure.maintainManual!!)
                                    logger.debug("图片数据=${any.toJson()}")
                                }else{
                                    photoDocMap["MaintainManual"] = equipUpDateEnclosure.maintainManual
                                    equip.ledgerParam!!.put("OperationMainte",photoDocMap)
                                }
                            }else{
                                logger.debug("OperationMainte不存在")
                                val mapPic = HashMap<String,ArrayList<TaskPic>>()
                                mapPic.put("MaintainManual",equipUpDateEnclosure.maintainManual!!)
                                equip.ledgerParam!!.put("OperationMainte",mapPic)
                            }
                        }else{
                            val mapPic = HashMap<String,ArrayList<TaskPic>>()
                            mapPic.put("MaintainManual",equipUpDateEnclosure.maintainManual!!)
                            val mapPhotoDoc = HashMap<String,Any?>()
                            mapPhotoDoc.put("OperationMainte",mapPic)
                            equip.ledgerParam = mapPhotoDoc
                        }
                    }
                    /** 安装说明书 */
                    if (!equipUpDateEnclosure.installInstruction.isNullOrEmpty()){
                        if (!equip!!.ledgerParam.isNullOrEmpty()){
                            val containsKey = equip.ledgerParam!!.containsKey("Siteinstall")
                            if (containsKey){
                                logger.debug("Siteinstall存在")
//                                logger.debug("Siteinstall数据=${equip.ledgerParam!!["Siteinstall"]}")
//                                val photoDocMap = equip.ledgerParam!!["Siteinstall"] as JSONObject
                                val photoDocMap = JSONObject.parseObject(JSON.toJSONString(equip.ledgerParam!!["Siteinstall"]))
                                val containsKeyPic = photoDocMap.containsKey("InstallInstruction")
                                if (containsKeyPic){
                                    val any = photoDocMap["InstallInstruction"] as JSONArray
                                    any.addAll(equipUpDateEnclosure.installInstruction!!)
                                    logger.debug("图片数据=${any.toJson()}")
                                }else{
                                    photoDocMap["InstallInstruction"] = equipUpDateEnclosure.installInstruction!!
                                    equip.ledgerParam!!.put("Siteinstall",photoDocMap)
                                }
                            }else{
                                logger.debug("Siteinstall不存在")
                                val mapPic = HashMap<String,ArrayList<TaskPic>>()
                                mapPic.put("InstallInstruction",equipUpDateEnclosure.installInstruction!!)
                                equip.ledgerParam!!.put("Siteinstall",mapPic)
                            }
                        }else{
                            val mapPic = HashMap<String,ArrayList<TaskPic>>()
                            mapPic.put("InstallInstruction",equipUpDateEnclosure.installInstruction!!)
                            val mapPhotoDoc = HashMap<String,Any?>()
                            mapPhotoDoc.put("Siteinstall",mapPic)
                            equip.ledgerParam = mapPhotoDoc
                        }
                    }
                    /** 验收报告 */
                    if (!equipUpDateEnclosure.acceptanceReport.isNullOrEmpty()){
                        if (!equip!!.ledgerParam.isNullOrEmpty()){
                            val containsKey = equip.ledgerParam!!.containsKey("SupplyPurchase")
                            if (containsKey){
                                logger.debug("SupplyPurchase存在")
//                                logger.debug("SupplyPurchase数据=${equip.ledgerParam!!["SupplyPurchase"]}")
                                val photoDocMap = equip.ledgerParam!!["SupplyPurchase"] as JSONObject
                                val containsKeyPic = photoDocMap.containsKey("AcceptanceReport")
                                if (containsKeyPic){
                                    val any = photoDocMap["AcceptanceReport"] as JSONArray
                                    any.addAll(equipUpDateEnclosure.acceptanceReport!!)
                                    logger.debug("图片数据=${any.toJson()}")
                                }else{
                                    photoDocMap["AcceptanceReport"] = equipUpDateEnclosure.acceptanceReport!!
                                }
                            }else{
                                logger.debug("SupplyPurchase不存在")
                                val mapPic = HashMap<String,ArrayList<TaskPic>>()
                                mapPic.put("AcceptanceReport",equipUpDateEnclosure.acceptanceReport!!)
                                equip.ledgerParam!!.put("SupplyPurchase",mapPic)
                            }
                        }else{
                            val mapPic = HashMap<String,ArrayList<TaskPic>>()
                            mapPic.put("AcceptanceReport",equipUpDateEnclosure.acceptanceReport!!)
                            val mapPhotoDoc = HashMap<String,Any?>()
                            mapPhotoDoc.put("SupplyPurchase",mapPic)
                            equip.ledgerParam = mapPhotoDoc
                        }
                    }
                    /** 进场验收单 */
                    if (!equipUpDateEnclosure.approachingAcceptance.isNullOrEmpty()){
                        if (!equip!!.ledgerParam.isNullOrEmpty()){
                            val containsKey = equip.ledgerParam!!.containsKey("SupplyPurchase")
                            if (containsKey){
                                logger.debug("SupplyPurchase存在")
//                                logger.debug("SupplyPurchase数据=${equip.ledgerParam!!["SupplyPurchase"]}")
                                val photoDocMap = JSONObject.parseObject(JSON.toJSONString(equip.ledgerParam!!["SupplyPurchase"]))
//                                val photoDocMap = equip.ledgerParam!!["SupplyPurchase"] as JSONObject
                                val containsKeyPic = photoDocMap.containsKey("ApproachingAcceptance")
                                if (containsKeyPic){
                                    val any = photoDocMap["ApproachingAcceptance"] as JSONArray
                                    any.addAll(equipUpDateEnclosure.approachingAcceptance!!)
                                    logger.debug("图片数据=${any.toJson()}")
                                }else{
                                    photoDocMap["ApproachingAcceptance"] = equipUpDateEnclosure.approachingAcceptance!!
                                    equip.ledgerParam!!.put("SupplyPurchase",photoDocMap)
                                }
                            }else{
                                logger.debug("SupplyPurchase不存在")
                                val mapPic = HashMap<String,ArrayList<TaskPic>>()
                                mapPic.put("ApproachingAcceptance",equipUpDateEnclosure.approachingAcceptance!!)
                                equip.ledgerParam!!.put("SupplyPurchase",mapPic)
                            }
                        }else{
                            val mapPic = HashMap<String,ArrayList<TaskPic>>()
                            mapPic.put("ApproachingAcceptance",equipUpDateEnclosure.approachingAcceptance!!)
                            val mapPhotoDoc = HashMap<String,Any?>()
                            mapPhotoDoc.put("SupplyPurchase",mapPic)
                            equip.ledgerParam = mapPhotoDoc
                        }
                    }
                    /** 供应合同 */
                    if (!equipUpDateEnclosure.supplierContract.isNullOrEmpty()){
                        if (!equip!!.ledgerParam.isNullOrEmpty()){
                            val containsKey = equip.ledgerParam!!.containsKey("SupplyPurchase")
                            if (containsKey){
                                logger.debug("SupplyPurchase存在")
//                                logger.debug("SupplyPurchase数据=${equip.ledgerParam!!["SupplyPurchase"]}")
                                val photoDocMap = JSONObject.parseObject(JSON.toJSONString(equip.ledgerParam!!["SupplyPurchase"]))
//                                val photoDocMap = equip.ledgerParam!!["SupplyPurchase"] as JSONObject
                                val containsKeyPic = photoDocMap.containsKey("SupplierContract")
                                if (containsKeyPic){
                                    val any = photoDocMap["SupplierContract"] as JSONArray
                                    any.addAll(equipUpDateEnclosure.supplierContract!!)
                                    logger.debug("图片数据=${any.toJson()}")
                                }else{
                                    photoDocMap["SupplierContract"] = equipUpDateEnclosure.supplierContract!!
                                    equip.ledgerParam!!.put("PSupplyPurchase",photoDocMap)
                                }
                            }else{
                                logger.debug("PSupplyPurchase不存在")
                                val mapPic = HashMap<String,ArrayList<TaskPic>>()
                                mapPic.put("SupplierContract",equipUpDateEnclosure.supplierContract!!)
                                equip.ledgerParam!!.put("PSupplyPurchase",mapPic)
                            }
                        }else{
                            val mapPic = HashMap<String,ArrayList<TaskPic>>()
                            mapPic.put("SupplierContract",equipUpDateEnclosure.supplierContract!!)
                            val mapPhotoDoc = HashMap<String,Any?>()
                            mapPhotoDoc.put("SupplyPurchase",mapPic)
                            equip.ledgerParam = mapPhotoDoc
                        }
                    }
                    /** 检测报告 */
                    if (!equipUpDateEnclosure.testReport.isNullOrEmpty()){
                        if (!equip!!.ledgerParam.isNullOrEmpty()){
                            val containsKey = equip.ledgerParam!!.containsKey("EquipManufactor")
                            if (containsKey){
                                logger.debug("EquipManufactor存在")
//                                logger.debug("EquipManufactor数据=${equip.ledgerParam!!["EquipManufactor"]}")
                                val photoDocMap = JSONObject.parseObject(JSON.toJSONString(equip.ledgerParam!!["EquipManufactor"]))
//                                val photoDocMap = equip.ledgerParam!!["EquipManufactor"] as JSONObject
                                val containsKeyPic = photoDocMap.containsKey("TestReport")
                                if (containsKeyPic){
                                    val any = photoDocMap["TestReport"] as JSONArray
                                    any.addAll(equipUpDateEnclosure.testReport!!)
                                    logger.debug("图片数据=${any.toJson()}")
                                }else{
                                    photoDocMap["TestReport"] = equipUpDateEnclosure.testReport!!
                                    equip.ledgerParam!!.put("EquipManufactor",photoDocMap)
                                }
                            }else{
                                logger.debug("PhotoDoc不存在")
                                val mapPic = HashMap<String,ArrayList<TaskPic>>()
                                mapPic.put("TestReport",equipUpDateEnclosure.testReport!!)
                                equip.ledgerParam!!.put("EquipManufactor",mapPic)
                            }
                        }else{
                            val mapPic = HashMap<String,ArrayList<TaskPic>>()
                            mapPic.put("TestReport",equipUpDateEnclosure.testReport!!)
                            val mapPhotoDoc = HashMap<String,Any?>()
                            mapPhotoDoc.put("EquipManufactor",mapPic)
                            equip.ledgerParam = mapPhotoDoc
                        }
                    }

                    /** 原厂证明 */
                    if (!equipUpDateEnclosure.originalCertificate.isNullOrEmpty()){
                        if (!equip!!.ledgerParam.isNullOrEmpty()){
                            val containsKey = equip.ledgerParam!!.containsKey("EquipManufactor")
                            if (containsKey){
                                logger.debug("EquipManufactor存在")
//                                logger.debug("EquipManufactor数据=${equip.ledgerParam!!["EquipManufactor"]}")
//                                val photoDocMap = equip.ledgerParam!!["EquipManufactor"] as JSONObject
                                val photoDocMap = JSONObject.parseObject(JSON.toJSONString(equip.ledgerParam!!["EquipManufactor"]))
                                val containsKeyPic = photoDocMap.containsKey("OriginalCertificate")
                                if (containsKeyPic){
                                    val any = photoDocMap["OriginalCertificate"] as JSONArray
                                    any.addAll(equipUpDateEnclosure.originalCertificate!!)
                                    logger.debug("图片数据=${any.toJson()}")
                                }else{
                                    photoDocMap["OriginalCertificate"] = equipUpDateEnclosure.originalCertificate!!
                                    equip.ledgerParam!!.put("EquipManufactor",photoDocMap)
                                }
                            }else{
                                logger.debug("EquipManufactor不存在")
                                val mapPic = HashMap<String,ArrayList<TaskPic>>()
                                mapPic.put("OriginalCertificate",equipUpDateEnclosure.originalCertificate!!)
                                equip.ledgerParam!!.put("EquipManufactor",mapPic)
                            }
                        }else{
                            val mapPic = HashMap<String,ArrayList<TaskPic>>()
                            mapPic.put("OriginalCertificate",equipUpDateEnclosure.originalCertificate!!)
                            val mapPhotoDoc = HashMap<String,Any?>()
                            mapPhotoDoc.put("EquipManufactor",mapPic)
                            equip.ledgerParam = mapPhotoDoc
                        }
                    }


                    /** 更新设备 */
                    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()


} // Object EquipmentService