package cclotus.cloud.gateway

import cclotus.weixin.api.service.WxAppLoginService
import cclotus.weixin.api.service.WxDemoService
import cclotus.weixin.util.WeixinError
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.http.server.reactive.ServerHttpRequest
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.ResponseBody

@Controller
class DemoController {

    @Autowired
    private lateinit var service: WxDemoService

    @Autowired
    private lateinit var wxa: WxAppLoginService

    /**
     * 功能演示
     */
    @GetMapping("/test/get_api_domain_ip")
    @ResponseBody
    @Throws(WeixinError::class)
    fun getApiDomainIp(appid: String): ResponseEntity<*> {
        val ret = service.getApiDomainIp(appid)
        return ResponseEntity.ok(ret)
    }

    @GetMapping("/test/code2session")
    @ResponseBody
    @Throws(WeixinError::class)
    fun login(appid: String, js_code: String): ResponseEntity<*> {
        val ret = wxa.code2Session(appid, js_code)
        return ResponseEntity.ok(ret)
    }

    @ExceptionHandler(Throwable::class)
    @ResponseBody
    private fun handleError(ex: Throwable, request: ServerHttpRequest): ResponseEntity<String> {
        log.warn("[WXAPI] ERROR: {}", ex.message)
        if (log.isTraceEnabled) {
            ex.printStackTrace()
        }
        var msg = ex.message
        val isJson = request.headers.accept.contains(MediaType.APPLICATION_JSON)
        if (isJson) {
            msg = if (ex is WeixinError) {
                ex.toJsonString()
            } else {
                String.format("{ \"errcode\": -1, \"errmsg\": \"%s\" }", msg)
            }
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .contentType(MediaType.APPLICATION_JSON)
                .body(msg)
        }
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(msg)
    }

    companion object {
        val log: Logger = LoggerFactory.getLogger(DemoController::class.java)
    }
}