/*
 * ********************************************************************************************************************
 *
 *                      :*$@@%$*:                         ;:                ;;    ;;
 *                    :@@%!  :!@@%:                       %!             ;%%@@%$ =@@@@@@@%;     @%@@@%%%%@@@@@
 *                   :@%;       :$=                       %%$$$%$$         ;$$  ;$@=   !@$
 *                   =@!                                  %!              @ $=;%   !@@@%:      !$$$$$$$$$$$$$$=
 *                   =@*                                  %!              @ $= % %@=   =%@!      %=
 *              *$%%! @@=        ;=$%%%$*:                %!              @ $= % =%%%%%%@$      *%:         =%
 *            %@@!:    !@@@%=$@@@@%!  :*@@$:              %!              @ $= % $*     ;@      @*          :%*
 *          ;@@!          ;!!!;:         ;@%:      =======@%========*     @ $$ % $%*****$@     :@$=*********=@$
 *          $@*   ;@@@%=!:                *@*
 *          =@$    ;;;!=%@@@@=!           =@!
 *           %@$:      =@%: :*@@@*       %@=                    Copyright (c) 2016-2019.  北京上格云技术有限公司
 *            ;%@@$=$@@%*       *@@@$=%@@%;
 *               ::;::             ::;::                                              All rights reserved.
 *
 * ********************************************************************************************************************
 */
package com.persagy.server.sso

import com.persagy.base.extensions.toJson
import com.persagy.server.models.Project
import com.persagy.server.models.responses.TokenCheckResponse
import com.persagy.server.models.responses.UserInfoResponse
import com.persagy.service.SPageContext
import com.persagy.service.models.requests.SQueryRequest
import com.persagy.service.models.responses.SQueryResponse
import com.persagy.service.utils.SJsonUtil
import com.persagy.service.utils.SSpringContextUtil
import org.slf4j.LoggerFactory
import org.springframework.core.ParameterizedTypeReference
import org.springframework.http.HttpEntity
import org.springframework.http.converter.StringHttpMessageConverter
import org.springframework.web.client.RestTemplate
import java.nio.charset.StandardCharsets

object UserService {
    // 日志
    private val logger = LoggerFactory.getLogger(UserService::class.java)
    private const val DATACENTER = "http://DATACENTER"
//    private const val DATACENTER = "http://GUANCHENG-DATACENTER"
//    val opts: Opts by lazy {
//        SSpringContextUtil.getBean(Opts::class.java) as Opts
//    } // opts

    /**
     * 获得用户信息
     */
    fun userInfo(): UserInfoResponse {
        val user = SPageContext.getAttribute("User") as TokenCheckResponse?
        val resp = UserInfoResponse()
        try {
            logger.debug("项目= ${user?.toJson()}")
            val projResp = projectList(user!!.projects!!)

            // 获得项目
            for (pj in projResp!!.content!!) {
                val proj = Project(pj.id!!, "", pj.localName)
                resp.projects.add(proj)
            }

            resp.userId = user.id
            resp.username = user.userName
            resp.permissions = arrayListOf("system:role:query", "system:role:create", "system:user:create",
                    "system:user:delete",
                    "database:hbase:query",
                    "system:role:query",
                    "system:user:query",
                    "database:redis:query",
                    "system:role:setOpts",
                    "system:role:update",
                    "system:user:update")
            logger.debug("userInfo = ${resp.toJson()}")
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return resp
    } // Function userInfo()

    /**
     * 项目列表
     *
     * @param   ids     项目ID列表
     * @return  从数据中心取得项目列表
     */
    fun projectList(ids: ArrayList<String>): SQueryResponse<Project>? {
        val restTemplate = SSpringContextUtil.getBean(RestTemplate::class.java) as RestTemplate
        restTemplate.messageConverters[1] = StringHttpMessageConverter(StandardCharsets.UTF_8)
        val req = SQueryRequest()
        req.filters = "id in ["
        for ((index, id) in ids.withIndex()) {
            if (index > 0) {
                req.filters += ", "
            }
            req.filters += "'$id'"
        }
        req.filters += "]"
        SQueryRequest.maxRow = 100000
        req.pageSize = 100000
        val request = HttpEntity(req)
        val pt = object : ParameterizedTypeReference<SQueryResponse<Project>>() {}
        val r = restTemplate.postForObject("$DATACENTER/datacenter/project/query", req, String::class.java)
        @Suppress("UNCHECKED_CAST")
        return SJsonUtil.fromJson(r!!, pt.type) as SQueryResponse<Project>
    } // Function projectList()

} // Object UserService
