package com.persagy.server.services.dict

import com.persagy.base.extensions.toJson
import com.persagy.database.SFilter
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.datacenter.models.entities.dict.*
import com.persagy.server.services.base.Service
import com.persagy.service.SBaseService
import com.persagy.service.SObjectService
import com.persagy.service.SPageContext
import com.persagy.service.models.enums.SResponseType
import com.persagy.service.models.responses.SBaseResponse
import com.persagy.service.models.responses.SCreateResponse
import org.slf4j.LoggerFactory

/**
 * 项目定制化字典服务
 *
 * @author 张维新
 */
object DataDictionaryDescriptionProjectService : Service<PropertyDefProjectInfo>(SMybatisDao(PropertyDefProjectInfo::class.java)) {

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

    /** 设备族对应的设备分类服务 */
    private val equipFamilyservice = SBaseService(SMybatisDao(EquipFamily::class.java))

    /** 物理世界自定义方案和项目的关系服务 */
    private var projectSchemeService = SObjectService(SMybatisDao(ProjectScheme::class.java))

    /** 数据中心方案服务 */
    var schemeInfoServices = SObjectService(SMybatisDao(DataCenterPropertyDefScheme::class.java))

    /**
     * 创建之前操作
     */
    override fun onCreateBefore(dataDictionary: PropertyDefProjectInfo): Boolean {
        val projectId = SPageContext.getHeader("ProjectId")
        if (dataDictionary.type!!.length == 3) {
            val equipFamily = equipFamilyservice.select("family = '${dataDictionary.type}'").entity()
            dataDictionary.type = equipFamily!!.equipCode!!
        }
        if (dataDictionary.projectId.isNullOrEmpty()) {
            dataDictionary.projectId = projectId
        }
        return true
    } // Function onCreateBefore()

