package com.persagy.server.services.objects

import cn.sagacloud.server.datacenter.utils.IdUtils
import cn.sagacloud.server.datacenter.utils.IdUtils.tenantIdCreate
import cn.sagacloud.server.datacenter.utils.ShaftNameUtil
import com.persagy.database.SFilter
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.datacenter.models.entities.logs.DataCenterLogs
import com.persagy.server.datacenter.models.entities.objects.Tenant
import com.persagy.server.datacenter.models.entities.objects.TenantWithCount
import com.persagy.server.datacenter.models.entities.objects.ZoneSpace
import com.persagy.server.services.assistant.ObjInfoService
import com.persagy.server.services.base.Service
import com.persagy.service.SBaseService
import com.persagy.service.SPageContext
import com.persagy.service.models.enums.SResponseType
import com.persagy.service.models.requests.SQueryRequest
import com.persagy.service.models.responses.SQueryResponse
import org.springframework.web.bind.annotation.RequestBody
import java.util.*

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

    /**
     * 创建之前操作
     *
     * @param   tenant  租户对象
     */
    override fun onCreateBefore(tenant: Tenant): Boolean  {
        val projectId = SPageContext.getHeader("ProjectId")
        tenant.projectId = projectId
        if (tenant.id.isNullOrEmpty()){
            tenant.id = tenantIdCreate(projectId!!)
        }

        if (tenant.name.isNullOrEmpty()) {
            tenant.name = ShaftNameUtil.shaftName("租户-")
        }
        return true
    } // Function onCreateBefore()

    /**
     * 查询租户信息-包含统计信息
     *
     * @param       request
     * @return      租户统计信息
     */
    fun queryWithCount(@RequestBody request: SQueryRequest): SQueryResponse<TenantWithCount> {
        val service = SBaseService(SMybatisDao(TenantWithCount::class.java))
        return try {
            val queryBuilder = service.select(request.filters)
                    .filter(SFilter.eq("ProjectId", SPageContext.getHeader("ProjectId")!!))
            if (null != request.projection) {
                queryBuilder.projection(request.projection!!)
            }
            if (null != request.orders) {
                queryBuilder.order(request.orders!!)
            }
            val pageInfo = queryBuilder.pageQuery(request.pageNumber, request.pageSize)
            SQueryResponse(pageInfo)
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, e.message!!)
        }
    } // Function queryWithCount()


    /**
     * 空间是否存在
     *
     * @param       zone       failureList
     * @return      是否存在
     */
    private fun zoneExists(zone: String, failureList: ArrayList<Any>): Boolean {
        val service = SBaseService(SMybatisDao(ZoneSpace::class.java))
        val list = service.select(SFilter.eq("RoomID", zone)).exec()
        if (list.size > 0) {
            return true
        }
        failureList.add(zone)
        return false
    }// Function zoneExists()

    /** 删除之前操作 */
    override fun onDeleteBefore(entity: Tenant): Boolean {
        try {
            val  tenant = this.select(SFilter.eq("id", entity.id!!)).entity()
            val projectId = SPageContext.getHeader("ProjectId")
            val coming = SPageContext.getHeader("Coming")
            val account = SPageContext.getHeader("Account")
            /** 日志 */
            val dataCenterLogs = DataCenterLogs()
            dataCenterLogs.id = IdUtils.uuidCreate()
            dataCenterLogs.author = "dataCenter"
            dataCenterLogs.projectId = projectId
            dataCenterLogs.objectType = entity.objectType
            dataCenterLogs.type = "delete"
            dataCenterLogs.account = account
            dataCenterLogs.coming = coming
            dataCenterLogs.objectId = tenant!!.id
            val hashMap = HashMap<String, Any?>()
            hashMap[entity.objectType!!] = tenant
            dataCenterLogs.dataSource = hashMap
            logService.insert(dataCenterLogs)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return super.onDeleteBefore(entity)
    } // Function onDeleteBefore()


    /**
     * @Description: 创建成功
     */
    override fun onCreateSuccess(entityList: ArrayList<Tenant>) {
        super.onCreateSuccess(entityList)
        for (tenant in entityList) {
            ObjInfoService.createInfo(tenant,true,"VOTn","Tenant")
        }
    }


    /**
     * @Description: 更新信息点
     */
    override fun onUpdateSuccess(entityList: ArrayList<Tenant>) {
        super.onUpdateSuccess(entityList)
        for (tenant in entityList) {
            ObjInfoService.createInfo(tenant,false,"VOTn","Tenant")
        }
    }


    /**
     * @Description:删除成功之后
     */
    override fun onDeleteSuccess(entityList: ArrayList<Tenant>) {
        super.onDeleteSuccess(entityList)

        try {
            val projectId = SPageContext.getHeader("ProjectId")
            for (entity in entityList) {
                ObjInfoService.delete(SFilter.eq("projectId",projectId!!), SFilter.eq("objId",entity.id!!), SFilter.eq("objType","VOTn"))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

} // Object TenantService