package com.persagy.labsl.services.planar

import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.persagy.base.extensions.toJson
import com.persagy.database.SFilter
import com.persagy.labsl.Opts
import com.persagy.labsl.models.entities.pbs.*
import com.persagy.labsl.models.response.SCommonResponse
import com.persagy.labsl.services.DmpBaseService
import com.persagy.labsl.utils.AdmEntityTransferUtil
import com.persagy.labsl.utils.IdUtils
import com.persagy.mybatis.SMybatisDao
import com.persagy.service.SObjectService
import com.persagy.service.models.enums.SResponseType
import com.persagy.service.models.requests.SQueryRequest
import com.persagy.service.models.requests.SUpdateRequest
import com.persagy.service.models.responses.SBaseResponse
import com.persagy.service.models.responses.SCreateResponse
import com.persagy.service.models.responses.SQueryResponse
import org.apache.poi.ss.formula.functions.T
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import java.text.SimpleDateFormat
import java.util.*

/**
 * 图服务
 *
 * @author wx  <zhangweixin@sagacloud.com>
 */
object PlanarGraphService : SObjectService<PlanarGraph>(SMybatisDao(PlanarGraph::class.java)) {

    /** 日志 */
    private val logger = LoggerFactory.getLogger(PlanarGraphService::class.java)
    /** 对象信息 */
    private val objExtInfoService = SObjectService(SMybatisDao(ObjExtInfo::class.java))
    /** 文本注释，图上的图片说明 */
    private val planarMarkersService = SObjectService(SMybatisDao(PlanarMarkers::class.java))
    /** 管线对象 */
    private val planarRelationService = SObjectService(SMybatisDao(PlanarRelation::class.java))
    /** 规则 */
    private val planarQbsRuleService = SObjectService(SMybatisDao(PlanarQbsRule::class.java))


    /** 发布的图例节点服务 */
    private val objExtInfoPubService = SObjectService(SMybatisDao(ObjExtInfoPub::class.java))
    /** 注释、说明已发布 */
    private val planarMarkersPubService = SObjectService(SMybatisDao(PlanarMarkersPub::class.java))
    /** 管线对象已发布 */
    private val planarRelationPubService = SObjectService(SMybatisDao(PlanarRelationPub::class.java))
    /** 规则已发布 */
    private val planarQbsRulePubService = SObjectService(SMybatisDao(PlanarQbsRulePub::class.java))
    /** 已发布 */
     val planarGraphPubService = SObjectService(SMybatisDao(PlanarGraphPub::class.java))
    /** 建筑 */
    val buildingService = SObjectService(SMybatisDao(Building::class.java))
    /** 楼层 */
    val floorService = SObjectService(SMybatisDao(Floor::class.java))

    @Autowired
    private val dmpBaseService: DmpBaseService? = DmpBaseService()

    /**
     * 创建图形
     *
     * @param entity    对象
     * @return 返回对象列表
     */
    fun create(entity: PlanarGraph): SCreateResponse<PlanarGraph>{
        val sCreateResponse = SCreateResponse<PlanarGraph>()
        /** id 赋值 */
        if (entity.id.isNullOrEmpty()){
            entity.id = IdUtils.uuidCreate()
        }

        /** 图 id */
        if (entity.graphId.isNullOrEmpty()){
            entity.graphId = IdUtils.uuidCreate()
        }

        /** 版本 */
        if (entity.version.isNullOrEmpty()) {
            entity.version = "1.0.1"
        }

        /** 项目 id */
        if (entity.projectId.isNullOrEmpty()){
            entity.projectId = Opts.projectId
        }
        entity.state = "Draft"

        val entity1 = select(
            SFilter.eq("projectId", Opts.projectId!!),
            SFilter.eq("floorId", entity.floorId!!),
            SFilter.eq("name", entity.name!!)
        ).entity()
        if (entity1!=null) {
            sCreateResponse.result = SResponseType.failure
            sCreateResponse.message = "图名称已存在"
            return sCreateResponse
        }
        val entity2 = planarGraphPubService.select(
            SFilter.eq("projectId", Opts.projectId!!),
            SFilter.eq("floorId", entity.floorId!!),
            SFilter.eq("name", entity.name!!)
        ).entity()
        if (entity2!=null) {
            sCreateResponse.result = SResponseType.failure
            sCreateResponse.message = "图名称已存在"
            return sCreateResponse
        }

        if (!entity.folderName.isNullOrEmpty()) {

            val execList = QbsFolderService.select(SFilter.eq("projectId", Opts.projectId!!),SFilter.eq("name", entity.folderName!!)).exec()
            if (execList.size>0){
                sCreateResponse.result = SResponseType.failure
                sCreateResponse.message ="文件夹名称已存在"
                return sCreateResponse
            }

            val qbsFolder = QbsFolder()
            qbsFolder.id = IdUtils.uuidCreate()
            entity.folderId = qbsFolder.id
            qbsFolder.name = entity.folderName
            qbsFolder.projectId = Opts.projectId
            QbsFolderService.insert(qbsFolder)
            insert(entity)
            sCreateResponse.entityList = ArrayList()
            sCreateResponse.entityList!!.add(entity)
            sCreateResponse.result = SResponseType.success
        } else {
            insert(entity)
            sCreateResponse.entityList = ArrayList()
            sCreateResponse.entityList!!.add(entity)
            sCreateResponse.result = SResponseType.success
        }
        return  sCreateResponse
    }

