package com.persagy.revit.services.json

import cn.sagacloud.server.algorithm.models.entities.*
import cn.sagacloud.server.algorithm.models.jsonAnalyzer.AllComponents
import cn.sagacloud.server.algorithm.models.jsonAnalyzer.BaseObj
import cn.sagacloud.server.algorithm.services.CommonService
import com.sybotan.database.SFilter
import com.sybotan.service.SObjectService
import com.sybotan.service.models.enums.SResponseType
import com.sybotan.service.models.requests.SCreateRequest
import org.apache.commons.lang3.StringUtils
import org.apache.commons.text.StringEscapeUtils
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap

/**
 *
 *
 * @author jxing
 */
object EquipmentAnalyzer {


    fun analyze(equipmentService: SObjectService<Equipment>, baseObj: BaseObj<AllComponents>,
                equipments: ArrayList<Equipment>?, bimIdPrefix: String,
                equipMap: HashMap<String, BaseComponent>,
                flag: Boolean, equipCompService: SObjectService<EquipComp>,
                infoPointCompService: SObjectService<InfoPointComp>,
                unrecognizedEquipService: SObjectService<UnrecognizedEquip>): Boolean {

        if(!flag){
            return analyze1(equipmentService,baseObj,equipments,bimIdPrefix,equipMap)
        }else{
            return analyze2(equipmentService,baseObj,equipments,bimIdPrefix,equipMap,equipCompService,infoPointCompService,unrecognizedEquipService)
        }
    }


    /**
     * @Description: 第一版设备解析，后面可能会删除
     * 将设备的编码转换为标准编码
     */
    fun analyze1(equipmentService: SObjectService<Equipment>, baseObj: BaseObj<AllComponents>, equipments: ArrayList<Equipment>?, bimIdPrefix: String, equipMap: HashMap<String, BaseComponent>): Boolean {
        if (equipments == null || equipments.isEmpty())
            return true
        val newEquipmnets = ArrayList<Equipment>()
        for (obj in equipments) {
            obj.id = CommonService.generateUUID(null, true)
            obj.modelId = baseObj.modelId
            var family: String? = null
            val familyName = obj.familyName
            if (!familyName.isNullOrEmpty()) {
                val index = familyName.indexOf("-")

                if(index != -1){
                    family = familyName!!.substring(0, index)
                    //设备编码转换
                    obj.family = family
                }

            }
            obj.bimId = "${bimIdPrefix}${obj.sourceId}"
            if (obj.revitId != null && obj.revitId!!.isNotEmpty())
                equipMap[obj.revitId!!] = obj
            if (obj.parameters != null) {
                var infos = HashMap<String, String>()

                for (param in obj.parameters!!) {
                    param.value = StringUtils.remove(param.value,"'")
                    if (param.name.equals("设备本地名称")) {
                        obj.localName = param.value
                    } else if (param.name.equals("设备本地编码")) {
                        obj.localId = param.value
                    } else if (param.name.equals("PropertyID", true)) {
                        obj.propertyId = param.value
                    } else if (param.name.equals("构件分类编码")) {
                        obj.bimTypeID = param.value
                    } else if (null != family && !param.name.isNullOrEmpty()) {
                        //信息点编码转换
                        infos[param.name!!] = param.value ?: ""
                    }
                }
                obj.infos = infos
            }

            if(!family.isNullOrEmpty()){
                newEquipmnets.add(obj)
            }
        }
        equipmentService.delete(SFilter.eq("modelId", baseObj.modelId!!))
        val create = SCreateRequest<Equipment>()
        create.content = newEquipmnets
        val result = equipmentService.createList(create)
        return SResponseType.success == result.result
    }

