/*
 * ********************************************************************************************************************
 *
 *                     :*$@@%$*:                         ;:                ;;    ;;
 *                   :@@%!  :!@@%:                       %!             ;%%@@%$ =@@@@@@@%;     @%@@@%%%%@@@@@
 *                  :@%;       :$=                       %%$$$%$$         ;$$  ;$@=   !@$
 *                  =@!                                  %!              @ $=;%   !@@@%:      !$$$$$$$$$$$$$$=
 *                  =@*                                  %!              @ $= % %@=   =%@!      %=
 *             *$%%! @@=        ;=$%%%$*:                %!              @ $= % =%%%%%%@$      *%:         =%
 *           %@@!:    !@@@%=$@@@@%!  :*@@$:              %!              @ $= % $*     ;@      @*          :%*
 *         ;@@!          ;!!!;:         ;@%:      =======@%========*     @ $$ % $%*****$@     :@$=*********=@$
 *         $@*   ;@@@%=!:                *@*
 *         =@$    ;;;!=%@@@@=!           =@!
 *          %@$:      =@%: :*@@@*       %@=                    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.Opt
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.server.services.log.DataCenterLogsService
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.slf4j.LoggerFactory

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

    /** 日志 */
    private val logger = LoggerFactory.getLogger(FloorService::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.buildingId.isNullOrEmpty()){
            val floorList = select(SFilter.eq("projectId", projectId!!), SFilter.eq("buildingId", floor.buildingId!!)).exec()
            if (floorList.size>0){
                for (floor001 in floorList){
                    if (floor001.floorSequenceId == floor.floorSequenceId){
                        return false
                    }
                }
            }
        }
        return true
    } // Function onCreateBefore()

    /**
     * 创建楼层对象
     *
     * @param request       对象列表
     * @return 返回结果
     */
    fun create(request: SCreateRequest<Floor>): SCreateResponse<Floor> {
        return try {
            /** 项目 id */
            val projectId = SPageContext.getHeader("projectId")
            /** 来源 */
            val coming = 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.buildingId.isNullOrEmpty()){
                            val floorList = select(SFilter.eq("projectId", projectId!!),
                                SFilter.eq("buildingId", floor.buildingId!!)).exec()
                            if (floorList.size>0){
                                for (floor001 in floorList){
                                    if (floor001.floorSequenceId == floor.floorSequenceId){
                                        val sCreateResponse = SCreateResponse<Floor>(SResponseType.failure)
                                        sCreateResponse.message = "楼层顺序号不可以重复"
                                        return sCreateResponse
                                    }
                                }
                            }
                        }
                        val insert = insert(floor)
                        if (insert){
                            try {
                                rabbitMqService.sendObjects(projectId!!, Opt.CREATE,floor.id!!)
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                            try {
                                /** 日志 */
                                DataCenterLogsService.addLogs(projectId!!,"create","floor",
                                    floor!!.id!!,floor,account,coming)
                            } 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

    /**
     * 更新楼层信息
     *
     * @param request       楼层对象列表
     * @return 返回结果
     */
    fun upDates(request: SUpdateRequest<Floor>): SBaseResponse {
        return try {
            /** 项目 id */
            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.buildingId.isNullOrEmpty()){
                        val floorList = select(SFilter.eq("projectId", projectId!!),
                            SFilter.eq("buildingId", floor.buildingId!!), SFilter.not(SFilter.eq("id",floor.id!!))).exec()
                        if (floorList.size>0){
                            for (floor001 in floorList){
                                try {
                                    if (floor001.floorSequenceId == floor.floorSequenceId){
                                        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 hashMap = HashMap<String, Any?>()
//                                    hashMap["Floor"] = floor
//                                    /** 日志 */
//                                    val dataCenterLogs = DataCenterLogs(IdUtils.uuidCreate(),projectId,
//                                        "update-after",hashMap,"dataCenter",floor.id,comming,account)
//                                    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
//
//                                    dataCenterLogs.dataSource = hashMap
//                                    logService.insert(dataCenterLogs)

                                    rabbitMqService.sendObjects(projectId!!, Opt.UPDATE,floor.id!!)
                                    DataCenterLogsService.addLogs(projectId!!,"update-after","floor",
                                        floor.id!!,floor,account,comming)
                                } 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)

                                    rabbitMqService.sendObjects(projectId!!, Opt.UPDATE,floor.id!!)
                                    logger.debug("更新标记= ***********************************************************************************")
                                    DataCenterLogsService.addLogs(projectId!!,"update","floor",
                                        floor.id!!,floor,account,comming)
                                } 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)
                        rabbitMqService.sendObjects(projectId!!, Opt.UPDATE,id)
                    }
//                    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)
        DataCenterLogsService.addLogs(projectId!!,"delete","floor",
            floor!!.id!!,floor,account,coming)
        return super.onDeleteBefore(entity)
    } // Function onDeleteBefore()

    /**
     * 更新楼层 Outline
     */
    fun updateOutline(request: SUpdateRequest<Floor>): SBaseResponse{
        return try {
            val projectId = SPageContext.getHeader("projectId")
            val coming = 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 = coming
//                                dataCenterLogs.objectId = floor.id
//                                val hashMap = HashMap<String, Any?>()
//                                hashMap["Floor"] = floor
//                                dataCenterLogs.dataSource = hashMap
//                                logService.insert(dataCenterLogs)
                                DataCenterLogsService.addLogs(projectId!!,"update-after","floor",
                                    floor!!.id!!,floor,account,coming)
                            } 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)
                        rabbitMqService.sendObjects(projectId!!, Opt.UPDATE,id)
                    }
//                    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

    /**
     * 删除之后
     *
     * @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"))
                rabbitMqService.sendObjects(floor.projectId!!, Opt.DELETE,floor.id!!)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 创建成功后
     *
     * @Param entityList    楼层列表
     */
    override fun onCreateSuccess(entityList: ArrayList<Floor>) {
        super.onCreateSuccess(entityList)
        try {
            for (floor in entityList) {
                ObjInfoService.createInfo(floor,true,"Fl","Floor")
                rabbitMqService.sendObjects(floor.projectId!!, Opt.CREATE,floor.id!!)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 更新成功后
     *
     * @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")
                rabbitMqService.sendObjects(floor.projectId!!, Opt.UPDATE,floor.id!!)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


} // Object FloorService