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

import com.persagy.database.SFilter
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.datacenter.models.entities.graphtype.GraphicType
import com.persagy.server.datacenter.models.entities.graphtype.RelationTypeProject
import com.persagy.server.datacenter.models.entities.rel.*
import com.persagy.server.mappers.IRelationCountMapper
import com.persagy.server.services.base.RService
import com.persagy.server.services.objects.EquipmentService
import com.persagy.server.services.objects.FloorService
import com.persagy.server.services.objects.PropertyService
import com.persagy.server.services.rel.RSyInBdService
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

    /**
     * 查询数量
     */
    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 rTn2SptService = RService(SMybatisDao(RTn2Sp::class.java))
            val rSh2SpService = RService(SMybatisDao(RSh2Sp::class.java))
            val rEq2SyService = RService(SMybatisDao(REq2Sy::class.java))
            val rPe2SpService = SObjectService(SMybatisDao(RPe2Sp::class.java))
            val rEq2EqService = RService(SMybatisDao(REq2Eq::class.java))
            val rSy2SpService = RService(SMybatisDao(RSy2Sp::class.java))
            val rEq2SpService = RService(SMybatisDao(REq2Sp::class.java))
            val rSp2SpService = RService(SMybatisDao(RSp2Sp::class.java))
            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(!tableName.isNullOrEmpty()&&tableName!=""){
                        var count = 0
                        val names = tableName.split(",")
                        for(n in names){
                            logger.debug("數據=${n  }")
                            if (n == "r_sy_in_fl"||n =="r_sh_through_sh"||n =="r_sh_in_bd"
                                    ||n =="r_sy_for_bd"|| n =="r_sy_in_sh"|| n =="r_eq_for_fl"
                                    || n =="r_sy_for_fl"||n =="r_sy_eq"||n =="r_sy_for_sh"
                                    ||n =="r_fl_through_fl"||n =="zone_space_base"||n =="floor"||n =="equipment"
                                    ||n =="general_system"||n =="r_eq_for_sh"||n =="r_eq_in_sh"
                                    ||n =="r_pe_in_sh"||n =="r_eq_for_bd"||n =="property"||n == "r_sp_in_bd"
                                    ||n =="r_sp_in_fl"){
                                count += mapper.relationCount(n, projectId)
                            }else if (n =="r_tn2sp"){
                                val exec = rTn2SptService.select(SFilter.eq("projectId", projectId), SFilter.eq("type", relationTypeProject.relationType!!)).exec()
                                count += exec.size
                            }else if (n =="r_sh2sp"){
                                try {
                                    logger.debug("类型=${relationTypeProject.relationType  }")
                                    val exec = rSh2SpService.select(SFilter.eq("ProjectId", projectId), SFilter.eq("Type", relationTypeProject.relationType!!)).exec()
                                    count += exec.size
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }
                            }else if (n =="r_eq2sy"){
                                val exec = rEq2SyService.select(SFilter.eq("projectId", projectId), SFilter.eq("type", relationTypeProject.relationType!!)).exec()
                                count += exec.size
                            }else  if (n =="r_pe2sp"){
                                val exec = rPe2SpService.select(SFilter.eq("ProjectId", projectId), SFilter.eq("Type", relationTypeProject.relationType!!)).exec()
                                count += exec.size
                                logger.debug("资产= ${exec.size}")
                            }else if (n =="r_eq2eq"){
                                val exec = rEq2EqService.select(SFilter.eq("projectId", projectId), SFilter.eq("type", relationTypeProject.relationType!!)).exec()
                                count += exec.size
                            }else if (n =="r_sy2sp"){
                                val exec = rSy2SpService.select(SFilter.eq("projectId", projectId), SFilter.eq("type", relationTypeProject.relationType!!)).exec()
                                count += exec.size
                            }else if (n =="r_eq2sp"){
                                if (!relationTypeProject.zoneType.isNullOrEmpty()){
                                    val exec = rEq2SpService.select(SFilter.eq("projectId", projectId), SFilter.eq("type", relationTypeProject.relationType!!),SFilter.eq("ZoneType", relationTypeProject.zoneType!!)).exec()
                                    count += exec.size
                                    logger.debug("空间数量=${relationTypeProject.relationType  }    ${exec.size} ****************************************************************************************************")
                                }else{
                                    val exec = rEq2SpService.select(SFilter.eq("projectId", projectId), SFilter.eq("type", relationTypeProject.relationType!!)).exec()
                                    count += exec.size
                                }
                            }else if (n =="r_sp2sp"){
                                val exec = rSp2SpService.select(SFilter.eq("projectId", projectId), SFilter.eq("type", relationTypeProject.relationType!!)).exec()
                                count += exec.size
                            }else if (n == "property_eq"){
                                val exec = PropertyService.select(SFilter.eq("projectId", projectId), SFilter.not(SFilter.isNull("EquipmentId"))).exec()
                                count += exec.size
                            }else if (n == "property_fl"){
                                val exec = PropertyService.select(SFilter.eq("projectId", projectId), SFilter.not(SFilter.isNull("floorId"))).exec()
                                count += exec.size
                            }else if (n == "equipment_com"){
                                val exec = EquipmentService.select(SFilter.eq("projectId", projectId), SFilter.not(SFilter.isNull("parentId"))).exec()
                                count = exec.size
                            }else if (n == "bd_sy_eq_com"){
                                val rSyInBdList = RSyInBdService.select(SFilter.eq("projectId", projectId)).exec()
                                count += rSyInBdList.size
                                val execEquip = EquipmentService.select(SFilter.eq("projectId", projectId), SFilter.not(SFilter.isNull("buildingId"))).exec()
                                count += execEquip.size
                                val exec = EquipmentService.select(SFilter.eq("projectId", projectId), SFilter.not(SFilter.isNull("parentId"))).exec()
                                count += exec.size
                            }else if (n == "property_bd"){
                                val execEquip = PropertyService.select(SFilter.eq("projectId", projectId), SFilter.not(SFilter.isNull("buildingId"))).exec()
                                count += execEquip.size
                            }else if (n == "floor_bd"){
                                val execEquip = FloorService.select(SFilter.eq("projectId", projectId), SFilter.not(SFilter.isNull("buildId"))).exec()
                                count += execEquip.size
                            }else if (n == "equipment_fl"){
                                val execEquip = EquipmentService.select(SFilter.eq("projectId", projectId), SFilter.not(SFilter.isNull("floorId")))
                                execEquip.tableName = "v_equipment"
                                val exec = execEquip.exec()
                                count += exec.size
                            }
                        }
//                        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

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

} // Class GraphicTypeMapperService