package com.persagy.server.syn.controllers.obj

import com.persagy.base.extensions.toJson
import com.persagy.database.SFilter
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.datacenter.models.entities.dictnew.DictProject
import com.persagy.server.datacenter.models.entities.dictnew.Group
import com.persagy.server.datacenter.models.entities.objects.*
import com.persagy.server.datacenter.models.entities.rel.RSpinBd
import com.persagy.server.datacenter.models.entities.rel.RSpinFl
import com.persagy.server.syn.models.api.obj.*
import com.persagy.server.syn.models.tools.*
import com.persagy.server.syn.services.dict.DClassDefService
import com.persagy.service.SBaseService
import com.persagy.service.SObjectService
import com.persagy.service.models.enums.SResponseType
import com.persagy.service.models.responses.SBaseResponse
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

/**
 * 对象，中台到数据中心   （项目、建筑、楼层、设备、系统、竖井）
 *
 * @author wx  <zhangweixin@sagacloud.com>
 * @date  2020/10/18 10:06
 */
@Api(tags = ["0003、对象-中台到数据中心"])
@RestController
@RequestMapping("/sync")
class ObjectFromToControllers {
    companion object {
        // 日志
        private val logger = LoggerFactory.getLogger(ObjectFromToControllers::class.java)
    } // Companion object

    /** 集团服务 */
    private val groupService = SBaseService(SMybatisDao(Group::class.java))
    /** 字典项目服务 */
    private val dictProjectService = SBaseService(SMybatisDao(DictProject::class.java))
    /** 数据中心项目服务 */
    private val projectService = SObjectService(SMybatisDao(Project::class.java))
    /** 数据中心建筑服务 */
    private val buildingService = SObjectService(SMybatisDao(Building::class.java))
    /** 数据中心楼层服务 */
    private val floorService = SObjectService(SMybatisDao(Floor::class.java))
    /** 数据中心设备服务 */
    private val equipmentService = SObjectService(SMybatisDao(Equipment::class.java))
    /** 建筑下的空间 */
    private val rSpinBdService = SObjectService(SMybatisDao(RSpinBd::class.java))
    /** 楼层下的空间 */
    private val rSpinFlService = SObjectService(SMybatisDao(RSpinFl::class.java))
    /** 业务空间 */
    private val zoneSpaceService = SObjectService(SMybatisDao(ZoneSpace::class.java))
    /** 系统服务 */
    private val generalSystemService = SObjectService(SMybatisDao(GeneralSystem::class.java))
    /** 竖井 */
    private val shaftService = SObjectService(SMybatisDao(Shaft::class.java))

    /**
     * 项目信息 - 数据中台存储到数据中心，根据集团获取集团写所有项目
     */
    @ApiOperation(value = "项目信息-数据中台存储到数据中心，根据集团获取集团写所有项目 ", notes = "")
    @PostMapping(value = ["/project-syn"])
    fun projectGroupAll(): SBaseResponse {
        return try {
            /** 集团数据 */
            DClassDefService.groupQuerys()
            /** 项目数据 */
            DClassDefService.dictProject()

            val groupList = dictProjectService.selectAll().exec()
            for (group in groupList) {
                val projectQueryList = ProjectApi.projectQuery(group.id!!)

                if (projectQueryList.size > 0) {
                    for (projectQuery in projectQueryList) {
                        val projectDataConversion = ProjectUtil.projectDataConversions(group.groupCode!!, projectQuery)
                        logger.debug("项目：  ${projectDataConversion.toJson()} ")
                        projectService.replace(projectDataConversion)
                    }
                }
            }

            SBaseResponse(SResponseType.success)
        } catch (e: Exception) {
            e.printStackTrace()
            SBaseResponse(SResponseType.failure, e.message!!)
        }

    }

    /**
     * 项目信息 - 数据中台存储到数据中心，根据集团获取集团写所有项目
     */
    @ApiOperation(value = "项目信息-数据中台存储到数据中心，根据 id 同步 ", notes = "")
    @PostMapping(value = ["/project-syn-id"])
    fun projectId(projectId: String): SBaseResponse {
        return try {
            /** 集团数据 */
            DClassDefService.groupQuerys()
            /** 项目数据 */
            DClassDefService.dictProject()
            val dictProject = dictProjectService.select(SFilter.eq("id",projectId)).entity()
                val projectQueryList = ProjectApi.projectQuery(projectId!!)
                if (projectQueryList.size > 0) {
                    for (projectQuery in projectQueryList) {
                        val projectDataConversion = ProjectUtil.projectDataConversions(dictProject!!.groupCode!!, projectQuery)
                        logger.debug("项目：  ${projectDataConversion.toJson()} ")
                        projectService.replace(projectDataConversion)
                    }
                }
            SBaseResponse(SResponseType.success)
        } catch (e: Exception) {
            e.printStackTrace()
            SBaseResponse(SResponseType.failure, e.message!!)
        }

    }




