/*
 * *********************************************************************************************************************
 *
 *          !!
 *        .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.datacenter.services.graphtype

import com.persagy.database.SFilter
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.datacenter.wanda.rel.REq2Sp
import com.persagy.server.datacenter.wanda.rel.REq2Sy
import com.persagy.server.datacenter.models.entities.graphtype.GraphicType
import com.persagy.server.datacenter.models.entities.graphtype.RelationTypeProject
import com.persagy.server.mappers.IRelationCountMapper
import com.persagy.server.datacenter.services.base.RService
import com.persagy.server.datacenter.wanda.rel.REq2Eq
import com.persagy.server.datacenter.wanda.rel.RSp2Sp
import com.persagy.server.datacenter.services.objects.EquipmentService
import com.persagy.server.datacenter.services.objects.ZoneSpaceBaseService
import com.persagy.service.SObjectService
import com.persagy.service.SPageContext
import com.persagy.service.models.enums.SResponseType
import com.persagy.service.models.responses.SQueryResponse
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
 * 查询总览
 *
 * @author  邓婷婷
 */
@Service
open class GraphicTypeMapperService {

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

    /** 实例化 mapper 对象 */
    @Autowired
    lateinit var mapper: IRelationCountMapper


    val rEq2SyService = SObjectService(SMybatisDao(REq2Sy::class.java))
    val rEq2EqService = RService(SMybatisDao(REq2Eq::class.java))
    val rEq2SpService = RService(SMybatisDao(REq2Sp::class.java))
    val rSp2SpService = RService(SMybatisDao(RSp2Sp::class.java))