    /**
     * 创建之前回调
     *
     * @param entity    图例对象
     */
    override fun onCreateBefore(entity: PlanarGraph): Boolean {
        /** id 赋值 */
        if (entity.id.isNullOrEmpty()){
            entity.id = IdUtils.uuidCreate()
        }

        /** 图 id */
        if (entity.graphId.isNullOrEmpty()){
            entity.graphId = IdUtils.uuidCreate()
        }

        /** 版本 */
        if (entity.version.isNullOrEmpty())
            entity.version = "2.0.1"

        /** 项目 id */
        if (entity.projectId.isNullOrEmpty()){
            entity.projectId = Opts.projectId
        }
        return super.onCreateBefore(entity)
    }

    /**
     * 创建图
     *
     * @param graph   图对象
     * @return 图形对象列表
     */
    fun save(graph: PlanarGraph): SCreateResponse<PlanarGraph> {
        val sCreateResponse = SCreateResponse<PlanarGraph>()
        /** 开启事务 */
        openTransaction()
        /** 未发布 */
        if (graph.id.isNullOrEmpty()) {
            /** id赋值 */
            graph.id = UUID.randomUUID().toString().replace("-", "")
        }

        /** 图 id 为空赋值*/
        if (graph.graphId.isNullOrEmpty()){
            graph.graphId = UUID.randomUUID().toString().replace("-", "")
        }

        /** 项目 id 赋值 */
        graph.projectId = Opts.projectId!!
        /** 清除以前的版本 */
        delOldData(graph)
        /** 版本号 */
        if (graph.version.isNullOrEmpty()) {
            graph.version = "1.0.1"
        } else {
            val listVersion = graph.version!!.split(".")
            val num = listVersion[2].toInt() + 1
            graph.version = listVersion[0] + "." + listVersion[1] + "." + num
        }
        /** 图标记设置为 Draft 草稿箱 */
        graph.state = "Draft"
        /** 插入图形数据 */
        val insertGraph = insert(graph)
        /** 插入是否成功 */
        if (!insertGraph) {
            /** 事务回滚 */
            backTransaction()
            /** 返回标记 */
            sCreateResponse.result = SResponseType.failure
            /** 返回对象 */
            return  sCreateResponse
        }

        /** 列表不能为空 */
        if (graph.elements != null) {
            val nodesList = graph.elements!!.objExtInfo
            /** 列表不能为空 */
            if (!nodesList.isNullOrEmpty()) {
                /** 遍历列表 */
                for (nodes in nodesList) {
                    /**  图 id 赋值给子节点*/
                    nodes.graphId = graph.graphId
                    /** 图形 id */
                    nodes.id = graph.id
                    /** 子节点 id */
                    if (nodes.ObjExtInfoId.isNullOrEmpty()) {
                        /** id 赋值 */
                        nodes.ObjExtInfoId = UUID.randomUUID().toString().replace("-", "")
                    }

                    /** 插入数据 */
                    val insertNode = objExtInfoService.insert(nodes)
                    /** 插入是否成功 */
                    if (!insertNode) {
                        /** 事务回滚 */
                        backTransaction()
                        /** 返回标记 */
                        sCreateResponse.result = SResponseType.failure
                        /** 返回对象 */
                        return  sCreateResponse
                    }
                }
            }

            val markersList = graph.elements!!.markers
            /** 列表不为空 */
            if (!markersList.isNullOrEmpty()) {
                /** 遍历列表 */
                for (markers in markersList) {
                    /** 图 id */
                    markers.graphId = graph.graphId
                    /** 标识 id */
                    markers.id = graph.id
                    /** id 为空赋值 */
                    if (markers.markerId.isNullOrEmpty()) {
                        /** id赋值 */
                        markers.markerId = UUID.randomUUID().toString().replace("-", "")
                    }
                    /** 插入数据 */
                    val insertMarkers = planarMarkersService.insert(markers)
                    /** 数据是否插入成功 */
                    if (!insertMarkers) {
                        /** 事务回滚 */
                        backTransaction()
                        /** 返回标志 */
                        sCreateResponse.result = SResponseType.failure
                        /** 返回对象 */
                        return  sCreateResponse
                    }
                }
            }

            val relationsList = graph.elements!!.relations
            /** 列表不为空 */
            if (!relationsList.isNullOrEmpty()) {
                /** 遍历列表 */
                for (relations in relationsList) {
                    /** 图 id */
                    relations.graphId = graph.graphId
                    /** 草稿箱标志 */
                    relations.state = 1
                    /** 图编码 */
                    relations.id = graph.id
                    /** 管线 id 为空 赋值 */
                    if (relations.relationId.isNullOrEmpty()) {
                        /** id 赋值 */
                        relations.relationId = UUID.randomUUID().toString().replace("-", "")
                    }

                    /** 插入数据 */
                    val insertRelation = planarRelationService.insert(relations)
                    /** 插入是否成功 */
                    if (!insertRelation) {
                        /** 事务回滚 */
                        backTransaction()
                        /** 返回标志 */
                        sCreateResponse.result = SResponseType.failure
                        /** 返回对象 */
                        return  sCreateResponse
                    }
                }
            }
            /** 规则列表 */
            if (!graph.ruleList.isNullOrEmpty()) {
                for (rule in graph.ruleList!!) {
                    rule.graphCoding = graph.id
                    rule.graphId = graph.graphId
//                    if (rule.id.isNullOrEmpty()) {
//                        rule.id =  UUID.randomUUID().toString().replace("-", "")
//                    }
                    val insert = planarQbsRuleService.insert(rule)
                    if (!insert) {
                        /** 事务回滚 */
                        backTransaction()
                        /** 返回标志 */
                        sCreateResponse.result = SResponseType.failure
                        /** 返回对象 */
                        return  sCreateResponse
                    }
                }


            }


        }

        /** 提交事务 */
        commitTransaction()
        /** 返回标志 */
        sCreateResponse.result = SResponseType.success
        /** 返回对象列表 */
        sCreateResponse.entityList = arrayListOf(graph)
        /** 返回对象 */
        return sCreateResponse
    }