    /**
     * 建筑信息 - 数据中台存储到数据中心
     */
    @ApiOperation(value = "建筑信息-数据中台存储到数据中心 ", notes = "switch true  根据输入的项目 id  同步建筑，false 同步所有项目的 建筑")
    @PostMapping(value = ["/building-syn"])
    fun buildingSyn(projectId: String, switch: Boolean = true): SBaseResponse {
        return try {
            if (switch) {
                val dictProject = dictProjectService.select(SFilter.eq("id", projectId)).entity()
                val buildingSynList = BuildingApi.buildingSyn(projectId,"building")
                if (buildingSynList.size > 0) {
                    for (buildingSyn in buildingSynList) {
                        val buildingDataConversion =
                            BuildingUtil.buildingDataConversions(projectId, dictProject!!.groupCode!!, buildingSyn)
                        logger.debug("建筑：  ${buildingDataConversion.toJson()} ")
                        buildingService.replace(buildingDataConversion)

                    }
                }

            } else {
                /** 查询所有的项目 */
                val projectList = projectService.selectAll().exec()
                for (project in projectList){
                    val dictProject = dictProjectService.select(SFilter.eq("id", project.id!!)).entity()
                    val buildingSynList = BuildingApi.buildingSyn(projectId,"building")
                    if (buildingSynList.size > 0) {
                        for (buildingSyn in buildingSynList) {
                            val buildingDataConversion =
                                BuildingUtil.buildingDataConversions(project.id!!, dictProject!!.groupCode!!, buildingSyn)
                            logger.debug("建筑：  ${buildingDataConversion.toJson()} ")
                            buildingService.replace(buildingDataConversion)
                        }
                    }
                }
            }
            SBaseResponse(SResponseType.success)
        } catch (e: Exception) {
            e.printStackTrace()
            SBaseResponse(SResponseType.failure, e.message!!)
        }

    }


    /**
     * 楼层 - 中台楼层同步到数据中心
     */
    @ApiOperation(value = "楼层信息-数据中台存储到数据中心 ", notes = "switch true  根据输入的项目 id  同步楼层，false 同步所有项目的 楼层")
    @PostMapping(value = ["/floor-syn"])
    fun floorSyn(projectId: String,switch: Boolean = true): SBaseResponse {
        return try {
            if (switch){
                val dictProject = dictProjectService.select(SFilter.eq("id", projectId)).entity()
                val floorSynList = BuildingApi.buildingSyn(projectId, "floor")
                if (floorSynList.size>0) {
                    for (floorSyn in floorSynList){
                        val floor = FloorUtil.floorSyns(projectId, dictProject!!.groupCode!!, floorSyn)
                        val floorInBuildingList = FloorApi.floorInBuilding(projectId, floor.id!!)
                        if (floorInBuildingList.size>0){
                            for (floorInBuilding in floorInBuildingList){
                                val containsKey = floorInBuilding.containsKey("objFrom")
                                if (containsKey){
                                    floor.buildingId = floorInBuilding["objFrom"].toString()
                                    break
                                }
                            }
                        }
                        floorService.replace(floor)
                    }
                }
            } else {
                /** 查询所有的项目 */
                val projectList = projectService.selectAll().exec()
                for (project in projectList){
                    val dictProject = dictProjectService.select(SFilter.eq("id", project.id!!)).entity()
                    val floorSynList = BuildingApi.buildingSyn(projectId, "floor")
                    if (floorSynList.size>0) {
                        for (floorSyn in floorSynList){
                            val floor = FloorUtil.floorSyns(project.id!!, dictProject!!.groupCode!!, floorSyn)
                            val floorInBuildingList = FloorApi.floorInBuilding(projectId, floor.id!!)
                            if (floorInBuildingList.size>0){
                                for (floorInBuilding in floorInBuildingList){
                                    val containsKey = floorInBuilding.containsKey("objFrom")
                                    if (containsKey){
                                        floor.buildingId = floorInBuilding["objFrom"].toString()
                                        break
                                    }
                                }
                            }
                            floorService.replace(floor)
                        }
                    }
                }
            }
            SBaseResponse(SResponseType.success)
        } catch (e: Exception) {
            e.printStackTrace()
            SBaseResponse(SResponseType.failure, e.message!!)
        }
    }


