package com.persagy.server.labsl.services

import com.persagy.base.extensions.toJson
import com.persagy.database.SFilter
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.labsl.models.entities.GraphCategory
import com.persagy.server.labsl.models.request.GraphCategoryRequest
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 com.persagy.service.utils.SSpringContextUtil
import org.slf4j.LoggerFactory

/**
 * 分类服务
 *
 * @author  wx
 * @date  2020/9/15 11:38
 */
object GraphCategoryService : SObjectService<GraphCategory>(SMybatisDao(GraphCategory::class.java)) {

    /** 日志 */
    private val logger = LoggerFactory.getLogger(GraphCategoryService::class.java)

    /** 自定义sql */
    private val customMapper by lazy {
        SSpringContextUtil.getBean(CustomService::class.java) as CustomService
    }

    /**
     * 系统图分类查询
     */
    fun graphCategoryQuery(request: GraphCategoryRequest): SQueryResponse<GraphCategory> {
        /** 项目id */
        val projectId = SPageContext.getHeader("ProjectId")
        val sQueryResponse = SQueryResponse<GraphCategory>()
        return try {
            if (request.switch) {
                val graphCategoryList = select(SFilter.isNull("parentId")).exec()
                for (graphCategory in graphCategoryList) {
                    val treeClimate = treeClimate(graphCategory.id!!, true)
                    if (treeClimate.size > 0) {
                        graphCategory.categoryList = treeClimate
                    }
                }
                sQueryResponse.content = graphCategoryList
                sQueryResponse.total = graphCategoryList.size.toLong()
                sQueryResponse.result = SResponseType.success
                sQueryResponse
            } else {

                val calcAffectedList = customMapper.draftsCategory(projectId!!)
                val pubCategoryList = customMapper.pubCategory(projectId)
                logger.debug("未发布：${calcAffectedList?.toJson()}")
                logger.debug("已发布：${pubCategoryList?.toJson()}")
                val set = HashSet<String>()
                if (!pubCategoryList.isNullOrEmpty() || !calcAffectedList.isNullOrEmpty()) {
                    if (!pubCategoryList.isNullOrEmpty()) {
                        for (pubCategory in pubCategoryList) {
                            set.add(pubCategory.categoryId!!)
                        }
                    }
                    if (!calcAffectedList.isNullOrEmpty()) {
                        for (calcAffected in calcAffectedList) {
                            set.add(calcAffected.categoryId!!)
                        }
                    }
                    val graphCategoryList = select(SFilter.isNull("parentId")).exec()
                    for (graphCategory in graphCategoryList) {
                        val treeClimate = treeClimate(graphCategory.id!!, true)
                        if (treeClimate.size > 0) {
                            graphCategory.categoryList = treeClimate
                        }
                    }

                    for (id in set) {
                        for (graphCategory in graphCategoryList) {
                            if (graphCategory.id == id) {
                                graphCategory.sign = true
                            }
                            if (!graphCategory.categoryList.isNullOrEmpty()) {
                                val categoryList = graphCategory.categoryList!!
                                for (category in categoryList) {
                                    if (category.id == id) {
                                        category.sign = true
                                        graphCategory.sign = true
                                    }
                                    if (!category.categoryList.isNullOrEmpty()) {
                                        val categoryList1 = category.categoryList!!
                                        for (category2 in categoryList1) {
                                            if (category2.id == id) {
                                                category2.sign = true
                                                category.sign = true
                                                graphCategory.sign = true
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                        val iterator = graphCategoryList.iterator()
                        while (iterator.hasNext()){
                            val next = iterator.next()
                            if (next.sign){
                                if (!next.categoryList.isNullOrEmpty()){
                                    val iterator1 = next.categoryList!!.iterator()
                                    while (iterator1.hasNext()){
                                        val next1 = iterator1.next()
                                        if (next1.sign){
                                            if (!next1.categoryList.isNullOrEmpty()){
                                                val iterator2 = next1.categoryList!!.iterator()
                                                while (iterator2.hasNext()){
                                                    val next2 = iterator2.next()
                                                    if (!next2.sign){
                                                        iterator2.remove()
                                                    }
                                                }
                                            }
                                        }else{
                                            iterator1.remove()
                                        }
                                    }
                                }
                            }else{
                                iterator.remove()
                            }
                        }

                    sQueryResponse.content = graphCategoryList
                    sQueryResponse.total = graphCategoryList.size.toLong()
                    sQueryResponse.result = SResponseType.success
                    sQueryResponse
                } else {
                    sQueryResponse.content = ArrayList()
                }
                sQueryResponse.result = SResponseType.success
                sQueryResponse
            }
        } catch (e: Exception) {
            e.printStackTrace()
            sQueryResponse.result = SResponseType.failure
            sQueryResponse
        }

    } // Fun graphCategoryQuery()

    /**
     * 气候区 递归查询
     *
     * @param   parent  外键关系值
     * @param   hasChildren 是否进行递归查询
     */
    fun treeClimate(parent: String, hasChildren: Boolean = true): ArrayList<GraphCategory> {
        val content = select("parentId" to parent).exec()
        if (hasChildren) {
            for (item in content) {
                try {
                    val children = treeClimate(item.id!!)
                    if (children.size > 0) {
                        item.categoryList = children
                    }
                } catch (e: Exception) {
                    // DO NOTHING
                }
            }
        }
        return content
    } // Function treeClimate()

} // Object GraphCategoryService