    /**
     * 发布图形 回收站和草稿箱在一个表中，导致同一个图会有多个在回收站中需要配备多主键
     *
     * @param graphPub  待发布的图对象
     * @return 已发布的图对象列表
     */
    fun pubDrawings(graphPub: PlanarGraphPub): SCreateResponse<PlanarGraphPub> {
        return try {
            /** 返回对象 */
            val sCreateResponse = SCreateResponse<PlanarGraphPub>()
            /** 图对象 */
            val graph1 = PlanarGraph()
            /** 项目 id */
            graph1.projectId = Opts.projectId!!
            /** 图编码 */
            graph1.id = graphPub.id
            /** 图 id */
            graph1.graphId = graphPub.graphId
            /** 查询草稿箱 */
            val squeryBuilder = planarGraphPubService.select(
                SFilter.eq("projectId", Opts.projectId!!),
                SFilter.eq("id", graphPub.id!!),
                SFilter.eq("graphId", graphPub.graphId!!),
                SFilter.eq("state", "Draft")
            )
            /** 设置表明，查询 */
            val graph = squeryBuilder.table("qibaishi_gallery.qbs_graph").entity()
            /** 对象不为空 */
            if (graph!=null){
                /** 开启事务 */
                openTransaction()
                /** 清除已发布的老数据 */
                delOldDataPub(graph1)
                /** 版本号 */
                val listVersion = graph.version!!.split(".")
                /** 版本号加 1 */
                val num = listVersion[1].toInt() + 1
                /** 版本号赋值 */
                graph.version = listVersion[0] + "." + num + "." + 0
                /** 已发布标志 Publish */
                graph.state = "Publish"
                /** 插入数据 */
                val insert = planarGraphPubService.insert(graph)
                /** 插入数据是否成功 */
                if (!insert) {
                    /** 回滚 */
                    backTransaction()
                    /** 返回标志 */
                    sCreateResponse.result = SResponseType.failure
                    /** 返回对象 */
                    return  sCreateResponse
                }

                /** 子节点 */
                val nodebuilder = objExtInfoPubService.select(
                    SFilter.eq("graphId", graph.graphId!!),
                    SFilter.eq("id", graphPub.id!!)
                )
                /** 设置表明，查询 */
                val nodePubList = nodebuilder.table("qibaishi_gallery.qbs_obj_ext_info").exec()
                /** 列表长度大于 0 */
                if (nodePubList.size>0){
                    /** 遍历列表 */
                    for (nodePub in nodePubList){
                        /** 图编码 */
                        nodePub.id = graph.id
                        /** 图 id */
                        nodePub.graphId = graph.graphId
                        /** 插入数据 */
                        val insert1 = objExtInfoPubService.insert(nodePub)
                        /** 插入是否成功 */
                        if (!insert1){
                            /** 回滚 */
                            backTransaction()
                            /** 返回标志 */
                            sCreateResponse.result = SResponseType.failure
                            /** 返回对象 */
                            return  sCreateResponse
                        }
                    }
                    if (graph.elements == null) {
                        graph.elements = PlanarElementsPub()
                    } else {
                        graph.elements!!.objExtInfo = nodePubList
                    }
                }

                /** 查询 */
                val markersbuilder = planarMarkersPubService.select(
                    SFilter.eq("graphId", graph.graphId!!),
                    SFilter.eq("id", graphPub.id!!)
                )
                /** 设置表明，查询 */
                val markersPubList = markersbuilder.table("qibaishi_gallery.qbs_marker").exec()
                /** 列表大于 0 */
                if (markersPubList.size>0){
                    /** 遍历列表 */
                    for (markersPub in markersPubList){
                        /** 图编码 */
                        markersPub.id = graph.id
                        /** 图 id */
                        markersPub.graphId = graph.graphId
                        /** 插图数据 */
                        val insert1 = planarMarkersPubService.insert(markersPub)
                        /** 插入是否成功 */
                        if (!insert1){
                            /** 回滚 */
                            backTransaction()
                            /** 返回标志 */
                            sCreateResponse.result = SResponseType.failure
                            /** 返回对象 */
                            return  sCreateResponse
                        }
                    }
                    if (graph.elements == null) {
                        graph.elements = PlanarElementsPub()
                    } else {
                        graph.elements!!.markers = markersPubList
                    }
                }

                /** 查询 */
                val relationBuilder = planarRelationPubService.select(
                    SFilter.eq("graphId", graph.graphId!!),
                    SFilter.eq("id", graphPub.id!!)
                )
                /** 设置表明，查询 */
                val relationList = relationBuilder.table("qibaishi_gallery.qbs_relation").exec()
                /** 列表长度大于 0 */
                if (relationList.size>0){
                    /** 遍历列表 */
                    for (relation in relationList){
                        /** 图编码  */
                        relation.id = graph.id
                        /** 图 id */
                        relation.graphId = graph.graphId
                        /** 已发布标志 */
                        relation.state = 0
                        /** 插入数据 */
                        val insert1 = planarRelationPubService.insert(relation)
                        /** 插入是否成功 */
                        if (!insert1){
                            /** 回滚 */
                            backTransaction()
                            /** 返回标志 */
                            sCreateResponse.result = SResponseType.failure
                            /** 返回对象 */
                            return  sCreateResponse
                        }
                    }
                    if (graph.elements == null) {
                        graph.elements = PlanarElementsPub()
                    } else {
                        graph.elements!!.relations = relationList
                    }

                }

                /** 规则 */
                val planarQbsRuleBuilder = planarQbsRulePubService.select(
                    SFilter.eq("graphId", graph.graphId!!),
                    SFilter.eq("graphCoding", graphPub.id!!)
                )
                /** 设置表明，查询 */
                val planarQbsRuleList = planarQbsRuleBuilder.table("qibaishi_gallery.qbs_rule").exec()
                /** 列表长度大于 0 */
                if (planarQbsRuleList.size>0){
                    /** 遍历列表 */
                    for (relation in planarQbsRuleList){
                        /** 图编码  */
                        relation.graphCoding = graph.id
                        /** 图 id */
                        relation.graphId = graph.graphId
                        /** 插入数据 */
                        val insert1 = planarQbsRulePubService.insert(relation)
                        /** 插入是否成功 */
                        if (!insert1){
                            /** 回滚 */
                            backTransaction()
                            /** 返回标志 */
                            sCreateResponse.result = SResponseType.failure
                            /** 返回对象 */
                            return  sCreateResponse
                        }
                    }
                    graph.ruleList = planarQbsRuleList
                }

                /** 清除草稿箱图 */
                delOldData(graph1)
                /** 提交事务 */
                commitTransaction()
                /** 对象列表 */
                sCreateResponse.entityList = arrayListOf(graph)
                /** 返回标志 */
                sCreateResponse.result = SResponseType.success
            }else{
                /** 返回标志 */
                sCreateResponse.result = SResponseType.failure
                sCreateResponse.message = "草稿箱中没有待发布图形"
            }

            /** 返回对象 */
            return sCreateResponse
        } catch (e: Exception) {
            e.printStackTrace()
            SCreateResponse(SResponseType.failure,e.message!!)
        }
    }