    /**
     * 设备
     *
     * @param projectId         项目 id
     * @param switch            开关
     * @param isBuildingFloor   是否查询楼层
     * @param page              页码
     * @return 返回值
     */
    @ApiOperation(value = "设备信息-数据中台存储到数据中心 ", notes = "switch true  根据输入的项目 id  同步楼层，false 同步所有项目的 楼层")
    @PostMapping(value = ["/equip-syn"])
    fun equipSyn(projectId: String,switch: Boolean = true,isBuildingFloor:Boolean = true,page: Int = 1): SBaseResponse {
        return try {
            var num = page
            if (switch) {
                val dictProject = dictProjectService.select(SFilter.eq("id", projectId)).entity()
                val equipSynApi = EquipApi.equipSynApi(projectId, page)
                val equipDataList = equipSynApi.data
                for (equipData in equipDataList!!){
                    val equipSyn = EquipUtil.equipSyns(projectId, dictProject!!.groupCode!!, equipData)
                    if (isBuildingFloor){
                        /** 查询建筑 */
                        val equipInBuildingList = EquipApi.equipInBuilding(projectId, equipSyn.id!!)
                        if (equipInBuildingList.size>0){
                            val hashMap = equipInBuildingList[0]
                            if (hashMap.containsKey("objTo")){
                                equipSyn.buildingId = hashMap["objTo"].toString()
                            }
                        }
                        /** 查询楼层 */
                        val equipInFloorList = EquipApi.equipInFloor(projectId, equipSyn.id!!)
                        if (equipInFloorList.size>0){
                            val hashMap = equipInFloorList[0]
                            if (hashMap.containsKey("objTo")){
                                equipSyn.floorId = hashMap["objTo"].toString()
                            }
                        }
                        if (equipSyn.buildingId.isNullOrEmpty()){
                            if (!equipSyn.floorId.isNullOrEmpty()){
                                val floor = floorService.select(SFilter.eq("id", equipSyn.floorId!!)).entity()
                                if (floor!=null){
                                    equipSyn.buildingId = floor.buildingId
                                }
                            }
                        }

                    }
                    equipmentService.replace(equipSyn)
                }
                if (equipSynApi.data!!.size>= 1000){
                    num ++
                    equipSyn(projectId,switch,isBuildingFloor,num)
                }
            } else {
                val projectList = projectService.selectAll().exec()
                for (project in projectList){

                    val dictProject = dictProjectService.select(SFilter.eq("id", project.id!!)).entity()
                    val equipSynApi = EquipApi.equipSynApi(project.id!!, page)
                    val equipDataList = equipSynApi.data
                    for (equipData in equipDataList!!){
                        val equipSyn = EquipUtil.equipSyns(projectId, dictProject!!.groupCode!!, equipData)
                        if (isBuildingFloor){
                            /** 查询建筑 */
                            val equipInBuildingList = EquipApi.equipInBuilding(projectId, equipSyn.id!!)
                            if (equipInBuildingList.size>0){
                                val hashMap = equipInBuildingList[0]
                                if (hashMap.containsKey("objTo")){
                                    equipSyn.buildingId = hashMap["objTo"].toString()
                                }
                            }
                            /** 查询楼层 */
                            val equipInFloorList = EquipApi.equipInFloor(projectId, equipSyn.id!!)
                            if (equipInFloorList.size>0){
                                val hashMap = equipInFloorList[0]
                                if (hashMap.containsKey("objTo")){
                                    equipSyn.floorId = hashMap["objTo"].toString()
                                }
                            }
                            if (equipSyn.buildingId.isNullOrEmpty()){
                                if (!equipSyn.floorId.isNullOrEmpty()){
                                    val floor = floorService.select(SFilter.eq("id", equipSyn.floorId!!)).entity()
                                    if (floor!=null){
                                        equipSyn.buildingId = floor.buildingId
                                    }
                                }
                            }
                        }
                        equipmentService.replace(equipSyn)
                    }
                    if (equipSynApi.data!!.size>= 1000){
                        num ++
                        equipSyn(projectId,switch,isBuildingFloor,num)
                    }
                }
            }
            SBaseResponse(SResponseType.success)
        } catch (e: Exception) {
            e.printStackTrace()
            SBaseResponse(SResponseType.failure, e.message!!)
        }
    }

