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

import com.persagy.database.SFilter
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.Opt
import com.persagy.server.dao.mappers.CustomSql
import com.persagy.server.dao.mappers.wanda.PersonnalisationSql
import com.persagy.server.datacenter.datacenter.models.entities.dictnew.DefClass
import com.persagy.server.datacenter.datacenter.models.entities.dictnew.DictMajor
import com.persagy.server.datacenter.models.entities.dictnew.DefFuncId
import com.persagy.server.datacenter.wanda.dict.DictInfosWanDa
import com.persagy.server.datacenter.wanda.dict.DictStage
import com.persagy.server.datacenter.wanda.response.DictInfoResponse
import com.persagy.service.SObjectService
import com.persagy.service.models.enums.SResponseType
import com.persagy.service.models.responses.SQueryResponse
import com.persagy.service.utils.SSpringContextUtil
import org.slf4j.LoggerFactory

/**
 * 字典服务
 *
 * @author wx  <zhangweixin@sagacloud.com>
 * @date  2020/11/17 17:28
 */
object DefFuncIdService: SObjectService<DefFuncId>(SMybatisDao(DefFuncId::class.java)) {
    // 日志
    private val logger = LoggerFactory.getLogger(DefFuncIdService::class.java)
    /** 平台集团对象类型 */
    private val defClassService = SObjectService(SMybatisDao(DefClass::class.java))
    /** 对照表 */
    private val dictInfosWanDaService = SObjectService(SMybatisDao(DictInfosWanDa::class.java))
    /** 阶段 */
    private val dictStageService = SObjectService(SMybatisDao(DictStage::class.java))
    /** 专业 */
    private val dictMajorService = SObjectService(SMybatisDao(DictMajor::class.java))

    /** 自定义查询 */
    private val personnalisationSql by lazy {
        SSpringContextUtil.getBean(PersonnalisationSql::class.java) as PersonnalisationSql
    }