    fun draftsUpdate(request: SUpdateRequest<PlanarGraph>): SBaseResponse {
        val sBaseResponse = SBaseResponse(SResponseType.success)
        if (!request.content.isNullOrEmpty()) {
            for (content in request.content!!) {
                val entity1 = select(
                    SFilter.eq("projectId", Opts.projectId!!),
                    SFilter.eq("floorId", content.floorId!!),
                    SFilter.eq("name", content.name!!),
                    SFilter.not(SFilter.eq("graphId",content.graphId!!))
                ).entity()
                if (entity1!=null) {
                    sBaseResponse.result = SResponseType.failure
                    sBaseResponse.message = "图名称已存在"
                    return sBaseResponse
                }
                val entity2 = planarGraphPubService.select(
                    SFilter.eq("projectId", Opts.projectId!!),
                    SFilter.eq("floorId", content.floorId!!),
                    SFilter.eq("name", content.name!!),
                    SFilter.not(SFilter.eq("graphId",content.graphId!!))
                ).entity()
                if (entity2!=null) {
                    sBaseResponse.result = SResponseType.failure
                    sBaseResponse.message = "图名称已存在"
                    return sBaseResponse
                }

                update(content)
            }
        }

        return  sBaseResponse
    }

    fun pubUpdate(request: SUpdateRequest<PlanarGraphPub>): SBaseResponse {
        val sBaseResponse = SBaseResponse(SResponseType.success)
        if (!request.content.isNullOrEmpty()) {
            for (content in request.content!!) {
                val entity1 = select(
                    SFilter.eq("projectId", Opts.projectId!!),
                    SFilter.eq("floorId", content.floorId!!),
                    SFilter.eq("name", content.name!!),
                    SFilter.not(SFilter.eq("graphId",content.graphId!!))
                ).entity()
                if (entity1!=null) {
                    sBaseResponse.result = SResponseType.failure
                    sBaseResponse.message = "图名称已存在"
                    return sBaseResponse
                }
                val entity2 = planarGraphPubService.select(
                    SFilter.eq("projectId", Opts.projectId!!),
                    SFilter.eq("floorId", content.floorId!!),
                    SFilter.eq("name", content.name!!),
                    SFilter.not(SFilter.eq("graphId",content.graphId!!))
                ).entity()
                if (entity2!=null) {
                    sBaseResponse.result = SResponseType.failure
                    sBaseResponse.message = "图名称已存在"
                    return sBaseResponse
                }
                planarGraphPubService.update(content)
            }
        }

        return  sBaseResponse
    }


    /**
     * 清除草稿箱以前数据
     *
     * @param  graph   图对象
     */
    private fun delOldData(graph: PlanarGraph) {
        logger.debug("保存图形：${graph.toJson()}")
        /** 清除以前的版本 */
        val entity = select(
            SFilter.eq("projectId", graph.projectId!!),
            SFilter.eq("id", graph.id!!),
            SFilter.eq("graphId", graph.graphId!!)
        ).entity()

        if (entity != null) {
            /** 清除之前的草稿记录 */
            val delete = delete(
                SFilter.eq("projectId", graph.projectId!!),
                SFilter.eq("id", graph.id!!),
                SFilter.eq("graphId", graph.graphId!!)
            )
            if (delete){
                /** 清除图下子集 */
                objExtInfoService.delete(
                    SFilter.eq("id", graph.id!!),
                    SFilter.eq("graphId", graph.graphId!!))
                planarMarkersService.delete(
                    SFilter.eq("id", graph.id!!),
                    SFilter.eq("graphId", graph.graphId!!))
                planarRelationService.delete(
                    SFilter.eq("id", graph.id!!),
                    SFilter.eq("graphId", graph.graphId!!))
                planarQbsRuleService.delete(SFilter.eq("graphCoding", graph.id!!),
                    SFilter.eq("graphId", graph.graphId!!))
            }
        }
    }