    /**
     * 查询数量
     */
    fun queryCount(): SQueryResponse<GraphicType> {
        return try {
            val queryResponse = SQueryResponse<GraphicType>()
            val projectId = SPageContext.getHeader("projectId")
            val graphicTypeService = RService(SMybatisDao(GraphicType::class.java))
            val relationTypeProjectService = RService(SMybatisDao(RelationTypeProject::class.java))
            val graphicTypeList = graphicTypeService.select(SFilter.not(SFilter.isNull("parentId"))).exec()
            for(graphicType in graphicTypeList){
                val relationTypeProjectList = relationTypeProjectService.select(SFilter.eq("graphicId",graphicType.graphTypeId!!),SFilter.eq("projectId",projectId!!)).exec()
               logger.debug("數據={${graphicType.graphTypeName}  數量：{${relationTypeProjectList.size}} }")

                for(relationTypeProject in relationTypeProjectList){
                    val tableName = relationTypeProject.tableName
                    if(!tableName.isNullOrEmpty()&&tableName!=""){
                        val names = tableName.split(",")
                        var count = 0
                        for(n in names){
                            count += mapper.relationCount(n, projectId)
                        }
                        if(relationTypeProject.isThorough!!){
                            relationTypeProject.count = (count / 2).toLong()
                        }else{
                            relationTypeProject.count = count.toLong()
                        }
                    }else{
                        relationTypeProject.count = 0
                    }
                }
                graphicType.relationTypeProjectList = relationTypeProjectList
            }
            queryResponse.content = graphicTypeList
            queryResponse
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, e.message!!)
        }
    }

    /**
     * 查询数量
     */
    fun queryCounts(): SQueryResponse<GraphicType> {
        return try {



            val queryResponse = SQueryResponse<GraphicType>()
            val projectId = SPageContext.getHeader("projectId")
            val graphicTypeService = RService(SMybatisDao(GraphicType::class.java))
            val relationTypeProjectService = RService(SMybatisDao(RelationTypeProject::class.java))
            val graphicTypeList = graphicTypeService.select(SFilter.not(SFilter.isNull("parentId"))).exec()
            for(graphicType in graphicTypeList){
                val relationTypeProjectList = relationTypeProjectService.select(SFilter.eq("graphicId",graphicType.graphTypeId!!),SFilter.eq("projectId",projectId!!)).exec()

                for(relationTypeProject in relationTypeProjectList){
                    val tableName = relationTypeProject.tableName
                    if(!relationTypeProject.tableName.isNullOrEmpty()){
                        var count = 0
                        if (relationTypeProject.graphicType == "ArchSubset") {
                            /** 建筑从属关系 */
                            if (relationTypeProject.relationType == "Bd2Sp"){
                                /** 空间所在建筑 */
                                val zoneSpaceList = ZoneSpaceBaseService.select(SFilter.eq("projectId", projectId), SFilter.not(SFilter.isNull("buildingId"))).exec()
                                count = zoneSpaceList.size
                            } else if(relationTypeProject.relationType == "Fl2Sp") {
                                /** 空间所在楼层 */
                                val zoneSpaceList = ZoneSpaceBaseService.select(SFilter.eq("projectId", projectId), SFilter.not(SFilter.isNull("floorId"))).exec()
                                count = zoneSpaceList.size
                            }

                        }else if (relationTypeProject.graphicType == "MechInArch") {
                            /** 机电类所在区域关系 */
                            if (relationTypeProject.relationType == "Eq2Bd"){
                                /** 建筑下的设备  */
                                val equipmentList = EquipmentService.select(SFilter.eq("projectId", projectId), SFilter.not(SFilter.isNull("buildingId"))).exec()
                                count = equipmentList.size
                            } else if (relationTypeProject.relationType == "Eq2Fl"){
                                /** 楼层下的设备 */
                                val equipmentList = EquipmentService.select(SFilter.eq("projectId", projectId), SFilter.not(SFilter.isNull("floorId"))).exec()
                                count = equipmentList.size
                            }else if (relationTypeProject.relationType == "Eq2Sp"){
                                /** 设备所在的空间 */
                                val rEq2SpList = rEq2SpService.select(SFilter.eq("projectId", projectId), SFilter.eq("graphCode", relationTypeProject.graphicType!!),
                                        SFilter.eq("type", relationTypeProject.relationType!!), SFilter.eq("zoneType", relationTypeProject.zoneType!!)).exec()
                                count = rEq2SpList.size
                            }
                        } else if (relationTypeProject.graphicType == "ArchForArch") {
                            /** 区域服务关系 */
                            if (relationTypeProject.relationType == "Sp2Sp") {
                                val rSp2SpList = rSp2SpService.select(SFilter.eq("projectId", projectId), SFilter.eq("graphCode", relationTypeProject.graphicType!!),
                                        SFilter.eq("type", relationTypeProject.relationType!!)).exec()
                                count = rSp2SpList.size
                            }
                        }else if (relationTypeProject.graphicType == "MechSubset") {
                            /** 机电从属关系 */
                            if (relationTypeProject.relationType == "Sy2Eq") {
                                val rEq2SyList = rEq2SyService.select(SFilter.eq("projectId", projectId), SFilter.eq("graphCode", relationTypeProject.graphicType!!),
                                        SFilter.eq("type", relationTypeProject.relationType!!)).exec()
                                count = rEq2SyList.size
                            }
                        }else if (relationTypeProject.graphicType == "MechForArch") {
                            /** 机电类服务区域关系 */
                            if (relationTypeProject.relationType == "Eq2Sp") {
                                val rEq2SpList = rEq2SpService.select(SFilter.eq("projectId", projectId), SFilter.eq("graphCode", relationTypeProject.graphicType!!),
                                        SFilter.eq("type", relationTypeProject.relationType!!), SFilter.eq("zoneType", relationTypeProject.zoneType!!)).exec()
                                count = rEq2SpList.size
                            }
                        }

                        relationTypeProject.count = count.toLong()
                    }else{
                        relationTypeProject.count = 0
                    }
                }
                graphicType.relationTypeProjectList = relationTypeProjectList
            }
            queryResponse.content = graphicTypeList
            queryResponse
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, e.message!!)
        }
    }

    /**
     * 更新状态
     */
    fun updateState(id: String,computationalState: Long): Boolean{
        return mapper.updateState(id,computationalState)
    } // Fun

} // Class GraphicTypeMapperService