    /**
     * 空间
     *
     * @param projectId         项目 id
     * @param switch            开关
     * @param isBuildingFloor   是否查询建筑楼层
     * @return 返回结果
     */
    @ApiOperation(value = "空间信息-数据中台存储到数据中心 ", notes = "switch true  根据输入的项目 id  空间，false 同步所有项目的 空间")
    @PostMapping(value = ["/space-syn"])
    fun spaceSyn(projectId: String,switch: Boolean = true,isBuildingFloor:Boolean = true): SBaseResponse {
        return try {
            if (switch){
                val dictProject = dictProjectService.select(SFilter.eq("id", projectId)).entity()
                val spaceSynApiList = SpaceApi.spaceSynApi(projectId)
                if (spaceSynApiList.size>0){
                    for (spaceSyn in spaceSynApiList){
                        val spaceDataConversion =
                            SpaceUtil.spaceDataConversions(projectId, dictProject!!.groupCode!!, spaceSyn)

                        zoneSpaceService.replace(spaceDataConversion)
                        if (isBuildingFloor){
                            val spaceInBuildingList = SpaceApi.spaceInBuilding(projectId, spaceDataConversion.id!!)
                            if (spaceInBuildingList.size>0){
                                for (spaceInBuilding in spaceInBuildingList){
                                    val rSpinBd = RSpinBd()
                                    spaceDataConversion.buildingId = spaceInBuilding["objFrom"].toString()
                                    rSpinBd.buildingId = spaceInBuilding["objFrom"].toString()
                                    rSpinBd.projectId = projectId
                                    rSpinBd.sign = 1
                                    rSpinBd.spaceId = spaceDataConversion.id
                                    rSpinBd.objectType = spaceDataConversion.classCode
                                    rSpinBdService.replace(rSpinBd)
                                }
                            }
                            val spaceInFloorList = SpaceApi.spaceInFloor(projectId, spaceDataConversion.id!!)
                            if (spaceInFloorList.size>0){
                                for (spaceInFloor in spaceInFloorList){
                                    val any = spaceInFloor["objFrom"].toString()
                                    val floor =
                                        floorService.select(SFilter.eq("id", spaceInFloor["objFrom"].toString())).entity()
                                    val rSpinFl = RSpinFl()
                                    spaceDataConversion.floorId = spaceInFloor["objFrom"].toString()
                                    rSpinFl.buildingId = floor?.buildingId
                                    rSpinFl.floorId = spaceInFloor["objFrom"].toString()
                                    rSpinFl.objectType = spaceDataConversion.classCode
                                    rSpinFl.projectId = projectId
                                    rSpinFl.sign = 1
                                    rSpinFl.spaceId = spaceDataConversion.id
                                    rSpinFlService.replace(rSpinFl)
                                }
                            }
                            zoneSpaceService.update(spaceDataConversion)
                        }

                    }
                }
            } else {
                /** 查询所有的项目 */
                val projectList = projectService.selectAll().exec()
                for (project in projectList){
                    val projectId = project.id!!
                    val dictProject = dictProjectService.select(SFilter.eq("id", projectId)).entity()
                    val spaceSynApiList = SpaceApi.spaceSynApi(projectId)
                    if (spaceSynApiList.size>0){
                        for (spaceSyn in spaceSynApiList){
                            val spaceDataConversion =
                                SpaceUtil.spaceDataConversions(projectId, dictProject!!.groupCode!!, spaceSyn)

                            zoneSpaceService.replace(spaceDataConversion)
                            if (isBuildingFloor){
                                val spaceInBuildingList = SpaceApi.spaceInBuilding(projectId, spaceDataConversion.id!!)
                                if (spaceInBuildingList.size>0){
                                    for (spaceInBuilding in spaceInBuildingList){
                                        val rSpinBd = RSpinBd()
                                        spaceDataConversion.buildingId = spaceInBuilding["objFrom"].toString()
                                        rSpinBd.buildingId = spaceInBuilding["objFrom"].toString()
                                        rSpinBd.projectId = projectId
                                        rSpinBd.sign = 1
                                        rSpinBd.spaceId = spaceDataConversion.id
                                        rSpinBd.objectType = spaceDataConversion.classCode
                                        rSpinBdService.replace(rSpinBd)
                                    }
                                }
                                val spaceInFloorList = SpaceApi.spaceInFloor(projectId, spaceDataConversion.id!!)
                                if (spaceInFloorList.size>0){
                                    for (spaceInFloor in spaceInFloorList){
                                        val any = spaceInFloor["objFrom"].toString()
                                        val floor =
                                            floorService.select(SFilter.eq("id", spaceInFloor["objFrom"].toString())).entity()
                                        spaceDataConversion.floorId = spaceInFloor["objFrom"].toString()
                                        val rSpinFl = RSpinFl()
                                        rSpinFl.buildingId = floor?.buildingId
                                        rSpinFl.floorId = spaceInFloor["objFrom"].toString()
                                        rSpinFl.objectType = spaceDataConversion.classCode
                                        rSpinFl.projectId = projectId
                                        rSpinFl.sign = 1
                                        rSpinFl.spaceId = spaceDataConversion.id
                                        rSpinFlService.replace(rSpinFl)
                                    }
                                }
                                zoneSpaceService.update(spaceDataConversion)
                            }
                        }
                    }
                }
            }
            SBaseResponse(SResponseType.success)
        } catch (e: Exception) {
            e.printStackTrace()
            SBaseResponse(SResponseType.failure, e.message!!)
        }
    }