    /**
     * 草稿箱 - 清除草稿箱正在使用的草稿
     *
     * @param graph  图对象
     */
    private fun delOldDataTwo(graph: PlanarGraph) {
        /** 清除以前的版本 */
        val entity = select(
            SFilter.eq("projectId", graph.projectId!!),
            SFilter.eq("state", "Draft"),
            SFilter.eq("graphId", graph.graphId!!)
        ).entity()

        /** 对象不为空 */
        if (entity != null) {
            /** 清除之前的草稿记录 */
            val delete = delete(
                SFilter.eq("projectId", graph.projectId!!),
                SFilter.eq("state", "Draft"),
                SFilter.eq("graphId", graph.graphId!!)
            )

            /** 删除成功执行下面操作 */
            if (delete){
                /** 清除图下子集 */
                objExtInfoService.delete(
                    SFilter.eq("id", graph.id!!),
                    SFilter.eq("graphId", graph.graphId!!))
                planarMarkersService.delete(
                    SFilter.eq("id", graph.id!!),
                    SFilter.eq("graphId", graph.graphId!!))
                planarRelationService.delete(
                    SFilter.eq("id", graph.id!!),
                    SFilter.eq("graphId", graph.graphId!!))
                planarQbsRuleService.delete(SFilter.eq("graphCoding", graph.id!!),
                    SFilter.eq("graphId", graph.graphId!!))
            }
        }
    }

    /**
     * 清除已发布的老数据
     *
     * @param   graph   图对象
     */
    private fun delOldDataPub(graph: PlanarGraph) {
        /** 清除以前的版本 */
        val entity = planarGraphPubService.select(
            SFilter.eq("projectId", graph.projectId!!),
            SFilter.eq("id", graph.id!!),
            SFilter.eq("graphId", graph.graphId!!)
        ).entity()

        /** 对象不为空 */
        if (entity != null) {
            /** 清除之前的草稿记录 */
            val delete = planarGraphPubService.delete(
                SFilter.eq("projectId", graph.projectId!!),
                SFilter.eq("id", graph.id!!),
                SFilter.eq("graphId", graph.graphId!!)
            )

            /** 删除成功执行线面操作 */
            if (delete){
                /** 清除图下子集 */
                objExtInfoPubService.delete(
                    SFilter.eq("id", graph.id!!),
                    SFilter.eq("graphId", graph.graphId!!))
                planarMarkersPubService.delete(
                    SFilter.eq("id", graph.id!!),
                    SFilter.eq("graphId", graph.graphId!!))
                planarRelationPubService.delete(
                    SFilter.eq("id", graph.id!!),
                    SFilter.eq("graphId", graph.graphId!!))
                planarQbsRulePubService.delete(
                    SFilter.eq("graphCoding", graph.id!!),
                    SFilter.eq("graphId", graph.graphId!!))
            }
        }
    }

    /**
     * 开启事务
     */
    private fun openTransaction() {

    }

    /**
     * 回滚事务
     */
    private fun backTransaction() {

    }

    /**
     * 提交事务
     */
    private fun commitTransaction() {

    }


    /**
     * 草稿图、移至回收站 或移出回收站
     *
     * @param idList    图对象列表
     * @return 操作结果
     */
    fun recycle(idList: ArrayList<PlanarGraph>): SBaseResponse {
        /** 返回对象 */
        val sBaseResponse = SBaseResponse()
        /** 列表不为空 */
        if (!idList.isNullOrEmpty()) {
            /** 遍历列表 */
            for (graph in idList) {
                /** 删除时间 */
                graph.delTime = time()
                /** 回收站标记 Recyle*/
                graph.state = "Recyle"
                /** 更新字典列表*/
                val list = ArrayList<String>()
                list.add("delTime")
                list.add("state")
                /** 更新 */
                update(graph, list)
            }

            /** 返回标记 */
            sBaseResponse.result = SResponseType.success
        } else {
            /** 返回标记 */
            sBaseResponse.result = SResponseType.failure
        }
        return sBaseResponse
    }

