/*
 * *********************************************************************************************************************
 *
 *          !!
 *        .F88X
 *        X8888Y
 *      .}888888N;
 *        i888888N;        .:!              .I$WI:
 *          R888888I      .'N88~            i8}+8Y&8"l8i$8>8W~'>W8}8]KW+8IIN"8&
 *          .R888888I    .;N8888~          .X8'  "8I.!,/8"  !%NY8`"8I8~~8>,88I
 *            +888888N;  .8888888Y                                  "&&8Y.}8,
 *            ./888888N;  .R888888Y        .'}~    .>}'.`+>  i}!    "i'  +/'  .'i~  !11,.:">,  .~]!  .i}i
 *              ~888888%:  .I888888l      .]88~`1/iY88Ii+1'.R$8$8]"888888888>  Y8$  W8E  X8E  W8888'188Il}Y88$*
 *              18888888    E8888881    .]W%8$`R8X'&8%++N8i,8N%N8+l8%`  .}8N:.R$RE%N88N%N$K$R  188,FE$8%~Y88I
 *            .E888888I  .i8888888'      .:$8I;88+`E8R:/8N,.>881.`$8E/1/]N8X.Y8N`"KF&&FK!'88*."88K./$88%RN888+~
 *            8888888I  .,N888888~        ~88i"8W,!N8*.I88.}888%F,i$88"F88"  888:E8X.>88!i88>`888*.}Fl1]*}1YKi'
 *          i888888N'      I888Y          ]88;/EX*IFKFK88X  K8R  .l8W  88Y  ~88}'88E&%8W.X8N``]88!.$8K  .:W8I
 *        .i888888N;        I8Y          .&8$  .X88!  i881.:%888>I88  ;88]  +88+.';;;;:.Y88X  18N.,88l  .+88/
 *      .:R888888I
 *      .&888888I                                          Copyright (c) 2009-2020.  博锐尚格科技股份有限公司
 *        ~8888'
 *        .!88~                                                                     All rights reserved.
 *
 * *********************************************************************************************************************
 */

package com.persagy.server.services.objects

import com.persagy.database.SFilter
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.Opt
import com.persagy.server.datacenter.wanda.obj.Floor
import com.persagy.server.datacenter.models.entities.objects.FloorOutline
import com.persagy.server.datacenter.services.objects.EquipmentService
import com.persagy.server.services.base.Service
import com.persagy.server.services.log.DataCenterLogsService
import com.persagy.server.utils.IdUtils
import com.persagy.server.utils.ShaftNameUtil
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.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)
    /** 楼层轮廓线 */
    val floorOutlineService = SObjectService(SMybatisDao(FloorOutline::class.java))
    /**
     * 创建之前操作
     */
    override fun onCreateBefore(floor: Floor): Boolean  {
        floor.projectId = Opt.projectId
        /** 楼层 id */
        if (!floor.id.isNullOrEmpty()) {
            val isWith = floor.id!!.startsWith("Fl")
            if (!isWith) {
                floor.id = IdUtils.floorIdCreate(Opt.projectId!!)
            }
        } else {
            floor.id = IdUtils.floorIdCreate(Opt.projectId!!)
        }

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

    /**
     * 创建楼层对象
     *
     * @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 = Opt.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(Opt.projectId!!, Opt.CREATE,floor.id!!)
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                            try {
                                /** 日志 */
                                DataCenterLogsService.addLogs(Opt.projectId!!,"create","floor",
                                    floor.id!!,floor,Opt.account,Opt.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())
        }
    }

    /**
     * 更新楼层信息
     *
     * @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()){
                /** 遍历楼层列表 */
                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 {
                            val update = update(floor)
                            if (update){
                                listId.add(floor.id!!)
                                try {
                                    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){
                        rabbitMqService.sendObjects(projectId!!, Opt.UPDATE,id)
                    }
                }
                return SBaseResponse(SResponseType.success)
            }else{
                return SBaseResponse(SResponseType.failure)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            SBaseResponse(SResponseType.failure,e.message.toString())
        }
    }

    /**
     * 删除之前操作
     */
    override fun onDeleteBefore(entity: Floor): Boolean {
        val  floor = this.select(SFilter.eq("id", entity.id!!)).entity()
        /** 日志 */
        if (floor!=null){
            DataCenterLogsService.addLogs(Opt.projectId!!,"delete","floor",
                floor!!.id!!,floor,Opt.account,Opt.coming)
        }
        return super.onDeleteBefore(entity)
    }

    /**
     * 更新楼层 Outline
     */
    fun updateOutline(request: SUpdateRequest<Floor>): SBaseResponse{
        return try {
            val sBaseResponse = SBaseResponse(SResponseType.success)
            if (!request.content.isNullOrEmpty()){
                val listOutline = ArrayList<String>()
                listOutline.add("outline")
                if (!request.content.isNullOrEmpty()){
                    for (floorOutline in request.content!!){
                        val update = update(floorOutline, listOutline)
                        if (update) {
                            rabbitMqService.sendObjects(Opt.projectId!!, Opt.UPDATE,floorOutline.id!!)
                        }
                    }
                    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", Opt.projectId!!), SFilter.eq("relationType", type)).entity()
                            if (entity!=null){
                                entity.computationalState = 2
                                EquipmentService.relationTypeProjectservice.update(entity)
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }

                return sBaseResponse
            }else{
                sBaseResponse.result = SResponseType.failure
                return sBaseResponse
            }

        } catch (e: Exception) {
            e.printStackTrace()
            SBaseResponse(SResponseType.failure,e.message.toString())
        }
    }

    /**
     * 删除之后
     *
     * @Param entityList    楼层列表
     */
    override fun onDeleteSuccess(entityList: ArrayList<Floor>) {
        super.onDeleteSuccess(entityList)
        try {
            for (floor in entityList) {
                rabbitMqService.sendObjects(Opt.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) {
                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 {
            for (floor in entityList) {
                rabbitMqService.sendObjects(floor.projectId!!, Opt.UPDATE,floor.id!!)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}