    /**
     * 系统
     *
     * @param projectId         项目 id
     * @param switch            开关
     * @param isBuildingFloor   是否查询建筑楼层
     * @return 返回结果
     */
    @ApiOperation(value = "系统信息-数据中台存储到数据中心 ", notes = "switch true  根据输入的项目 id  系统，false 同步所有项目的 系统")
    @PostMapping(value = ["/system-syn"])
    fun systemSyn(projectId: String,switch: Boolean = true,isBuildingFloor:Boolean = true): SBaseResponse {
        return try {
            if (switch) {
                val dictProject = dictProjectService.select(SFilter.eq("id", projectId)).entity()
                val systemQueryList = SystemApi.systemQuery(projectId)
                if (systemQueryList.size>0){
                    for (systemQuery in systemQueryList){
                        val spaceDataConversion =
                            SystemUtil.systemDataConversions(projectId, dictProject!!.groupCode!!, systemQuery)
                        generalSystemService.replace(spaceDataConversion)
                    }
                }
            } else {
                /** 查询所有的项目 */
                val projectList = projectService.selectAll().exec()
                for (project in projectList){
                    val dictProject = dictProjectService.select(SFilter.eq("id", project.id!!)).entity()
                    val systemQueryList = SystemApi.systemQuery(project.id!!)
                    if (systemQueryList.size>0){
                        for (systemQuery in systemQueryList){
                            val spaceDataConversion =
                                SystemUtil.systemDataConversions(project.id!!, dictProject!!.groupCode!!, systemQuery)
                            generalSystemService.replace(spaceDataConversion)
                        }
                    }
                }
            }
            SBaseResponse(SResponseType.success)
        } catch (e: Exception) {
            e.printStackTrace()
            SBaseResponse(SResponseType.failure, e.message!!)
        }
    }

    /**
     * 竖井
     *
     * @param projectId         项目 id
     * @param switch            开关
     * @param isBuildingFloor   是否查询建筑楼层
     * @return 返回结果
     */
    @ApiOperation(value = "竖井信息-数据中台存储到数据中心 ", notes = "switch true  根据输入的项目 id  竖井，false 同步所有项目的 竖井")
    @PostMapping(value = ["/shaft-syn"])
    fun shaftSyn(projectId: String,switch: Boolean = true,isBuildingFloor:Boolean = true): SBaseResponse {
        return try {
            if (switch){
                val dictProject = dictProjectService.select(SFilter.eq("id", projectId)).entity()
                val shaftQueryList = ShaftApi.shaftQuery(projectId)
                if (!shaftQueryList.isNullOrEmpty()) {
                    for (shaftQuery in shaftQueryList) {
                        val shaftDataConversion =
                            ShaftUtil.shaftDataConversions(projectId, dictProject?.groupCode!!, shaftQuery)
                        shaftService.replace(shaftDataConversion)
                    }
                }
            } else {
                /** 查询所有的项目 */
                val projectList = projectService.selectAll().exec()
                for (project in projectList){
                    val dictProject = dictProjectService.select(SFilter.eq("id", project.id!!)).entity()
                    val shaftQueryList = ShaftApi.shaftQuery(project.id!!)
                    if (!shaftQueryList.isNullOrEmpty()) {
                        for (shaftQuery in shaftQueryList) {
                            val shaftDataConversion =
                                ShaftUtil.shaftDataConversions(project.id!!, dictProject?.groupCode!!, shaftQuery)
                            shaftService.replace(shaftDataConversion)
                        }
                    }
                }
            }
            SBaseResponse(SResponseType.success)
        } catch (e: Exception) {
            e.printStackTrace()
            SBaseResponse(SResponseType.failure, e.message!!)
        }
    }
}