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

package com.persagy.server.services.objects

import cn.sagacloud.server.datacenter.utils.IdUtils
import cn.sagacloud.server.datacenter.utils.ShaftNameUtil
import com.persagy.database.SFilter
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.datacenter.models.entities.logs.DataCenterLogs
import com.persagy.server.datacenter.models.entities.objects.Floor
import com.persagy.server.services.assistant.ObjInfoService
import com.persagy.server.services.base.Service
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.SUpdateRequest
import com.persagy.service.models.responses.SBaseResponse
import com.persagy.service.models.responses.SCreateResponse
import org.json.JSONArray
import org.json.JSONObject

/**
 * 楼层信息服务
 *
 * @author 张维新
 */
object FloorService : Service<Floor>(SMybatisDao(Floor::class.java)) {

    /**
     * 创建之前操作
     */
    override fun onCreateBefore(floor: Floor): Boolean  {
        val projectId = SPageContext.getHeader("ProjectId")
        floor.projectId = projectId
        /** 楼层id */
        if (!floor.id.isNullOrEmpty()) {
            val isWith = floor.id!!.startsWith("Fl")
            if (!isWith) {
                floor.id = IdUtils.floorIdCreate(projectId!!)
            }
        } else {
            floor.id = IdUtils.floorIdCreate(projectId!!)
        }

        if (floor.name.isNullOrEmpty()){
            floor.name = ShaftNameUtil.shaftName("楼层-")
        }
        if (!floor.buildId.isNullOrEmpty()){
            val floorList = select(SFilter.eq("projectId", projectId!!), SFilter.eq("buildId", floor.buildId!!)).exec()
            if (floorList.size>0){
                for (floor001 in floorList){
                    if (floor001.sequenceId == floor.sequenceId){
                        return false
                    }
                }
            }
        }
        return true
    } // Function onCreateBefore()

  fun create(request: SCreateRequest<Floor>): SCreateResponse<Floor> {
      return try {
          val projectId = SPageContext.getHeader("ProjectId")
          val comming = SPageContext.getHeader("Coming")
          val account = SPageContext.getHeader("Account")
          if (!request.content.isNullOrEmpty()){
              for (floor in request.content){
                  try {
                      floor.projectId = projectId
                      /** 楼层id */
                      if (!floor.id.isNullOrEmpty()) {
                          val isWith = floor.id!!.startsWith("Fl")
                          if (!isWith) {
                              floor.id = IdUtils.floorIdCreate(projectId!!)
                          }
                      } else {
                          floor.id = IdUtils.floorIdCreate(projectId!!)
                      }

                      if (floor.name.isNullOrEmpty()){
                          floor.name = ShaftNameUtil.shaftName("楼层-")
                      }
                      if (!floor.buildId.isNullOrEmpty()){
                          val floorList = select(SFilter.eq("projectId", projectId!!), SFilter.eq("buildId", floor.buildId!!)).exec()
                          if (floorList.size>0){
                              for (floor001 in floorList){
                                  if (floor001.sequenceId == floor.sequenceId){
                                      val sCreateResponse = SCreateResponse<Floor>(SResponseType.failure)
                                      sCreateResponse.message = "楼层顺序号不可以重复"
                                      return sCreateResponse
                                  }
                              }
                          }
                      }
                      val insert = insert(floor)
                      if (insert){
                          try {
                              val jsonObject = JSONObject()
                              jsonObject.put("type", "1")
                              jsonObject.put("projectId", projectId)
                              jsonObject.put("id", floor.id)
                              jsonObject.put("obj_type", "Floor")
                              /** 发送消息 */
                              messageHandler.sendMessage(jsonObject.toString())
    //                kafkaService.sendNotice("datacenter", ObjectNotice(projectId!!, it.objectType!!, "create",IdUtils.uuidCreate(), hashSetOf(it.keyValue("id").toString())),false)

                          } catch (e: Exception) {
                              e.printStackTrace()
                          }
                          try {
                              /** 日志 */
                              val dataCenterLogs = DataCenterLogs()
                              dataCenterLogs.id = IdUtils.uuidCreate()
                              dataCenterLogs.author = "dataCenter"
                              dataCenterLogs.projectId = projectId
                              dataCenterLogs.objectType = "Floor"
                              dataCenterLogs.type = "create"
                              dataCenterLogs.coming = comming
                              dataCenterLogs.account = account
                              dataCenterLogs.objectId = floor.id
                              val hashMap = HashMap<String, Any?>()
                              hashMap["Floor"] = floor
                              dataCenterLogs.dataSource = hashMap
                              logService.insert(dataCenterLogs)
                          } catch (e: Exception) {
                              e.printStackTrace()
                          }
                      }
                  } catch (e: Exception) {
                      e.printStackTrace()
                  }
              }
              val sCreateResponse = SCreateResponse<Floor>(SResponseType.success)
              sCreateResponse.entityList = request.content
              return sCreateResponse

          }else{
              val sCreateResponse = SCreateResponse<Floor>(SResponseType.failure)
              sCreateResponse.message = "不可以传入空列表"
              return sCreateResponse
          }
      } catch (e: Exception) {
          e.printStackTrace()
          SCreateResponse(SResponseType.failure,e.message.toString())
      }
  } // Fun

