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

import org.apache.ibatis.jdbc.SQL
import org.slf4j.LoggerFactory
import java.util.*


/**
 * 关系SQL提供器
 *
 * @author  庞利祥<sybotan@126.com>
 */
class RelationProvider {
    companion object {
        // 日志
        private val logger = LoggerFactory.getLogger(RelationProvider::class.java)
    }

    /**
     * 查询对象ID
     *
     * @param   projectId           项目ID
     */
    fun findObjectId(projectId: String, table: String, code: String, codeValue: String): String {
        val sql = object: SQL() {
            init {
                SELECT("id")
                FROM(table)
                WHERE("\"$code\"='$codeValue'")
                WHERE("\"project_id\"='$projectId'")
            }
        }.toString()
        return sql
    } // Fun findObjectId()


    /**
     * 获取模型里的设备uuid到数据中心设备的映射
     *
     * @param   projectId           项目ID
     * @param   equipIds            设备在模型里的uuid
     */
    fun getEquipIdUUIDMap(projectId: String, equipIds : Set<String>): String {
        val uuids = concateStr(equipIds)
        val sql = object: SQL() {
            init {
                //select eq.id equipId, deq.id revitUUID from revit.equipment eq inner join public.equipment deq on deq.bim_id = eq.bimid where eq.id in ('') and deq.project_id = ''
                SELECT("eq.id equipId, deq.id revitUUID")
                FROM("revit.equipment eq")
                INNER_JOIN("public.equipment deq on deq.bim_id = eq.bimid")
                WHERE("eq.id in (${uuids}) and deq.project_id = '${projectId}'")
            }
        }.toString()
        return sql
    } // Fun findObjectId()

    /**
     * 获取模型里的设备uuid到数据中心设备的映射
     *
     * @param   projectId           项目ID
     * @param   equipIds            设备在模型里的uuid
     */
    fun getEquipPartIdUUIDMap(projectId: String, equipIds : Set<String>): String {
        val uuids = concateStr(equipIds)
        val sql = object: SQL() {
            init {
                //select eq.id equipId, deq.id revitUUID from revit.equipment eq inner join public.equipment deq on deq.bim_id = eq.bimid where eq.id in ('') and deq.project_id = ''
                SELECT("eq.id equipId, deq.id revitUUID")
                FROM("revit.component eq")
                INNER_JOIN("public.equipment deq on deq.bim_id = eq.bimid")
                WHERE("eq.id in (${uuids}) and deq.project_id = '${projectId}'")
            }
        }.toString()
        return sql
    } // Fun findObjectId()

    /**
     * 获取分块中指定bimid 的对象
     *
     * @param   projectId           项目ID
     */
    fun getEquipByBimId(projectId: String, buildingId : String?, mepSystemType: ArrayList<String>, bimId: ArrayList<String>): String {
        var mepStr = concateStr(mepSystemType)
        var bimStr = concateStr(bimId)
        val sql1 = object: SQL() {
            init {
                SELECT("id1 sourceId, block.project_id projectId, block.block_id blockId, block.type1 as sourceType, domain, mep_system_type mepSystemType, building_id buildingId")
                FROM("revit_calc.connected_block block")
                INNER_JOIN("revit.equipment eq on eq.id = block.id1")
                WHERE("block.project_id = '${projectId}'")
                AND()
                WHERE("mep_system_type in (${mepStr})")
                AND()
                WHERE("bimid in (${bimStr})")
                if(buildingId != null) {
                    AND()
                    WHERE("building_id = '${buildingId}'")
                }
            }
        }.toString()

        val sql2 = object: SQL() {
            init {
                SELECT("id2 sourceId, block.project_id projectId, block.block_id blockId, block.type2 as sourceType, domain, mep_system_type mepSystemType, building_id buildingId")
                FROM("revit_calc.connected_block block")
                INNER_JOIN("revit.equipment eq on eq.id = block.id2")
                WHERE("block.project_id = '${projectId}'")
                AND()
                WHERE("mep_system_type in (${mepStr})")
                AND()
                WHERE("bimid in (${bimStr})")
                if(buildingId != null) {
                    AND()
                    WHERE("building_id = '${buildingId}'")
                }
            }
        }.toString()
        println(sql1)
        println(sql2)
        return "${sql1} union ${sql2}"
    } // Fun getEquipByBimId()

    fun concateStr(arr : Collection<String>) : String{
        var stringBuilder = StringBuilder()
        arr.forEach {
            stringBuilder.append("\'").append(it).append("\',")
        }
        if(stringBuilder.endsWith(',')){
            stringBuilder.deleteCharAt(stringBuilder.length - 1) //.removeSuffix(",")
        }
        return stringBuilder.toString()
    }

    /**
     * 获取模型里的设备uuid到数据中心设备的映射
     *
     * @param   projectId           项目ID
     * @param   equipIds            设备在模型里的uuid
     */
//    fun getEquipSql(projectId: String,modelId: String, ids : ArrayList<String>): String {
//
//        val sql = object: SQL() {
//            init {
//                //select eq.id equipId, deq.id revitUUID from revit.equipment eq inner join public.equipment deq on deq.bim_id = eq.bimid where eq.id in ('') and deq.project_id = ''
//
//                val list: List<String> = ArrayList()
//                for (i in ids.indices) {
//                    if (i == 0){
//                        SELECT("*")
//                        FROM("equipment e")
//                        WHERE(" project_id = '${projectId}' AND bim_location  IS NOT null  AND model_id = '${modelId}' AND is_point_in_polygon_v2_str(split_part(e.bim_location, E',', 1) , split_part(e.bim_location, E',', 2) , (SELECT outline FROM zone_ispace WHERE project_id= '${projectId}' AND bim_id = '${id}'))")
//                    }else if(i == ids.size-1 ){
//
//                    } else{
//                        Union
//                    }
//                }
//
//
//               for (id in ids){
//
//
//               }
//
//
//            }
//        }.toString()
//        return sql
//    } // Fun findObjectId()

} // Class RelationProvider