/*
 * *********************************************************************************************************************
 *
 *          !!
 *        .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.RelationType
import com.persagy.server.datacenter.models.entities.graphtype.RelationTypeProject
import com.persagy.server.datacenter.services.base.RService
import com.persagy.service.SObjectService
import com.persagy.service.SPageContext
import com.persagy.service.models.SCascadeQuery
import com.persagy.service.models.enums.SResponseType
import com.persagy.service.models.requests.SQueryRequest
import com.persagy.service.models.responses.SQueryResponse
import org.slf4j.LoggerFactory
import java.util.*
import kotlin.collections.ArrayList

/**
 * 查询总览
 *
 * @author  邓婷婷
 */
object GraphicTypeService : RService<GraphicType>(SMybatisDao(GraphicType::class.java))  {
    // 日志
    private val logger = LoggerFactory.getLogger(GraphicTypeService::class.java)
    /**  */
    val service = SObjectService(RelationTypeProject::class.java)
    /** 类型 */
    val relationTypeService = SObjectService(SMybatisDao(RelationType::class.java))
    /**
     * 查询关系总览
     */
    fun overview(): SQueryResponse<GraphicType> {
        return try {
            val projectId = SPageContext.getHeader("projectId")
            val request = SQueryRequest()
            request.pageSize = 1000
            request.orders = "sort"
            request.filters = "parentId isnull"
            request.cascade = ArrayList<SCascadeQuery>()

            val childType = SCascadeQuery()
            childType.name = "childGraphicTypeList"
            childType.cascade = ArrayList<SCascadeQuery>()
            childType.orders = "sort,graphTypeCode"
            request.cascade!!.add(childType)

//            val relationType = SCascadeQuery()
//            relationType.name = "relationTypeProjectList"
//            relationType.filters = "projectId = '$projectId'"
//            childType.cascade!!.add(relationType)

            copyRelationType(projectId!!)

            val pageQuery = GraphicTypeService.pageQuery(request)
            if (!pageQuery.content.isNullOrEmpty()){
                for ( content in pageQuery.content!!){
                    if (!content.childGraphicTypeList.isNullOrEmpty()){
                        val childGraphicTypeList = content.childGraphicTypeList
                        for (childGraphicType in childGraphicTypeList!!){
                            val relationTypeProjectList = service.select(SFilter.eq("projectId", projectId), SFilter.eq("graphicId", childGraphicType.graphTypeId!!)).order("graphicType asc,relationType asc,zoneType asc").exec()
                            if (relationTypeProjectList.size>0){
                                childGraphicType.relationTypeProjectList = relationTypeProjectList
                            }
                        }
                    }
                }
            }

            pageQuery
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, e.message!!)
        }
    }

    /**
     * 复制关系类型表
     *
     * @param   projectId       项目ID
     */
    private fun copyRelationType(projectId: String) {
        val relationTypeProjectService = SObjectService(SMybatisDao(RelationTypeProject::class.java))
        val relationTypeService = SObjectService(SMybatisDao(RelationType::class.java))
        val n = relationTypeProjectService.select(SFilter.eq("projectId", projectId)).execCount()

        if (n == 0L) {//需要录入数据
            val requests = SQueryRequest()
            val relationTypeList = relationTypeService.selectAll().exec()
            logger.debug("數據長度= ${relationTypeList.size}")
            for (relationType in relationTypeList) {
                try {
                    val relationTypeProject = RelationTypeProject()
                    relationTypeProject.id = UUID.randomUUID().toString().replace("-", "")
                    relationTypeProject.relationTypeName = relationType.relationTypeName
                    relationTypeProject.relationTypeCode = relationType.relationTypeCode
                    relationTypeProject.graphicId = relationType.graphicId
                    relationTypeProject.note = relationType.note
                    relationTypeProject.conneObject = relationType.conneObject
                    relationTypeProject.source = relationType.source
                    relationTypeProject.automatic = relationType.automatic
                    relationTypeProject.manual = relationType.manual
                    relationTypeProject.prompting = relationType.prompting
                    relationTypeProject.tableName = relationType.tableName
                    relationTypeProject.isThorough = relationType.isThorough
                    relationTypeProject.relationType = relationType.relationType;
                    relationTypeProject.zoneType = relationType.zoneType;
                    relationTypeProject.projectId = projectId
                    relationTypeProject.computationalState = 1
                    relationTypeProject.manualQuery = relationType.manualQuery
                    relationTypeProject.mainType = relationType.mainType
                    relationTypeProject.fromType = relationType.fromType
                    relationTypeProject.addRel = relationType.addRel
                    relationTypeProject.delRel = relationType.delRel
                    relationTypeProject.relManualType = relationType.relManualType
                    relationTypeProject.mainObject = relationType.mainObject
                    relationTypeProject.fromObject = relationType.fromObject
                    relationTypeProject.mepSystemType = relationType.mepSystemType
                    relationTypeProject.graphicType = relationType.graphicType
                    relationTypeProject.relTypeStatus = relationType.relTypeStatus
                    relationTypeProject.enableCalc = relationType.enableCalc
                    relationTypeProject.requestUrl = relationType.requestUrl
                    relationTypeProjectService.insert(relationTypeProject)


//                    try {
//                        val relationTypeProjectService = SObjectService(SMybatisDao(RelationTypeProject::class.java))
//                        val relationType = relationTypeProjectService.select(SFilter.eq("projectId", projectId!!),SFilter.eq("RelationType", relationAddRequest.relType!!)).entity()
//                        if (relationType!=null){
//                            relationType.computingTime = time()
//                            relationTypeProjectService.update(relationType)
//                        }
//                    } catch (e: Exception) {
//                        e.printStackTrace()
//                    }

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

    /**
     * 查询设备关系类型
     *
     * @return 返回结果对象
     */
    fun equipType(): SQueryResponse<GraphicType>{
        val sQueryResponse = SQueryResponse<GraphicType>(SResponseType.success)
        /** 查询类型 */
        val typeList = select(SFilter.inList("graphTypeName", arrayListOf("强电类", "暖通空调类", "给排水类", "消防类", "测控类"))).exec()
        /** id列表 */
        val idList = ArrayList<String>()
        /** 遍历图形 */
        for (graphicType in typeList) {
            /** 添加 id */
            idList.add(graphicType.graphTypeId!!)
        }

        /** 查询二级类型 */
        val graphicTypeList = select(SFilter.inList("parentId", idList)).exec()
        /** 遍历类型 */
        for (graphicType in graphicTypeList) {
            /** 查询三级类型 */
            graphicType.relationTypeList = relationTypeService.select(SFilter.eq("graphicId",graphicType.graphTypeId!!)).exec()
        }

        /** 二级数量 */
        sQueryResponse.total = graphicTypeList.size.toLong()
        /** 关系列表 */
        sQueryResponse.content = graphicTypeList
        /** 返回结果对象 */
        return sQueryResponse
    }

}