    /**
     * 已发布图形移至回收站
     *
     * @param idList    图对象列表
     * @return  操作结果
     */
    fun recyclePub(idList: ArrayList<PlanarGraph>): SBaseResponse{
        /** 返回对象 */
        val sBaseResponse = SBaseResponse()
        /** 开启事务 */
        openTransaction()
        /** 列表不为空 */
        if (!idList.isNullOrEmpty()){
            /** 遍历列表 */
            for (graph in idList){
                /** 项目 id */
                graph.projectId = Opts.projectId
                /** 查询 */
                val graphBuilder = PlanarGraphService.select(
                    SFilter.eq("projectId", Opts.projectId!!),
                    SFilter.eq("id", graph.id!!),
                    SFilter.eq("graphId", graph.graphId!!)
                )
                /** 设置表明，查询 */
                val graphPub = graphBuilder.table("qibaishi_gallery.qbs_graph_pub").entity()
                /** 对象不为空 */
                if (graphPub!=null){
                    /** 图编码 */
                    graphPub.id = IdUtils.uuidCreate()
                    /** 回收站标志 */
                    graphPub.state = "Recyle"
                    /** 插入数据 */
                    val insert = PlanarGraphService.insert(graphPub)
                    /** 插入是否成功 */
                    if (!insert){
                        /** 回滚处理 */
                        backTransaction()
                        /** 返回标志 */
                        sBaseResponse.result = SResponseType.failure
                        /** 返回对象 */
                        return sBaseResponse
                    }

                    /** 查询 */
                    val nodeBuilder = objExtInfoService.select(
                        SFilter.eq("id", graph.id!!),
                        SFilter.eq("graphId", graph.graphId!!)
                    )

                    /** 设置表明，查询 */
                    val nodeList = nodeBuilder.table("qibaishi_gallery.qbs_obj_ext_info_pub").exec()
                    /** 里边数量大于 0  */
                    if (nodeList.size>0){
                        /** 遍历列表 */
                        for (node in nodeList){
                            /** 图编码 */
                            node.id = graphPub.id
                            /** 插入数据 */
                            objExtInfoService.insert(node)
                        }
                    }

                    /** 查询 */
                    val markersBuilder = planarMarkersService.select(
                        SFilter.eq("id", graph.id!!),
                        SFilter.eq("graphId", graph.graphId!!)
                    )
                    /** 设置表明，查询 */
                    val markersList = markersBuilder.table("qibaishi_gallery.qbs_marker_pub").exec()
                    /** 列表大于 0  */
                    if (markersList.size>0){
                        /** 遍历列表 */
                        for (markers in markersList){

                            /** 图编码 */
                            markers.id = graphPub.id
                            /** 插入数据 */
                            planarMarkersService.insert(markers)
                        }
                    }

                    /** 查询 */
                    val relationBuilder = planarRelationService.select(
                        SFilter.eq("id", graph.id!!),
                        SFilter.eq("graphId", graph.graphId!!)
                    )
                    /** 设置表明，查询 */
                    val relationList = relationBuilder.table("qibaishi_gallery.qbs_relation_pub").exec()
                    /** 列表大于 0  */
                    if (relationList.size>0){
                        /** 遍历列表 */
                        for (relation in relationList ){
                            /** 图编码 */
                            relation.id = graphPub.id
                            /** 插入数据 */
                            planarRelationService.insert(relation)
                        }
                    }

                    /** 规则 */
                    val planarQbsRuleBuilder = planarQbsRuleService.select(
                        SFilter.eq("graphCoding", graph.id!!),
                        SFilter.eq("graphId", graph.graphId!!)
                    )
                    /** 设置表明，查询 */
                    val planarQbsRuleList = planarQbsRuleBuilder.table("qibaishi_gallery.qbs_rule_pub").exec()
                    if (planarQbsRuleList.size>0) {
                        /** 遍历列表 */
                        for (relation in planarQbsRuleList ){
                            /** 图编码 */
                            relation.graphCoding = graphPub.id
                            /** 插入数据 */
                            planarQbsRuleService.replace(relation)
                        }
                    }

                    /** 删除已发布的图形数据 */
                    delOldDataPub(graph)
                }
            }

            /** 返回标志 */
            sBaseResponse.result = SResponseType.success
        }else{
            /** 返回标志 */
            sBaseResponse.result = SResponseType.failure
        }
        return sBaseResponse
    }

    /**
     * 草稿箱图形数据读取所有节点
     *
     * @param graphs    图对象
     * @return 查询结果
     */
    fun readDrafts(graphs: PlanarGraph): SCommonResponse<PlanarGraph> {
        /** 返回对象 */
        val sQueryResponse = SCommonResponse<PlanarGraph>()
        /** 查询 */
        val graph = select(
            SFilter.eq("projectId", Opts.projectId!!),
            SFilter.eq("id", graphs.id!!),
            SFilter.eq("graphId", graphs.graphId!!)
        ).entity()
        /** 对象不为空，继续操作 */
        if (graph!=null){
            /** 查询节点 */
            val nodeList = objExtInfoService.select(
                SFilter.eq("id", graph.id!!),
                SFilter.eq("graphId", graph.graphId!!)
            ).exec()
            /** 子列表数组 */
            val elements = PlanarElements()
            /** 列表大于 0  */
            if (nodeList.size>0){
                /** 赋值 */
                elements.objExtInfo = nodeList
            }

            /** 查询 */
            val markersList = planarMarkersService.select(
                SFilter.eq("id", graph.id!!),
                SFilter.eq("graphId", graph.graphId!!)
            ).exec()

            /** 查询管线 */
            val relationList = planarRelationService.select(
                SFilter.eq("id", graph.id!!),
                SFilter.eq("graphId", graph.graphId!!)
            ).exec()

            /** 规则 */
            val planarQbsRuleList = planarQbsRuleService.select(
                SFilter.eq("graphCoding", graph.id!!),
                SFilter.eq("graphId", graph.graphId!!)
            ).exec()

            if (planarQbsRuleList.size>0) {
                graph.ruleList = planarQbsRuleList
            }
            /** 列表大于 0 */
            if (relationList.size>0){
                elements.relations = relationList
            }
            /** 列表大于 0 */
            if (markersList.size>0){
                elements.markers = markersList
            }
            /** 赋值 */
            graph.elements = elements
            /** 标志*/
            sQueryResponse.result = SResponseType.success
            /** 对象 */
            sQueryResponse.content = graph
        }else{
            sQueryResponse.message = "图不存在"
            sQueryResponse.result = SResponseType.failure
        }
        /** 返回对象 */
        return sQueryResponse
    }