    fun upDates(request: SUpdateRequest<Floor>): SBaseResponse{
        return try {
            val projectId = SPageContext.getHeader("ProjectId")
            val comming = SPageContext.getHeader("Coming")
            val account = SPageContext.getHeader("Account")
            val listId = ArrayList<String>()
            if (!request.content.isNullOrEmpty()){
                val jsonObject = JSONObject()
                jsonObject.put("type", "7")
                jsonObject.put("projectId", projectId)
                jsonObject.put("obj_type", "Floor")
                val jsonArray = JSONArray()
                for (floor in request.content!!){
                    if (!floor.buildId.isNullOrEmpty()){

                        val floorList = select(SFilter.eq("projectId", projectId!!), SFilter.eq("buildId", floor.buildId!!), SFilter.not(SFilter.eq("id",floor.id!!))).exec()
                        if (floorList.size>0){
                            for (floor001 in floorList){
                                try {
                                    if (floor001.sequenceId == floor.sequenceId){
                                        if (listId.size>0){
                                            for (id in listId){
                                                val jsonInfos = JSONObject()
                                                jsonInfos.put("id", id)
                                                jsonInfos.put("obj_type", "Floor")
                                                jsonArray.put(jsonInfos)
                                            }
                                            jsonObject.put("infos", jsonArray)
                                            /** 发送消息 */
                                            messageHandler.sendMessage(jsonObject.toString())
                                        }
                                        val sBaseResponse = SBaseResponse(SResponseType.failure)
                                        sBaseResponse.message = "楼层顺序号不可以重复"
                                        return sBaseResponse
                                    }
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }
                            }
                        }
                    }
                    try {
                        if (!request.projection.isNullOrEmpty()&&request.projection!!.size>0){

                            val update = update(floor, request.projection)
                            if (update){
                                listId.add(floor.id!!)
                                try {
                                    /** 日志 */
                                    val dataCenterLogs = DataCenterLogs()
                                    dataCenterLogs.id = IdUtils.uuidCreate()
                                    dataCenterLogs.author = "dataCenter"
                                    dataCenterLogs.projectId = projectId
                                    dataCenterLogs.objectType = "Floor"
                                    dataCenterLogs.type = "update-after"
                                    dataCenterLogs.account = account
                                    dataCenterLogs.coming = comming
                                    dataCenterLogs.objectId = floor.id
                                    val hashMap = HashMap<String, Any?>()
                                    hashMap["Floor"] = floor
                                    dataCenterLogs.dataSource = hashMap
                                    logService.insert(dataCenterLogs)
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }
                            }
                        }else{
                            val update = update(floor)
                            if (update){
                                listId.add(floor.id!!)
                                try {
                                    /** 日志 */
                                    val dataCenterLogs = DataCenterLogs()
                                    dataCenterLogs.id = IdUtils.uuidCreate()
                                    dataCenterLogs.author = "dataCenter"
                                    dataCenterLogs.projectId = projectId
                                    dataCenterLogs.objectType = "Floor"
                                    dataCenterLogs.type = "update-after"
                                    dataCenterLogs.account = account
                                    dataCenterLogs.coming = comming
                                    dataCenterLogs.objectId = floor.id
                                    val hashMap = HashMap<String, Any?>()
                                    hashMap["Floor"] = floor
                                    dataCenterLogs.dataSource = hashMap
                                    logService.insert(dataCenterLogs)
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }

                if (listId.size>0){
                    for (id in listId){
                        val jsonInfos = JSONObject()
                        jsonInfos.put("id", id)
                        jsonInfos.put("obj_type", "Floor")
                        jsonArray.put(jsonInfos)
                    }
                    jsonObject.put("infos", jsonArray)
                    /** 发送消息 */
                    messageHandler.sendMessage(jsonObject.toString())
                }
                val sBaseResponse = SBaseResponse(SResponseType.success)
                return sBaseResponse
            }else{
                val sBaseResponse = SBaseResponse(SResponseType.failure)
                return sBaseResponse
            }
        } catch (e: Exception) {
            e.printStackTrace()
            SBaseResponse(SResponseType.failure,e.message.toString())
        }
    } // Fun




    /**
     * 删除之前操作
     */
    override fun onDeleteBefore(entity: Floor): Boolean {
        val  floor = this.select(SFilter.eq("id", entity.id!!)).entity()

        val projectId = SPageContext.getHeader("ProjectId")
        val coming = SPageContext.getHeader("Coming")
        val account = SPageContext.getHeader("Account")
        /** 日志 */
        val dataCenterLogs = DataCenterLogs()
        dataCenterLogs.id = IdUtils.uuidCreate()
        dataCenterLogs.author = "dataCenter"
        dataCenterLogs.projectId = projectId
        dataCenterLogs.objectType = entity.objectType
        dataCenterLogs.type = "delete"
        dataCenterLogs.coming = coming
        dataCenterLogs.account = account
        dataCenterLogs.objectId = floor!!.id
        val hashMap = HashMap<String, Any?>()
        hashMap[entity.objectType!!] = floor
        dataCenterLogs.dataSource = hashMap
        logService.insert(dataCenterLogs)
        return super.onDeleteBefore(entity)
    } // Function onDeleteBefore()

    /**
     * 更新楼层 Outline
     */
    fun updateOutline(request: SUpdateRequest<Floor>): SBaseResponse{
        return try {
            val projectId = SPageContext.getHeader("ProjectId")
            val comming = SPageContext.getHeader("Coming")
            val account = SPageContext.getHeader("Account")
            val listId = ArrayList<String>()
            if (!request.content.isNullOrEmpty()){
                val jsonObject = JSONObject()
                jsonObject.put("type", "7")
                jsonObject.put("projectId", projectId)
                jsonObject.put("obj_type", "Floor")
                val jsonArray = JSONArray()
                for (floor in request.content!!){
                    try {
                        val listOutline = ArrayList<String>()
                        listOutline.add("Outline")
                            val update = update(floor,listOutline)
                            if (update){
                                listId.add(floor.id!!)
                                try {
                                    /** 日志 */
                                    val dataCenterLogs = DataCenterLogs()
                                    dataCenterLogs.id = IdUtils.uuidCreate()
                                    dataCenterLogs.author = "dataCenter"
                                    dataCenterLogs.projectId = projectId
                                    dataCenterLogs.objectType = "Floor"
                                    dataCenterLogs.type = "update-after"
                                    dataCenterLogs.account = account
                                    dataCenterLogs.coming = comming
                                    dataCenterLogs.objectId = floor.id
                                    val hashMap = HashMap<String, Any?>()
                                    hashMap["Floor"] = floor
                                    dataCenterLogs.dataSource = hashMap
                                    logService.insert(dataCenterLogs)
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }
                            }

                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }

                if (listId.size>0){
                    for (id in listId){
                        val jsonInfos = JSONObject()
                        jsonInfos.put("id", id)
                        jsonInfos.put("obj_type", "Floor")
                        jsonArray.put(jsonInfos)
                    }
                    jsonObject.put("infos", jsonArray)
                    /** 发送消息 */
                    messageHandler.sendMessage(jsonObject.toString())

                    try {
                        /** 处理关系标记 */
                        val listtype = ArrayList<String>()
                        listtype.add("sh2bd")
                        listtype.add("bd2sp")
                        listtype.add("fl2sp")
                        listtype.add("syeq2bd")
                        listtype.add("sy2fl")
                        listtype.add("eq2fl")
                        listtype.add("pe2bd")
                        listtype.add("pe2fl")
                        for (type in listtype){
                            val entity = EquipmentService.relationTypeProjectservice.select(SFilter.eq("projectId", projectId!!), SFilter.eq("relationType", type)).entity()
                            if (entity!=null){
                                entity.computationalState = 2
                                EquipmentService.relationTypeProjectservice.update(entity)
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
                val sBaseResponse = SBaseResponse(SResponseType.success)
                return sBaseResponse
            }else{
                val sBaseResponse = SBaseResponse(SResponseType.failure)
                return sBaseResponse
            }
        } catch (e: Exception) {
            e.printStackTrace()
            SBaseResponse(SResponseType.failure,e.message.toString())
        }
    } // Fun

    /**
     * @Description: 删除之后
     * @Param: entityList
     */
    override fun onDeleteSuccess(entityList: ArrayList<Floor>) {
        super.onDeleteSuccess(entityList)

        try {
            val projectId = SPageContext.getHeader("ProjectId")
            for (floor in entityList) {
                ObjInfoService.delete(SFilter.eq("projectId",projectId!!), SFilter.eq("objId",floor.id!!), SFilter.eq("objType","Fl"))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

//    /**
//     * @Description: 查找信息点选择创建或修改
//     * @Param: entityList,flag
//     */
//    fun findInfo(entityList: ArrayList<Floor>, flag: Boolean){
//        val prodefs = PropertyDefProjectService.select(SFilter.eq("projectId",entityList.get(0).projectId!!),SFilter.eq("firstTag","PeopleInfo"),SFilter.eq("type","Floor"), SFilter.or(SFilter.eq("inputMode","L"), SFilter.eq("inputMode","M"))).exec()
//        var peopleList = ArrayList<HashMap<String,String?>>()
//        for (prodef in prodefs) {
//            var itemMap = HashMap<String,String?>()
//            itemMap["firstTag"] = prodef.firstTag
//            itemMap["secondTag"] = prodef.secondTag
//            itemMap["infoPointCode"] = prodef.infoPointCode
//            peopleList.add(itemMap)
//        }
//        for (floor in entityList) {
//            if(floor.peopleInfo!=null){
//                BuildingService.createInfo("Fl",floor.projectId!!,floor.id!!,floor.lastUpdate,peopleList,floor.peopleInfo,flag)
//            }
//        }
//    }

    /**
     * @Description:创建成功后
     * @Param:entityList
     */
    override fun onCreateSuccess(entityList: ArrayList<Floor>) {
        super.onCreateSuccess(entityList)
        try {
            for (floor in entityList) {
                ObjInfoService.createInfo(floor,true,"Fl","Floor")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * @Description:更新成功后
     * @Param:entityList
     */
    override fun onUpdateSuccess(entityList: ArrayList<Floor>) {
        super.onUpdateSuccess(entityList)
        try {
            val projectId = SPageContext.getHeader("ProjectId")
            for (floor in entityList) {
                ObjInfoService.createInfo(floor,false,"Fl","Floor")
//                ObjInfoService.delete(SFilter.eq("projectId",projectId!!), SFilter.eq("objId",floor.id!!), SFilter.eq("objType","Fl"))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


} // Object FloorService