    /**
     * 设置项目定制信息
     *
     * @param  dataDictionaryList  定制字典数组
     */
    fun create(dataDictionaryList: ArrayList<PropertyDefProjectInfo>): SCreateResponse<PropertyDefProjectInfo> {
        return try {
            val projectId = SPageContext.getHeader("ProjectId")
            for (dataDictionary in dataDictionaryList) {

//                if (dataDictionary.type!!.length == 3){
//                    val equipFamily = equipFamilyservice.select("family = '${dataDictionary.type}'").entity()
//                    dataDictionary.type = equipFamily!!.equipCode!!
//                }
                try {
                    if (dataDictionary.projectId.isNullOrEmpty()) {
                        dataDictionary.projectId = projectId
                    }
                    dataDictionary.objectType = null
                    try {
                        replace(dataDictionary)
                    } catch (e: Exception) {
                        e.printStackTrace()
                        update(dataDictionary)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            val sCreateResponse = SCreateResponse<PropertyDefProjectInfo>()
            sCreateResponse.result = SResponseType.success
            sCreateResponse.entityList = dataDictionaryList
            sCreateResponse
        } catch (e: Exception) {
            e.printStackTrace()
            SCreateResponse(SResponseType.failure, e.message!!)
        }
    } // Function create()

    /**
     * 根据项目id 具体类型重项目定制信息
     *
     * @param   type    类型
     */
    fun deleteType(type: String): SBaseResponse {
        return try {
            val projectId = SPageContext.getHeader("ProjectId")
            val isDelete = delete(SFilter.eq("type", type), SFilter.eq("projectId", projectId!!))
            if (isDelete) {
                val sCreateResponse = SBaseResponse()
                sCreateResponse.result = SResponseType.success
                sCreateResponse.message = type
                sCreateResponse
            } else {
                val sCreateResponse = SBaseResponse()
                sCreateResponse.result = SResponseType.failure
                sCreateResponse.message = type
                sCreateResponse

            }
        } catch (e: Exception) {
            e.printStackTrace()
            return SBaseResponse(SResponseType.failure, e.message!!)
        }
    } // Function deletes()

    /**
     * 根据项目id重项目定制信息
     *
     */
    fun deleteId(): SBaseResponse {
        return try {
            val projectId = SPageContext.getHeader("ProjectId")
            val isDelete = delete(SFilter.eq("projectId", projectId!!))
            if (isDelete) {
                val sCreateResponse = SBaseResponse()
                sCreateResponse.result = SResponseType.success
                sCreateResponse.message = projectId
                sCreateResponse
            } else {
                val sCreateResponse = SBaseResponse()
                sCreateResponse.result = SResponseType.failure
                sCreateResponse.message = projectId
                sCreateResponse
            }
        } catch (e: Exception) {
            e.printStackTrace()
            return SBaseResponse(SResponseType.failure, e.message!!)
        }
    } // Function deletes()

    /**
     * 批量处理定制化字典信息
     *
     * @param   request     处理命令对象
     */
    fun createListDict(request: DictBatchProcessing): SCreateResponse<DictBatchProcessing> {
        return try {
            val projectId = SPageContext.getHeader("ProjectId")
            if (request.schemeId.isNullOrEmpty()) {
                val sCreateResponse = SCreateResponse<DictBatchProcessing>(SResponseType.failure)
                sCreateResponse.message = "SchemeId:不能为空"
                sCreateResponse
            } else {
                logger.debug("一级标签000=${request.toJson()}")
                when {
                    request.schemeId == "schemeZero" -> {
                        if (!request.priorityList.isNullOrEmpty() && request.priorityList!!.size > 0 && !request.firstNameList.isNullOrEmpty() && request.firstNameList!!.size > 0) {

                            /** 清除项目下的字典信息 */
                            delete(SFilter.eq("projectId",projectId!!))
                            /** 导入原始字典数据 */
                            schemeService.setControlDict(projectId)
                            /** 查询项目对应的方案 */
                            val projectScheme = projectSchemeService.select(SFilter.eq("projectId", projectId)).entity()
                            if (projectScheme!=null){
                                /** 导入自定义信息点 */
                                schemeService.setSchemeCustomDict(projectId,projectScheme.schemeId!!)
                            }
                            val propertyDefProjectInfo = PropertyDefProjectInfo()
                            propertyDefProjectInfo.visible = false
                            propertyDefProjectInfo.projectId = projectId
                            DataDictionaryDescriptionProjectService.update(propertyDefProjectInfo, arrayListOf("visible"),
                                    arrayListOf(SFilter.eq("projectId",projectId),SFilter.not(SFilter.eq("unDisabled",false))))

                            /** 一级标签 */
                            for (firstName in request.firstNameList!!) {
                                val propertyDefProjectInfo = PropertyDefProjectInfo()
                                propertyDefProjectInfo.visible = true
                                propertyDefProjectInfo.projectId = projectId
                                DataDictionaryDescriptionProjectService.update(propertyDefProjectInfo, arrayListOf("visible"),
                                        arrayListOf(SFilter.eq("projectId",projectId),SFilter.eq("firstName",firstName)))
                            }

                            /** 匹配优先级 */
                            for (priority in request.priorityList!!) {
                                val propertyDefProjectInfo = PropertyDefProjectInfo()
                                propertyDefProjectInfo.visible = true
                                propertyDefProjectInfo.projectId = projectId
                                DataDictionaryDescriptionProjectService.update(propertyDefProjectInfo, arrayListOf("visible"),
                                        arrayListOf(SFilter.eq("projectId",projectId),SFilter.eq("priority",priority)))
                            }

                        } else if (!request.firstNameList.isNullOrEmpty() && request.firstNameList!!.size > 0) {
                            logger.debug("一级标签1=${request.firstNameList!!.toJson()}")
                            try {

                                /** 清除项目下的字典信息 */
                                DataDictionaryDescriptionProjectService.delete(SFilter.eq("projectId",projectId!!))
                                /** 导入原始字典数据 */
                                schemeService.setControlDict(projectId)
                                /** 查询项目对应的方案 */
                                val projectScheme = projectSchemeService.select(SFilter.eq("projectId", projectId)).entity()
                                if (projectScheme!=null){
                                    /** 导入自定义信息点 */
                                    schemeService.setSchemeCustomDict(projectId,projectScheme.schemeId!!)
                                }

                                val propertyDefProjectInfo = PropertyDefProjectInfo()
                                propertyDefProjectInfo.visible = false
                                propertyDefProjectInfo.projectId = projectId
                                DataDictionaryDescriptionProjectService.update(propertyDefProjectInfo, arrayListOf("visible"),
                                        arrayListOf(SFilter.eq("projectId",projectId), SFilter.not(SFilter.eq("unDisabled",false))))

                                /** 一级标签 */
                                for (firstName in request.firstNameList!!) {
                                    logger.debug("一级标签=$firstName")
                                    val propertyDefProjectInfo = PropertyDefProjectInfo()
                                    propertyDefProjectInfo.visible = true
                                    propertyDefProjectInfo.projectId = projectId
                                    DataDictionaryDescriptionProjectService.update(propertyDefProjectInfo, arrayListOf("visible"),
                                            arrayListOf(SFilter.eq("projectId",projectId),SFilter.eq("firstName",firstName)))
                                }
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }

                        } else if (!request.priorityList.isNullOrEmpty() && request.priorityList!!.size > 0) {
                            /** 设置优先级 */

                            try {
                                /** 清除项目下的字典信息 */
                                DataDictionaryDescriptionProjectService.delete(SFilter.eq("projectId",projectId!!))
                                /** 导入原始字典数据 */
                                schemeService.setControlDict(projectId)
                                /** 查询项目对应的方案 */
                                val projectScheme = projectSchemeService.select(SFilter.eq("projectId", projectId)).entity()
                                if (projectScheme!=null){
                                    /** 导入自定义信息点 */
                                    schemeService.setSchemeCustomDict(projectId,projectScheme.schemeId!!)
                                }

                                val propertyDefProjectInfo = PropertyDefProjectInfo()
                                propertyDefProjectInfo.visible = false
                                propertyDefProjectInfo.projectId = projectId
                                DataDictionaryDescriptionProjectService.update(propertyDefProjectInfo, arrayListOf("visible"),
                                        arrayListOf(SFilter.eq("projectId",projectId), SFilter.not(SFilter.eq("unDisabled",false))))

                                /** 匹配优先级 */
                                for (priority in request.priorityList!!) {
                                    val propertyDefProjectInfo = PropertyDefProjectInfo()
                                    propertyDefProjectInfo.visible = true
                                    propertyDefProjectInfo.projectId = projectId
                                    DataDictionaryDescriptionProjectService.update(propertyDefProjectInfo, arrayListOf("visible"),
                                            arrayListOf(SFilter.eq("projectId",projectId),SFilter.eq("priority",priority)))
                                }
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        } else {

                            /** 清除项目下的字典信息 */
                            DataDictionaryDescriptionProjectService.delete(SFilter.eq("projectId",projectId!!))
                            /** 导入原始字典数据 */
                            schemeService.setControlDict(projectId)
                            /** 查询项目对应的方案 */
                            val projectScheme = projectSchemeService.select(SFilter.eq("projectId", projectId)).entity()
                            if (projectScheme!=null){
                                /** 导入自定义信息点 */
                                schemeService.setSchemeCustomDict(projectId,projectScheme.schemeId!!)
                            }

                            val propertyDefProjectInfo = PropertyDefProjectInfo()
                            propertyDefProjectInfo.visible = false
                            propertyDefProjectInfo.projectId = projectId
                            DataDictionaryDescriptionProjectService.update(propertyDefProjectInfo, arrayListOf("visible"),
                                    arrayListOf(SFilter.eq("projectId",projectId), SFilter.not(SFilter.eq("unDisabled",false))))
                        }
                        SCreateResponse(SResponseType.success)
                    }
                    request.schemeId == "schemeOne" -> {
                        /** 方案一数据处理 */

                        /** 清除项目下的字典信息 */
                        DataDictionaryDescriptionProjectService.delete(SFilter.eq("projectId",projectId!!))
                        /** 导入方案1 */
                        schemeService.setScheme(projectId,"1")
                        /** 查询项目对应的方案 */
                        val projectScheme = projectSchemeService.select(SFilter.eq("projectId", projectId)).entity()
                        if (projectScheme!=null){
                            /** 导入自定义信息点 */
                            schemeService.setSchemeCustomDict(projectId,projectScheme.schemeId!!)
                        }

                        SCreateResponse(SResponseType.success)
                    }
                    request.schemeId == "schemeTwo" ->{
                        /** 清除项目下的字典信息 */
                        DataDictionaryDescriptionProjectService.delete(SFilter.eq("projectId",projectId!!))
                        /** 导入方案1 */
                        schemeService.setScheme(projectId,"2")
                        /** 查询项目对应的方案 */
                        val projectScheme = projectSchemeService.select(SFilter.eq("projectId", projectId)).entity()
                        if (projectScheme!=null){
                            /** 导入自定义信息点 */
                            schemeService.setSchemeCustomDictFalse(projectId,projectScheme.schemeId!!)
                        }
//                        /** 万达方案 */
//                        val listWanDa = schemeInfoServices.select(SFilter.eq("schemeId", "2")).exec()
//                        try {
//                            for (content in listWanDa){
//
//                                val propertyDefProjectInfo = PropertyDefProjectInfo()
//                                propertyDefProjectInfo.dataSource = content.dataSource
//                                logger.debug("数据源=${content.dataSource}")
//                                propertyDefProjectInfo.dataType = content.dataType
//                                propertyDefProjectInfo.unDisabled = content.unDisabled
//                                propertyDefProjectInfo.editable = content.editable
//                                propertyDefProjectInfo.firstName = content.firstName
//                                propertyDefProjectInfo.firstTag = content.firstTag
//                                propertyDefProjectInfo.flag = content.flag
//                                propertyDefProjectInfo.infoPointCode = content.infoPointCode
//                                propertyDefProjectInfo.infoPointName = content.infoPointName
//                                propertyDefProjectInfo.inputMode = content.inputMode
//                                propertyDefProjectInfo.note = content.note
//                                propertyDefProjectInfo.priority = content.priority
//                                propertyDefProjectInfo.projectId = projectId
//                                propertyDefProjectInfo.secondName = content.secondName
//                                propertyDefProjectInfo.secondTag = content.secondTag
//                                propertyDefProjectInfo.sort = content.sort
//                                propertyDefProjectInfo.unit = content.unit
//                                propertyDefProjectInfo.visible = content.visible
//                                propertyDefProjectInfo.type = content.type
//                                DataDictionaryDescriptionProjectService.replace(propertyDefProjectInfo)
//                            }
//                        } catch (e: Exception) {
//                            e.printStackTrace()
//                        }

                        SCreateResponse(SResponseType.success)
                    }
                    else -> {
                        val sCreateResponse = SCreateResponse<DictBatchProcessing>(SResponseType.failure)
                        sCreateResponse.message = "SchemeId:值传输错误，请参考文档"
                        sCreateResponse
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            SCreateResponse(SResponseType.failure, e.message!!)
        }
    } // Function createListDict()

} // Object DataDictionaryDescriptionProjectService