    /**
     * 已发布图形数据读取所有节点
     *
     * @param graphPub  图对象
     * @return 查询结果
     */
    fun readPub(graphPub: PlanarGraphPub): SCommonResponse<PlanarGraphPub>{
        /** 返回对象 */
        val sQueryResponse = SCommonResponse<PlanarGraphPub>()
        /** 查询 */
        val graph = planarGraphPubService.select(
            SFilter.eq("projectId", Opts.projectId!!),
            SFilter.eq("id", graphPub.id!!),
            SFilter.eq("graphId", graphPub.graphId!!)
        ).entity()
        /** 对象不为空 */
        if (graph!=null){
            /** 查询 */
            val nodeList = objExtInfoPubService.select(
                SFilter.eq("id", graph.id!!),
                SFilter.eq("graphId", graph.graphId!!)
            ).exec()
            /** 列表对象 */
            val elements = PlanarElementsPub()
            /** 列表不为空 */
            if (nodeList.size>0){
                /** 遍历列表 */
                /** 赋值 */
                elements.objExtInfo = nodeList
            }
            /**查询 */
            val markersList = planarMarkersPubService.select(
                SFilter.eq("id", graph.id!!),
                SFilter.eq("graphId", graph.graphId!!)
            ).exec()
            /** 查询 */
            val relationList = planarRelationPubService.select(
                SFilter.eq("id", graph.id!!),
                SFilter.eq("graphId", graph.graphId!!)
            ).exec()

            try {
                val planarQbsRuleList = planarQbsRulePubService.select(
                    SFilter.eq("graphCoding", graph.id!!),
                    SFilter.eq("graphId", graph.graphId!!)
                ).exec()

                if (planarQbsRuleList.size>0) {
                    graph.ruleList = planarQbsRuleList
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            /** 管线列表数量大于 0  */
            if (relationList.size>0){
                elements.relations = relationList
            }

            /** 列表数量大于 0 */
            if (markersList.size>0){
                elements.markers = markersList
            }
            /** 列表赋值 */
            graph.elements = elements
            /** 返回标志 */
            sQueryResponse.result = SResponseType.success
            /** 对象 */
            sQueryResponse.content = graph
        }else{
            /** 返回标志 */
            sQueryResponse.result = SResponseType.failure
        }

        /** 返回结果 */
        return sQueryResponse
    }

    /**
     * 回收站-恢复                             待处理
     *
     * @param graphs    图对象
     * @return 处理结果
     */
    fun recovery(graphs: PlanarGraph): SBaseResponse{
        /** 项目 id */
        graphs.projectId = Opts.projectId
        /** 查询图 */
        val graph = select(
            SFilter.eq("projectId", Opts.projectId!!),
            SFilter.eq("id", graphs.id!!),
            SFilter.eq("graphId", graphs.graphId!!)
        ).entity()
        /** 图对象不为空 */
        if (graph!=null){
            /** 查询 */
//            val markersList = planarMarkersService.select(
//                SFilter.eq("id", graphs.id!!),
//                SFilter.eq("graphId", graphs.graphId!!)
//            ).exec()
//            /** 查询 */
//            val nodeList = objExtInfoService.select(
//                SFilter.eq("id", graphs.id!!),
//                SFilter.eq("graphId", graphs.graphId!!)
//            ).exec()
//            /** 查询 */
//            val relationList = planarRelationService.select(
//                SFilter.eq("id", graphs.id!!),
//                SFilter.eq("graphId", graphs.graphId!!)
//            ).exec()
//
//            val planarQbsRuleList = planarQbsRulePubService.select(
//                SFilter.eq("id", graphs.id!!),
//                SFilter.eq("graphId", graphs.graphId!!)
//            ).exec()


            /** 清除草稿箱数据 */
            delOldDataTwo(graphs)
            /** 列表 */
            val listState = ArrayList<String>()
            listState.add("state")
            /** 草稿箱标志 */
            graph.state = "Draft"
            /** 更新 */
            update(graph,listState)
            /** 列表不为空 */
//            if (!markersList.isNullOrEmpty()){
//                /** 遍历列表 */
//                for (markers in markersList){
//                    /** 草稿箱标志 */
//                    markers.state = 1
//                    /** 更新数据 */
//                    MarkersService.update(markers,listState)
//                }
//            }
//
//            /** 列表不为空 */
//            if (!nodeList.isNullOrEmpty()){
//                /** 遍历列表 */
//                for (node in nodeList){
//                    /** 回收站标志 */
//                    node.state = 1
//                    /** 更新 */
//                    NodeService.update(node,listState)
//                }
//            }
//
//            /** 列表不为空 */
//            if (!anchorList.isNullOrEmpty()){
//                /** 遍历列表 */
//                for (anchor in anchorList){
//                    /** 草稿箱标志 */
//                    anchor.state = 1
//                    /** 更新 */
//                    AnchorService.update(anchor,listState)
//                }
//            }
//
//            /** 列表不为空 */
//            if (!attachObjectIdsList.isNullOrEmpty()){
//                /** 遍历列表 */
//                for (attachObjectIds in attachObjectIdsList){
//                    /** 草稿箱标志 */
//                    attachObjectIds.state = 1
//                    /** 更新 */
//                    AttachObjectIdsServices.update(attachObjectIds,listState)
//                }
//            }

//            /** 列表不为空 */
//            if (!relationList.isNullOrEmpty()){
//                /** 遍历列表 */
//                for (relation in relationList){
//                    /** 回收站标志 */
//                    relation.state = 1
//                    /** 更新 */
//                    RelationService.update(relation,listState)
//                }
//            }
        }
        /** 返回操作状态 */
        return SBaseResponse(SResponseType.success)
    }


    /**
     * 查询对象信息
     * @param ids
     * @param type
     * @return
     */
    fun queryBuilding(ids: SFilter): List<Building?>? {
        val param = JSONObject()
        val criteria = JSONObject()
        criteria["id"] = ids.second
        param["criteria"] = criteria
        return dmpBaseService!!.queryBuilding(param)
    }


    /**
     * 查询对象信息
     * @param ids
     * @param type
     * @return
     */
    fun queryFloor(ids: SFilter): List<Floor?>? {
        val param = JSONObject()
        val criteria = JSONObject()
        criteria["id"] = ids.second
        param["criteria"] = criteria
        //排序
        val orders = JSONArray()
        val order = JSONObject()
        order["column"] = "floorSequenceID"
        order["asc"] = false
        orders.add(order)
        param["orders"] = orders
        return dmpBaseService!!.queryFloor(param)
    }

    /**
     * 查询草稿箱平面图
     *
     * @param request       查询条件
     */
    fun pageQuerysDrafts(request: SQueryRequest): SQueryResponse<Building> {
        val sQueryResponse = SQueryResponse<Building>()
        try {
            val pageQuery = PlanarGraphService.pageQuery(request, arrayListOf(SFilter.eq("projectId", Opts.projectId!!)))
            if (pageQuery.result == SResponseType.success){
                if (!pageQuery.content.isNullOrEmpty()) {

                    val setBuilding = HashSet<String>()
                    for (content in pageQuery.content!!) {
                        setBuilding.add(content.buildingId!!)
                    }

                    val setFloor = HashSet<String>()
                    for (content in pageQuery.content!!) {
                        setFloor.add(content.floorId!!)
                    }
                    val buildingList = queryBuilding(SFilter.inList("id", setBuilding.toList()))
                    val floorList = queryFloor(SFilter.inList("id", setFloor.toList()))

                    for (floor in floorList!!) {
                        for (content in pageQuery.content!!) {
                            if (floor != null) {
                                if (content.floorId == floor.id) {
                                    if (floor!!.planarGraphList.isNullOrEmpty()) {
                                        floor.planarGraphList =  ArrayList()
                                    }
                                    floor.planarGraphList!!.add(content)
                                }
                            }
                        }
                    }
                    for (building in buildingList!!) {
                        for (floor in floorList) {
                            if (building != null) {
                                if (floor!!.buildingId == building.id) {
                                    if (building.floorList.isNullOrEmpty()) {
                                        building.floorList = ArrayList<Floor>()
                                    }
                                    building.floorList!!.add(floor)
                                }
                            }
                        }
                    }
                    sQueryResponse.content = buildingList as List<Building>?
                }else{
                    sQueryResponse.content = ArrayList()
                }
                sQueryResponse.result = SResponseType.success
            } else {
                sQueryResponse.result = SResponseType.failure
            }
        } catch (e: Exception) {
            e.printStackTrace()
            sQueryResponse.message = e.message!!
            sQueryResponse.result = SResponseType.failure
        }
        return sQueryResponse
    }



    /**
     * 查询已发布平面图
     */
    fun pageQuerysPub(request: SQueryRequest): SQueryResponse<Building> {
        val sQueryResponse = SQueryResponse<Building>()
        try {
            val pageQuery = planarGraphPubService.pageQuery(request, arrayListOf(SFilter.eq("projectId", Opts.projectId!!)))
            if (pageQuery.result == SResponseType.success){
                if (!pageQuery.content.isNullOrEmpty()) {

                    val setBuilding = HashSet<String>()
                    for (content in pageQuery.content!!) {
                        setBuilding.add(content.buildingId!!)
                    }

                    val setFloor = HashSet<String>()
                    for (content in pageQuery.content!!) {
                        setFloor.add(content.floorId!!)
                    }

                    val buildingList = queryBuilding(SFilter.inList("id", setBuilding.toList()))
                    val floorList = queryFloor(SFilter.inList("id", setFloor.toList()))

                    if (floorList != null) {
                        for (floor in floorList) {
                            for (content in pageQuery.content!!) {
                                if (content.floorId == floor!!.id) {
                                    if (floor.planarGraphList.isNullOrEmpty()) {
                                        floor.planarGraphList =  ArrayList()
                                    }
                                    floor.planarGraphList!!.add(content)
                                }
                            }
                        }
                    }
                    if (buildingList != null) {
                        for (building in buildingList) {
                            if (floorList != null) {
                                for (floor in floorList) {
                                    if (floor!!.buildingId == building!!.id) {
                                        if (building.floorList.isNullOrEmpty()) {
                                            building.floorList = ArrayList<Floor>()
                                        }
                                        building.floorList!!.add(floor)
                                    }
                                }
                            }
                        }
                    }
                    sQueryResponse.content = buildingList as List<Building>?
                }else{
                    sQueryResponse.content = ArrayList()
                }
                sQueryResponse.result = SResponseType.success
            } else {
                sQueryResponse.result = SResponseType.failure
            }
        } catch (e: Exception) {
            e.printStackTrace()
            sQueryResponse.message = e.message!!
            sQueryResponse.result = SResponseType.failure
        }
        return sQueryResponse
    }

    /**
     * 当前时间
     *
     * @return 当前时间
     */
    private fun time():Date {
        val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") //设置日期格式
        println(df.format(Date())) // new Date()为获取当前系统时间
        val format = df.format(Date())
        return df.parse(format)
    }

}