package com.persagy.meiku.controller

import com.persagy.meiku.models.pic.Picture
import com.persagy.meiku.services.pic.PictureService
import com.sybotan.base.extensions.toJson
import com.sybotan.database.SFilter
import com.sybotan.service.models.enums.SResponseType
import com.sybotan.service.models.responses.SBaseResponse
import com.sybotan.service.models.responses.SCreateResponse
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.tags.Tag
import lombok.extern.slf4j.Slf4j
import org.slf4j.LoggerFactory
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import java.io.IOException
import java.util.*
import javax.servlet.ServletOutputStream
import javax.servlet.http.HttpServletResponse

/**
 * 图片接口
 *
 * @author wx
 */
@Tag(name = "006、图片接口")
@RestController
@RequestMapping("/picture")
@Slf4j
class PictureController {

    companion object {
        /** 日志 */
        private val logger = LoggerFactory.getLogger(PictureController::class.java)
    } // Companion object

    /**
     * 上传图片
     *
     * @param   file         图片文件
     * @param   uid          图片id
     * @return              创建结果信息
     */
   @Operation(summary = "上传图片", description = "")
    @PostMapping(value = ["/upload"])
    fun create(@RequestParam(value = "file", required = true) file: MultipartFile, @RequestParam(required = false) id: String?): SCreateResponse<String> {
        var response = SCreateResponse<String>()
        try {
            val picture = Picture()
            if(id.isNullOrEmpty()){
                picture.id = UUID.randomUUID().toString().replace("-","")
            }else{
                PictureService.delete(SFilter.eq("id",id!!))
                picture.id = id
            }
            picture.pic = file.bytes
            logger.debug("name："+file.name)
            logger.debug("长度："+file.size)
            PictureService.insert(picture)
            response.result = SResponseType.success
            response.entityList = arrayListOf(picture.id!!)
        } catch (e: Exception) {
            response.result = SResponseType.failure
            response.message = e.message.toString()
            e.printStackTrace()
        }
        return response
    } // Function create()

    /**
     * 根据id删除图片
     *
     * @param   idList      id数组
     * @return              删除的结果信息
     */
    @Operation(summary = "根据id删除图片信息", description = "")
    @PostMapping(value = ["/delete"])
    fun delete(@RequestBody idList: ArrayList<Picture>): SBaseResponse {
        return PictureService.deleteByKeysList(idList)
    } // Function delete()

    /**
     * 查询图片信息
     *
     * @param   id             查询条件id
     * @return                 查询结果
     */
    @Operation(summary = "查询图片信息", description = "")
    @GetMapping(value = ["/query/{id}"])
    fun query(@RequestParam id: String,response: HttpServletResponse) {
//        val picture = PictureService.select(SFilter.eq("id", id)).entity()
        val picture = PictureService.customSql.loadPic(id)
        if(picture!=null){
            response.contentType = "image/svg+xml;charset=UTF-8"
            response.addHeader("Accept-Ranges","bytes")
            // 将图像输出到Servlet输出流中
            val sos: ServletOutputStream
            try {
                response.setContentLength(picture.pic!!.size);
                sos = response.outputStream
                sos.write(picture.pic!!)
                sos.close()
                response.flushBuffer()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }else{
            throw RuntimeException("图片不存在")
        }
        logger.debug(picture?.toJson())

    } // Function query()

    /**
     * 查询图片信息
     *
     * @param   request        查询条件
     * @return                 查询结果
     */
    @Operation(summary = "查询图片信息", description = "")
    @GetMapping(value = ["/query01/{id}"])
    fun querys(@PathVariable("id") id: String): ResponseEntity<ByteArray> {
        val picture = PictureService.customSql.loadPic(id)
        if(picture!=null){
            val buffer: ByteArray = Base64.getMimeDecoder().decode(picture.pic!!)
            return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(buffer)
        }else{
            throw RuntimeException("图片不存在")
        }

    } // Function query()

} //