    /**
     * 查询设备类型
     */
    fun dictTypeEquipQuery(): SQueryResponse<DefClass>{
        return try {
            val sQueryResponse = SQueryResponse<DefClass>(SResponseType.success)
            val dictInfosWanDaGroupList = dictInfosWanDaService.select(SFilter.eq("groupCode", Opt.groupCode!!), SFilter.eq("projectId", "0")).exec()
            val dictInfosWanDaProjectList = dictInfosWanDaService.select(SFilter.eq("groupCode", Opt.groupCode!!), SFilter.eq("projectId", Opt.projectId!!)).exec()
            val setCode = HashSet<String>()
            for (dictInfosWanDaGroup in dictInfosWanDaGroupList){
                setCode.add(dictInfosWanDaGroup.classCode!!)
            }
            if (dictInfosWanDaProjectList.size>0){
                for (dictInfosWanDaProject in dictInfosWanDaProjectList){
                    setCode.add(dictInfosWanDaProject.classCode!!)
                }
            }
            var defClassList = defClassService.select(SFilter.eq("projectId", Opt.projectId!!), SFilter.inList("code", setCode.toList())).order("code").exec()
            if (defClassList.size == 0){
                defClassList = defClassService.select(SFilter.eq("type","group"), SFilter.eq("groupCode",Opt.groupCode!!),SFilter.inList("code", setCode.toList())).order("code").exec()
                if (defClassList.size == 0){
                    defClassList = defClassService.select(SFilter.eq("type", "common"), SFilter.inList("code", setCode.toList())).order("code").exec()
                }
            }
            sQueryResponse.content = defClassList
            sQueryResponse.total = defClassList.size.toLong()
            sQueryResponse
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure)
        }

    }

    /**
     * 类型下信息点查询
     *
     * @param category    分类
     */
    fun dictEquipInfoQuery(category: String): DictInfoResponse {
        val dictInfoResponse = DictInfoResponse()
        try {//        val dictInfosWanDaGroupList = dictInfosWanDaService.select(SFilter.eq("groupCode", Opt.groupCode!!), SFilter.eq("projectId", "0")
//                ,SFilter.eq("classCode", category)).exec()
//        val dictInfosWanDaProjectList = dictInfosWanDaService.select(SFilter.eq("groupCode", Opt.groupCode!!), SFilter.eq("projectId", Opt.projectId!!)
//                ,SFilter.eq("classCode", category)).exec()
            var defFuncId = DefFuncIdService.select(SFilter.eq("projectId", Opt.projectId!!),
                    SFilter.eq("classCode", category),
                    SFilter.inList("code", arrayListOf("bimTypeId"))).entity()

            var defFuncIdName = DefFuncIdService.select(SFilter.eq("projectId", Opt.projectId!!),
                    SFilter.eq("classCode", category),
                    SFilter.inList("code", arrayListOf("name"))).entity()

            var defFuncIdList = DefFuncIdService.select(SFilter.eq("projectId", Opt.projectId!!),
                    SFilter.eq("classCode", category),
                    SFilter.inList("code", arrayListOf("localName","localId"))).exec()
            defFuncIdList.add(0,defFuncId!!)

            defFuncIdName!!.code = "systemCategory"
            defFuncIdName.name = "系统分类"
            defFuncIdName.aliasCode = "systemCategory"
            defFuncIdName.aliasName = "系统分类"

            defFuncIdList.add(1,defFuncIdName!!)
//            if (defFuncIdList.size == 0 ) {
//                defFuncIdList = DefFuncIdService.select(SFilter.eq("type","group"),
//                        SFilter.inList("code", arrayListOf("bimTypeId","name","localName","localId"))).exec()
//                if (defFuncIdList.size == 0) {
//                    defFuncIdList = DefFuncIdService.select(SFilter.eq("type","common"),
//                            SFilter.inList("code", arrayListOf("bimTypeId","name","localName","localId"))).exec()
//                }
//            }
            for (defFuncId in defFuncIdList) {
                if (defFuncId.code == "name"){
                    defFuncId.code = "systemCategory"
                    defFuncId.name = "系统分类"
                    defFuncId.aliasCode = "systemCategory"
                    defFuncId.aliasName = "系统分类"
                } else if (defFuncId.code == "localName"){
                    defFuncId.code = "codeName"
                    defFuncId.name = "设备类型名称"
                    defFuncId.aliasCode = "codeName"
                    defFuncId.aliasName = "设备类型名称"
                }
            }

            val dictStageList = dictStageService.selectAll().exec()
            for (dictStage in dictStageList) {
                val dictInfosWanDaGroupList = dictInfosWanDaService.select(SFilter.eq("groupCode", Opt.groupCode!!), SFilter.eq("projectId", "0")
                        ,SFilter.eq("classCode", category),SFilter.eq("stage", dictStage.code!!)).exec()
                val dictInfosWanDaProjectList = dictInfosWanDaService.select(SFilter.eq("groupCode", Opt.groupCode!!), SFilter.eq("projectId", Opt.projectId!!)
                        ,SFilter.eq("classCode", category),SFilter.eq("stage", dictStage.code!!)).exec()
                if (dictInfosWanDaProjectList.size>0){
                    dictInfosWanDaGroupList.addAll(dictInfosWanDaProjectList)
                }
                var setCode = HashSet<String>()
                for (dictInfosWanDaGroup in dictInfosWanDaGroupList){
                    setCode.add(dictInfosWanDaGroup.code!!)
                }
                if (setCode.isNotEmpty()) {
                    var funcIdList = DefFuncIdService.select(SFilter.eq("projectId", Opt.projectId!!),SFilter.eq("classCode", category),
                        SFilter.inList("code", setCode.toList())).order("code").exec()
                    dictStage.infos = funcIdList
                }else {
                    dictStage.infos = ArrayList()
                }

//                if (funcIdList.size == 0 ) {
//                    funcIdList = DefFuncIdService.select(SFilter.eq("type","group"),
//                             SFilter.eq("groupCode",Opt.groupCode!!),SFilter.eq("classCode", category),
//                            SFilter.inList("code", setCode.toList())).order("code").exec()
//                    if (funcIdList.size == 0) {
//                        funcIdList = DefFuncIdService.select(SFilter.eq("type","common"),SFilter.eq("classCode", category),
//                                SFilter.inList("code",  setCode.toList())).order("code").exec()
//                    }
//                }

            }
            dictInfoResponse.basicInfos = defFuncIdList
            dictInfoResponse.dictStages = dictStageList
            dictInfoResponse.result = SResponseType.success
            return dictInfoResponse
        } catch (e: Exception) {
            e.printStackTrace()
            dictInfoResponse.result = SResponseType.failure
            dictInfoResponse.message = "错误"
        }
        return dictInfoResponse
    }

    /**
     * 项目下已有的设备类型
     */
    fun dictProjectTypeEquipQuery(): SQueryResponse<DictMajor>{
        return try {
            val sQueryResponse = SQueryResponse<DictMajor>(SResponseType.success)
            val equipTypeProjectList = personnalisationSql.equipTypeProject(Opt.projectId!!)
            if (equipTypeProjectList.size>0) {
                val equipTypeList = ArrayList<String>()
                for (equipTypeProject in equipTypeProjectList){
                    equipTypeList.add(equipTypeProject.classCode!!)
                }
//                val dictInfosWanDaGroupList = dictInfosWanDaService.select(SFilter.eq("groupCode", Opt.groupCode!!), SFilter.eq("projectId", "0"),SFilter.inList("classCode", equipTypeList)).exec()
//                val dictInfosWanDaProjectList = dictInfosWanDaService.select(SFilter.eq("groupCode", Opt.groupCode!!), SFilter.eq("projectId", Opt.projectId!!),SFilter.inList("classCode", equipTypeList)).exec()
//                val setCode = HashSet<String>()
//                for (dictInfosWanDaGroup in dictInfosWanDaGroupList){
//                    setCode.add(dictInfosWanDaGroup.classCode!!)
//                }
//                if (dictInfosWanDaProjectList.size>0){
//                    for (dictInfosWanDaProject in dictInfosWanDaProjectList){
//                        setCode.add(dictInfosWanDaProject.classCode!!)
//                    }
//                }
                var defClassList = defClassService.select(SFilter.eq("projectId", Opt.projectId!!), SFilter.inList("code", equipTypeList)).order("code").exec()
                if (defClassList.size == 0){
                    defClassList = defClassService.select(SFilter.eq("type","group"), SFilter.eq("groupCode",Opt.groupCode!!),SFilter.inList("code", equipTypeList)).order("code").exec()
                    if (defClassList.size == 0){
                        defClassList = defClassService.select(SFilter.eq("type", "common"), SFilter.inList("code", equipTypeList)).order("code").exec()
                    }
                }
               if (defClassList.size>0){
                   val typeset = HashSet<String>()
                   val majorSet = HashSet<String>()
                   for (defClass in defClassList) {
                       typeset.add(defClass.systemCode!!)
                       majorSet.add(defClass.majorCode!!)
                   }

                   var systemDefClassList = defClassService.select(SFilter.eq("projectId", Opt.projectId!!), SFilter.inList("code", typeset.toList())).order("code").exec()
                   val defMajors = dictMajorService.select(SFilter.inList("code",majorSet.toList())).order("id").exec()

                   if (systemDefClassList.size>0) {

                       for (systemDefClass in systemDefClassList) {
                           for (defClass in defClassList) {
                               if (defClass.systemCode == systemDefClass.code) {
                                   if (systemDefClass.children.isNullOrEmpty()) {
                                       systemDefClass.children = ArrayList<DefClass>()
                                   }
                                   systemDefClass.children!!.add(defClass)
                               }
                           }

                       }

                       for (defMajor in defMajors) {
                           for (systemDefClass in systemDefClassList) {
                               if(defMajor.code == systemDefClass.majorCode){
                                   if (defMajor.children.isNullOrEmpty()) {
                                       defMajor.children = ArrayList<DefClass>()
                                   }
                                   defMajor.children!!.add(systemDefClass)
                               }
                           }
                       }
                   }
                   sQueryResponse.content = defMajors
                   sQueryResponse.total = defMajors.size.toLong()
                   sQueryResponse
               }
                sQueryResponse
            }else {
                sQueryResponse.result = SResponseType.success
                sQueryResponse.message = "项目下没有设备"
                sQueryResponse
            }

        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure)
        }
    }

    /**
     * 项目下已有的系统
     */
    fun dictProjectTypeSystemQuery(): SQueryResponse<DefClass>{
        return try {
            val sQueryResponse = SQueryResponse<DefClass>(SResponseType.success)
            val systemTypeProjectList = personnalisationSql.systemTypeProject(Opt.projectId!!)
            if (systemTypeProjectList.size>0) {

                val systemTypeList = ArrayList<String>()
                for (systemType in systemTypeProjectList){
                    systemTypeList.add(systemType.classCode!!)
                }
                /** 系统 */
                var systemDefClassList = defClassService.select(SFilter.eq("projectId", Opt.projectId!!), SFilter.inList("code", systemTypeList)).order("code").exec()
                if (systemDefClassList.size == 0){
                    systemDefClassList = defClassService.select(SFilter.eq("type","group"), SFilter.eq("groupCode",Opt.groupCode!!),SFilter.inList("code", systemTypeList)).order("code").exec()
                    if (systemDefClassList.size == 0){
                        systemDefClassList = defClassService.select(SFilter.eq("type", "common"), SFilter.inList("code", systemTypeList)).order("code").exec()
                    }
                }
                val typeset = HashSet<String>()
                for (systemDefClass in systemDefClassList) {
                    typeset.add(systemDefClass.majorCode!!)
                }
                val dictMajorList = dictMajorService.select(SFilter.inList("code", typeset.toList())).order("code").exec()
                val listMajor = ArrayList<DefClass>()
                for (dictMajor in dictMajorList) {
                    val defClass = DefClass()
                    defClass.code = dictMajor.code
                    defClass.name = dictMajor.name
                    defClass.aliasCode = dictMajor.aliasCode
                    defClass.aliasName = dictMajor.aliasName

                    for (systemDefClass in  systemDefClassList) {
                        if (systemDefClass.majorCode == dictMajor.code) {
                            if (defClass.children.isNullOrEmpty()) {
                                defClass.children = ArrayList<DefClass>()
                            }
                            defClass.children!!.add(systemDefClass)
                        }
                    }
                    listMajor.add(defClass)
                }

                sQueryResponse.content = listMajor
                sQueryResponse.total = listMajor.size.toLong()
                sQueryResponse
            } else {
                sQueryResponse.result = SResponseType.success
                sQueryResponse.message = "项目下没有系统"
                sQueryResponse
            }
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure)
        }


    }


    /**
     * 所有的系统
     */
    fun dictTypeSystemQuery(): SQueryResponse<DefClass>{
        return try {
            val sQueryResponse = SQueryResponse<DefClass>(SResponseType.success)

            /** 系统 */
            var systemDefClassList = defClassService.select(SFilter.eq("projectId", Opt.projectId!!), SFilter.eq("parentCode","system")).order("code").exec()
            if (systemDefClassList.size == 0){
                systemDefClassList = defClassService.select(SFilter.eq("type","group"), SFilter.eq("groupCode",Opt.groupCode!!),SFilter.eq("parentCode","system")).order("code").exec()
                if (systemDefClassList.size == 0){
                    systemDefClassList = defClassService.select(SFilter.eq("type", "common"),SFilter.eq("parentCode","system")).order("code").exec()
                }
            }
            val typeset = HashSet<String>()
            for (systemDefClass in systemDefClassList) {
                typeset.add(systemDefClass.majorCode!!)
            }
            val dictMajorList = dictMajorService.select(SFilter.inList("code", typeset.toList())).order("code").exec()
            val listMajor = ArrayList<DefClass>()
            for (dictMajor in dictMajorList) {
                val defClass = DefClass()
                defClass.code = dictMajor.code
                defClass.name = dictMajor.name
                defClass.aliasCode = dictMajor.aliasCode
                defClass.aliasName = dictMajor.aliasName

                for (systemDefClass in  systemDefClassList) {
                    if (systemDefClass.majorCode == dictMajor.code) {
                        if (defClass.children.isNullOrEmpty()) {
                            defClass.children = ArrayList<DefClass>()
                        }
                        defClass.children!!.add(systemDefClass)
                    }
                }
                listMajor.add(defClass)
            }

            sQueryResponse.content = listMajor
            sQueryResponse.total = listMajor.size.toLong()
            sQueryResponse
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure)
        }
    }



}