    /**
     * @Description: 第二版设备解析，正在使用的
     * 将设备的构建码转换为标准编码
     */
    fun analyze2(equipmentService: SObjectService<Equipment>, baseObj: BaseObj<AllComponents>, equipments: ArrayList<Equipment>?, bimIdPrefix: String, equipMap: HashMap<String, BaseComponent>, equipCompService: SObjectService<EquipComp>, infoPointCompService: SObjectService<InfoPointComp>,unrecognizedEquipService: SObjectService<UnrecognizedEquip>): Boolean {
        if (equipments == null || equipments.isEmpty())
            return true


        val newEquipmnets = ArrayList<Equipment>()
        val unrecognizedEquips = ArrayList<UnrecognizedEquip>()
        for (obj in equipments) {
            obj.id = CommonService.generateUUID(null, true)
            obj.modelId = baseObj.modelId
            var family: String? = null
            obj.bimId = "${bimIdPrefix}${obj.sourceId}"
            if (obj.revitId != null && obj.revitId!!.isNotEmpty())
                equipMap[obj.revitId!!] = obj
            if (obj.parameters != null) {
                var infos = HashMap<String, String>()

                for (param in obj.parameters!!) {
                    if (param.name.equals("设备本地名称")) {
                        obj.localName = param.value
                    } else if (param.name.equals("设备本地编码")) {
                        obj.localId = param.value
                    } else if (param.name.equals("PropertyID", true)) {
                        obj.propertyId = param.value
                    } else if (param.name.equals("构件分类编码")) {
                        obj.bimTypeID = param.value
                    } else if (param.name.equals("系统类型")) {
                        obj.sysName = param.value
                    }


//                    if (null != family && !param.name.isNullOrEmpty()) {
//                        //信息点编码转换
//                        val infoPointComp = infoPointCompService.select(SFilter.eq("family", family), SFilter.eq("infoPointCode", param.name!!)).entity()
//                        if (infoPointComp != null) {
//                            infos[infoPointComp.sInfoPointCode!!] = param.value ?: ""
//                        } else {
//                            infos[param.name!!] = param.value ?: ""
//                        }
//                    }
                }
                var equipComp: EquipComp? = null

                //bimtypeID转换,设备构建码没有抛弃，查不到抛弃
                if(! obj.bimTypeID.isNullOrEmpty()){
                    if(! obj.sysName.isNullOrEmpty()){
                        equipComp = equipCompService.select(SFilter.eq("bimTypeID",obj.bimTypeID!!), SFilter.eq("sysName",obj.sysName!!)).entity()
                        if(equipComp != null){
                            obj.family = equipComp.classCode?:"XXXXXX"
                        }else{
                            equipComp = equipCompService.select(SFilter.eq("bimTypeID",obj.bimTypeID!!)).entity()
                            if(equipComp != null){
                                obj.family = equipComp.classCode?:"XXXXXX"
                            }else{
                                obj.family = "OTXXXX"
                            }
                            //未识别的设备类型，类型码转换为"OTXXXX",OT表示“其他系统”，“XXXX”表示未识别的设备
                        }
                    }else{
                        equipComp = equipCompService.select(SFilter.eq("bimTypeID",obj.bimTypeID!!)).entity()
                        if(equipComp != null){
                            obj.family = equipComp.classCode?:"XXXXXX"
                        }else{
                            obj.family = "OTXXXX"
                        }
                    }
                    family = obj.family
                    if(!family.isNullOrEmpty()){

                        //信息点编码转换
                        for (param in obj.parameters!!) {
                            if (param.name.equals("设备本地名称")) {

                            } else if (param.name.equals("设备本地编码")) {

                            } else if (param.name.equals("PropertyID", true)) {

                            } else if (param.name.equals("构件分类编码")) {

                            } else if (param.name.equals("系统类型")) {

                            }else{
                                //信息点编码转换
                                val infoPointComp = infoPointCompService.select(SFilter.eq("family", family!!), SFilter.eq("infoPointCode", param.name!!)).entity()
                                if (infoPointComp != null) {
                                    infos[infoPointComp.sInfoPointCode!!] = param.value ?: ""
                                } else {
                                    infos[param.name!!] = param.value ?: ""
                                }
                            }

                        }

                    }else{
                        continue
                    }
                    obj.infos = infos
                    if(("OTXXXX") == family || ("XXXXXX") == family){
                        val unrecognizedEquip =  UnrecognizedEquip()
                        unrecognizedEquip.id = UUID.randomUUID().toString()
                        unrecognizedEquip.bimTypeId = obj.bimTypeID
                        unrecognizedEquip.familyName = obj.familyName
                        unrecognizedEquip.modelId = baseObj.modelId
                        unrecognizedEquip.projectId = baseObj.mbiName
                        unrecognizedEquips.add(unrecognizedEquip)
                    }else{
                        newEquipmnets.add(obj)
                    }

                }
            }
        }
        equipmentService.delete(SFilter.eq("modelId", baseObj.modelId!!))
        unrecognizedEquipService.delete((SFilter.eq("modelId", baseObj.modelId!!)))
        val create = SCreateRequest<Equipment>()
        val createOther = SCreateRequest<UnrecognizedEquip>()
        createOther.content = unrecognizedEquips
        unrecognizedEquipService.createList(createOther)
        create.content = newEquipmnets
//        create.content = equipments
        val result = equipmentService.createList(create)
        return SResponseType.success == result.result
    }

    fun analyzeComponent(componentService: SObjectService<EquipPart>, baseObj: BaseObj<AllComponents>, equipParts: ArrayList<EquipPart>?, bimIdPrefix: String, equipMap: HashMap<String, BaseComponent>): Boolean {
        if (equipParts == null || equipParts.isEmpty())
            return true
        for (obj in equipParts) {
            obj.id = CommonService.generateUUID(null, true)
            obj.modelId = baseObj.modelId
            if (obj.familyName != null && obj.familyName!!.length > 6) {
                obj.family = obj.familyName!!.substring(0, 6)
            }
            if (obj.owner != null && equipMap.containsKey(obj.owner!!)) {
                obj.ownerId = equipMap[obj.owner!!]!!.id
                obj.ownerSourceId = equipMap[obj.owner!!]!!.sourceId
            }
            obj.bimId = "${bimIdPrefix}${obj.sourceId}"
            if (obj.revitId != null && obj.revitId!!.isNotEmpty())
                equipMap[obj.revitId!!] = obj
            if (obj.parameters != null) {
                for (param in obj.parameters!!) {
                    if (param.name.equals("设备本地名称")) {
                        obj.localName = param.value
                    } else if (param.name.equals("设备本地编码")) {
                        obj.localId = param.value
                    } else if (param.name.equals("PropertyID", true)) {
                        obj.propertyId = param.value
                    } else if (param.name.equals("构件分类编码")) {
                        obj.bimTypeID = param.value
                    }
                }
            }
        }
        componentService.delete(SFilter.eq("modelId", baseObj.modelId!!))
        val create = SCreateRequest<EquipPart>()
        create.content = equipParts
        val result = componentService.createList(create)
        return SResponseType.success == result.result
    }

}