/*
 * ********************************************************************************************************************
 *
 *                     :*$@@%$*:                         ;:                ;;    ;;
 *                   :@@%!  :!@@%:                       %!             ;%%@@%$ =@@@@@@@%;     @%@@@%%%%@@@@@
 *                  :@%;       :$=                       %%$$$%$$         ;$$  ;$@=   !@$
 *                  =@!                                  %!              @ $=;%   !@@@%:      !$$$$$$$$$$$$$$=
 *                  =@*                                  %!              @ $= % %@=   =%@!      %=
 *             *$%%! @@=        ;=$%%%$*:                %!              @ $= % =%%%%%%@$      *%:         =%
 *           %@@!:    !@@@%=$@@@@%!  :*@@$:              %!              @ $= % $*     ;@      @*          :%*
 *         ;@@!          ;!!!;:         ;@%:      =======@%========*     @ $$ % $%*****$@     :@$=*********=@$
 *         $@*   ;@@@%=!:                *@*
 *         =@$    ;;;!=%@@@@=!           =@!
 *          %@$:      =@%: :*@@@*       %@=                    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.base.extensions.toJson
import com.persagy.database.SFilter
import com.persagy.database.SQueryBuilder
import com.persagy.database.extensions.keyValue
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.datacenter.models.entities.assistant.ObjInfos
import com.persagy.server.datacenter.models.entities.graphtype.RelationTypeProject
import com.persagy.server.datacenter.models.entities.logs.DataCenterLogs
import com.persagy.server.datacenter.models.entities.objects.Equipment
import com.persagy.server.datacenter.models.entities.objects.Property
import com.persagy.server.scanbuilding.UserLog
import com.persagy.server.services.assistant.ObjInfoService
import com.persagy.server.services.base.Service
import com.persagy.service.SBaseService
import com.persagy.service.SPageContext
import com.persagy.service.models.enums.SResponseType
import com.persagy.service.models.requests.SUpdateRequest
import com.persagy.service.models.responses.SQueryResponse
import org.json.JSONArray
import org.json.JSONObject
import org.slf4j.LoggerFactory

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

    private val logger = LoggerFactory.getLogger(EquipmentService::class.java)

    /** 关系总览服务 */
    val relationTypeProjectservice = SBaseService(SMybatisDao(RelationTypeProject::class.java))

    /**
     * 创建前赋值操作
     *
     * @param   equip   设备对象
     */
    override fun onCreateBefore(equip: Equipment): Boolean {
        /** 查询准备类型 */
        val projectId = SPageContext.getHeader("ProjectId")
        if (!equip.id.isNullOrEmpty()) {
            val isStartsWith = equip.id.toString().startsWith("Eq")
            if (!isStartsWith) {
                /** 资产id */
                equip.id = IdUtils.equipmentIdCreate(projectId!!)
            }
        } else {
            /** 资产id */
            equip.id = IdUtils.equipmentIdCreate(projectId!!)
        }
        /** 项目id */
        equip.projectId = projectId
        /** 设备名字 */
        if (equip.name.isNullOrEmpty()) {
            equip.name = ShaftNameUtil.shaftName("设备-")
        }

        equip.codeType = 1
        return true
    } // Function onCreateBefore()

    override fun onCountSuccess(count: Long) {
        super.onCountSuccess(count)

    }


    /**
     * 查询设备数量之前设置条件
     *
     * @param   queryBuilder    条件信息
     */
    override fun onCountBefore(queryBuilder: SQueryBuilder<Equipment>) {
        queryBuilder.tableName = "v_equipment"
        return
    }  // Function onCreateBefore()

    /**
     * 查询设备之前添加条件方法
     *
     * @param   queryBuilder    条件信息
     */
    override fun onQueryBefore(queryBuilder: SQueryBuilder<Equipment>) {
        queryBuilder.tableName = "v_equipment"
        /** 调整数量 */
//        SQueryRequest.maxRow
//        val pr = PropertyService.select(SFilter.eq("id", "Pe20b75606191ea7ab530b314b0abaa176")).entity()
//        val listp = ArrayList<Property>()
//        pr!!.equipId = null
//        listp.add(pr)
//        val sUpdate= SUpdateRequest<Property>()
//        sUpdate.content = listp
//        sUpdate.projection = arrayListOf("EquipmentId")
//        PropertyService.updateList(sUpdate)
//        logger.debug("修改结束*********************************")
////
//        val list = arrayListOf("1180765",
//                "1180762")
//        this.select(SFilter.inList(SEndWithChar("bimId",":"),list) ).exec()

        return
    } // Function onCreateBefore()

    /**
     * 修改设备信息之前的操作
     */
    override fun onUpdateBefore(entity: Equipment): Boolean {
        try {
            val projectId = SPageContext.getHeader("ProjectId")
            if (entity.propertyId.isNullOrEmpty()) {
//                val property = PropertyService.select(SFilter.eq("equipmentId", entity.id!!)).entity()
//                logger.debug("设备初次关联*********************************")
//                if (property!=null){
//                    property.equipId = null
//                    val list = ArrayList<Property>()
//                    list.add(property)
//                    val sUpdateRequest = SUpdateRequest<Property>()
//                    sUpdateRequest.content = list
//                    sUpdateRequest.projection = arrayListOf("EquipmentId")
//                    PropertyService.updateList(sUpdateRequest)
//                }
            } else {
                val property = PropertyService.select(SFilter.eq("equipmentId", entity.id!!)).entity()
                if (property != null) {

                    logger.debug("已经有关联的信息*********************************")
                    /** 设备关联的资产如果更改了先取消以前的，在关联新的 */
                    if (entity.propertyId != property.id) {
                        property.equipId = null
                        property.bimId = null
                        val list = ArrayList<Property>()
                        list.add(property)
                        val sUpdateRequest = SUpdateRequest<Property>()
                        sUpdateRequest.content = list
                        sUpdateRequest.projection = arrayListOf("EquipmentId", "BIMID")

                        val updateList = PropertyService.updateList(sUpdateRequest)
                        logger.debug("现在**${sUpdateRequest.toJson()}*******************************")
                        logger.debug("现在**${updateList.toJson()}*******************************")

                        val pr = PropertyService.select(SFilter.eq("id", entity.propertyId!!)).entity()
                        val listp = ArrayList<Property>()
                        pr!!.equipId = entity.id
                        pr.bimId = entity.bimId
                        listp.add(pr)
                        val sUpdate = SUpdateRequest<Property>()
                        sUpdate.content = listp
                        sUpdate.projection = arrayListOf("EquipmentId", "BIMID")
                        PropertyService.updateList(sUpdate)
                        logger.debug("现在关联**${sUpdate.toJson()}*******************************")

                        try {
                            /** 处理关系标记 */
                            val listtype = ArrayList<String>()
                            listtype.add("pe2bd")
                            listtype.add("pe2fl")
                            listtype.add("pe2sh")
                            listtype.add("pe2sp")
                            for (type in listtype){
                                val entity = relationTypeProjectservice.select(SFilter.eq("projectId", projectId!!), SFilter.eq("relationType", type)).entity()
                                if (entity!=null){
                                    entity.computationalState = 2
                                    relationTypeProjectservice.update(entity)
                                }
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                } else {
                    val prop = PropertyService.select(SFilter.eq("id", entity.propertyId!!)).entity()
                    logger.debug("第一次关联***${prop!!.toJson()}******************************")
                    if (prop != null) {
                        prop.equipId = entity.id
                        prop.lastUpdate = null
                        prop.createTime = null
                        prop.name = "1236"
                        val listp = ArrayList<Property>()
                        listp.add(prop)
                        val sUpdate = SUpdateRequest<Property>()
                        sUpdate.content = listp
                        sUpdate.projection = arrayListOf("EquipmentId")
                        val updateList = PropertyService.updateList(sUpdate)
                        logger.debug("第一次更新信息***${sUpdate.toJson()}******************************")
                        logger.debug("第一次更新***${updateList.toJson()}******************************")
                        try {
                            /** 处理关系标记 */
                            val listtype = ArrayList<String>()
                            listtype.add("pe2bd")
                            listtype.add("pe2fl")
                            listtype.add("pe2sh")
                            listtype.add("pe2sp")
                            for (type in listtype){
                                val entity = relationTypeProjectservice.select(SFilter.eq("projectId", projectId!!), SFilter.eq("relationType", type)).entity()
                                if (entity!=null){
                                    entity.computationalState = 2
                                    relationTypeProjectservice.update(entity)
                                }
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            }

            try {
                val projectId = SPageContext.getHeader("ProjectId")
                val comming = 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 = "update-before"
                dataCenterLogs.account = account
                dataCenterLogs.coming = comming
                dataCenterLogs.objectId = entity.keyValue("id").toString()
                val hashMap = HashMap<String, Any?>()
                hashMap[entity.objectType!!] = entity
                dataCenterLogs.dataSource = hashMap
                logService.insert(dataCenterLogs)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return true
    } // Function onUpdateBefore()




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

            val projectId = SPageContext.getHeader("ProjectId")
            val coming = SPageContext.getHeader("Coming")
            val account = SPageContext.getHeader("Account")
            try {
                /** 日志 */
                val dataCenterLogs = DataCenterLogs()
                dataCenterLogs.id = IdUtils.uuidCreate()
                dataCenterLogs.author = "dataCenter"
                dataCenterLogs.projectId = projectId
                dataCenterLogs.objectType = entity.objectType
                dataCenterLogs.type = "delete"
                dataCenterLogs.account = account
                dataCenterLogs.coming = coming
                dataCenterLogs.objectId = equipment!!.id
                val hashMap = HashMap<String, Any?>()
                hashMap[entity.objectType!!] = equipment
                dataCenterLogs.dataSource = hashMap
                logService.insert(dataCenterLogs)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            /** 清除对应关系 */
            if (equipment != null) {
                val property = PropertyService.select(SFilter.eq("EquipmentId", equipment.id!!)).entity()
                if (property != null && equipment.taskState != null && equipment.taskState == -1 && property.taskState != null && property.taskState == -1) {
                    val list = ArrayList<Property>()
                    list.add(property)
                    PropertyService.deleteByKeysList(list)
                } else {
                    if (property != null) {
                        property.equipId = null
                        property.bimId = null
                        val list = ArrayList<Property>()
                        list.add(property)
                        val sUpdateRequest = SUpdateRequest<Property>()
                        sUpdateRequest.content = list
                        val listStr = ArrayList<String>()
                        listStr.add("EquipmentId")
                        listStr.add("BIMID")
                        sUpdateRequest.projection = listStr
                        PropertyService.updateList(sUpdateRequest)
                    }
                }
            }

        } catch (e: Exception) {
            e.printStackTrace()
        }
        return super.onDeleteBefore(entity)
    } // Function onDeleteBefore()

    /**
     * 查询项目下的设备和部件
     */
    fun queryEquipCom(): SQueryResponse<Equipment> {
        return try {
            val projectId = SPageContext.getHeader("ProjectId")
            val equipList = select(SFilter.eq("projectId", projectId!!)).exec()
            val sQueryResponse = SQueryResponse<Equipment>(SResponseType.success)
            sQueryResponse.content = equipList
            sQueryResponse
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure)
        }
    } // Function queryEquipCom()

    override fun onCreateSuccess(entityList: ArrayList<Equipment>) {
        entityList.forEach {
            val projectId = SPageContext.getHeader("ProjectId")
            val comming = SPageContext.getHeader("Coming")
            val account = SPageContext.getHeader("Account")

            try {
                val jsonObject = JSONObject()
                jsonObject.put("type", "1")
                jsonObject.put("projectId", projectId)
                jsonObject.put("id", it.keyValue("id"))
                jsonObject.put("obj_type", it.objectType)
                /** 发送消息 */
                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 entity = EquipmentService.select(SFilter.eq("equipId", it.keyValue("id")!!)).entity()
                if (entity != null) {
                    /** 日志 */
                    val dataCenterLogs = DataCenterLogs()
                    dataCenterLogs.id = IdUtils.uuidCreate()
                    dataCenterLogs.author = "dataCenter"
                    dataCenterLogs.projectId = projectId
                    dataCenterLogs.objectType = it.objectType
                    dataCenterLogs.type = "create"
                    dataCenterLogs.coming = comming
                    dataCenterLogs.account = account
                    dataCenterLogs.objectId = it.keyValue("id").toString()
                    val hashMap = HashMap<String, Any?>()
                    hashMap[it.objectType!!] = it
                    dataCenterLogs.dataSource = hashMap
                    logService.insert(dataCenterLogs)

                    //添加信息点创建 表号功能号
                    ObjInfoService.createInfo(entity,true,"Eq",entity.category!!)
                }

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

    /**
     * 更新成功能回调函数
     *
     * @param   entityList      更新成功对象列表
     */
    override fun onUpdateSuccess(entityList: ArrayList<Equipment>) {
        val projectId = SPageContext.getHeader("ProjectId")
        val comming = SPageContext.getHeader("Coming")
        val account = SPageContext.getHeader("Account")
        try {
            val jsonObject = JSONObject()
            jsonObject.put("type", "7")
            jsonObject.put("projectId", projectId)
            jsonObject.put("obj_type", entityList[0].objectType)
            val jsonArray = JSONArray()
            for (entity in entityList) {
                val jsonInfos = JSONObject()
                jsonInfos.put("id", entity.keyValue("id"))
                jsonInfos.put("obj_type", entity.objectType)
                jsonArray.put(jsonInfos)
                try {
                    val equip = EquipmentService.select(SFilter.eq("equipId", entity.keyValue("id")!!)).entity()
                    if (equip != null) {
                        /** 日志 */
                        val dataCenterLogs = DataCenterLogs()
                        dataCenterLogs.id = IdUtils.uuidCreate()
                        dataCenterLogs.author = "dataCenter"
                        dataCenterLogs.projectId = projectId
                        dataCenterLogs.objectType = entity.objectType
                        dataCenterLogs.type = "update-after"
                        dataCenterLogs.account = account
                        dataCenterLogs.coming = comming
                        dataCenterLogs.objectId = entity.keyValue("id").toString()
                        val hashMap = HashMap<String, Any?>()
                        hashMap[entity.objectType!!] = entity
                        dataCenterLogs.dataSource = hashMap
                        logService.insert(dataCenterLogs)

                        //更新信息点 表号功能号
                        ObjInfoService.createInfo(entity,false,"Eq",entity.category!!)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                try {
                    /** 发送消息 */
//                    kafkaService.sendNotice("datacenter", ObjectNotice(projectId!!, entity.objectType!!, "update", IdUtils.uuidCreate(), hashSetOf(entity.keyValue("id").toString())), false)
                } catch (e: Exception) {
                    e.toString()
                }

            }
            jsonObject.put("infos", jsonArray)
            logger.debug("修改发送消息$jsonObject")
            /** 发送消息 */
            messageHandler.sendMessage(jsonObject.toString())


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

        try {
            for (entity in entityList){
                try {
                    if (!comming.isNullOrEmpty()){
                        if (comming == "app"){
                            val user = LocationPointServices.userService.select(SFilter.eq("projectId", projectId!!), SFilter.eq("phone", account!!)).entity()
                            val userLog = UserLog()
                            userLog.comming = "app"
                            userLog.action = "更新设备"
                            userLog.id = IdUtils.uuidCreate()
                            userLog.note = "项目ID: "+projectId+" 用户ID："+user!!.id+" 手机号："+ account+" 请求来源："+comming+ " "+entity.toJson()
                            userLog.phone = account
                            userLog.projectId = projectId
                            userLog.userId = user!!.id
                            userLog.name = user.name
                            userLog.objectId = entity.id
                            LocationPointServices.userLogService.insert(userLog)
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    } // Function onUpdateSuccess()

    /**
     * @Description:删除成功之后
     */
    override fun onDeleteSuccess(entityList: ArrayList<Equipment>) {
        super.onDeleteSuccess(entityList)
        try {
            val projectId = SPageContext.getHeader("ProjectId")
            val oService = SBaseService(SMybatisDao(ObjInfos::class.java))
            for (entity in entityList) {
                //更新信息点 表号功能号
                oService.delete(SFilter.eq("projectId",projectId!!), SFilter.eq("objId",entity.id!!), SFilter.eq("objType","Eq"))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }




} // Object EquipmentService