package com.persagy.server.service.objects

import com.persagy.database.SFilter
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.datacenter.models.entities.objects.Tenant
import com.persagy.server.models.objects.Building
import com.persagy.server.models.objects.FloorCompon
import com.persagy.server.service.CustomSqlService
import com.persagy.server.service.base.Service
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


/**
 * 租户信息服务
 *
 * @author
 */
object TenantService : Service<Tenant>(SMybatisDao(Tenant::class.java)) {

    /** 自定义sql */
    val customSqlService by lazy {
        SSpringContextUtil.getBean(CustomSqlService::class.java) as CustomSqlService
    }
    val serviceBuilding = SObjectService(SMybatisDao(Building::class.java))
    val serviceFloor = SObjectService(SMybatisDao(FloorCompon::class.java))

    /**
     * 查询楼层空间的数据以及数量
     */
    fun tenantBuildingFloors(tenantId: String,objectType: String): SQueryResponse<Building> {

        return try {
            val projectId = SPageContext.getHeader("ProjectId")
            val buildingList = serviceBuilding.select(SFilter.eq("projectId", projectId!!)).exec()
            if (buildingList.size>0){

                val tenantBuildingFloorList = customSqlService.tenantBuildingFloor(projectId, objectType, tenantId)

                for (building in buildingList){
                    val floorList = serviceFloor.select(SFilter.eq("projectId", projectId!!), SFilter.eq("buildId", building.id!!)).order("sequenceId desc").exec()

                    if (tenantBuildingFloorList.size>0){
                        for (floor in floorList){
                            for (tenantBuildingFloor in tenantBuildingFloorList){
                                if (floor.id == tenantBuildingFloor.id){
                                    floor.count = tenantBuildingFloor.count
                                    building.count = 1
                                }
                            }

                        }
                    }

                    building.floor = floorList
                }
            }
            val sQueryResponse = SQueryResponse<Building>(SResponseType.success)
            sQueryResponse.content = buildingList
            sQueryResponse.total = buildingList.size.toLong()
            sQueryResponse
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, e.message!!)
        }

    } // Function tenantBuildingFloors()


} // Object TenantService