package com.zhiqiyun.open.router.apis;

import com.dliyun.oap.framework.annotation.ServiceMethod;
import com.dliyun.oap.framework.annotation.ServiceMethodBean;
import com.dliyun.oap.framework.response.OapResponse;
import com.zhiqiyun.open.core.models.UploadResult;
import com.zhiqiyun.open.core.service.UploadFileInfoService;
import com.zhiqiyun.open.mvc.Result;
import com.zhiqiyun.open.mvc.params.UploaderBase64Param;
import com.zhiqiyun.open.router.request.UploaderBase64Request;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.IOException;

@Slf4j
@ServiceMethodBean
public class UploadApi {
	@Autowired
	private UploadFileInfoService uploadFileInfoService;

	@ServiceMethod(method = "uploader.handle.base64File", title = "文件上传")
	public OapResponse handleBase64File(@RequestBody UploaderBase64Request request) throws IOException {

		byte[] fileBuff = Base64.decodeBase64(request.getBase64File());

		String originalFilename = request.getFilename();
		if (StringUtils.isBlank(originalFilename)) {
			originalFilename = String.format("%s.%s", DigestUtils.md5Hex(fileBuff), "png");
		}

		UploadResult uploadResult = this.uploadFileInfoService.handle(originalFilename, fileBuff);

		if (uploadResult.isSuccess()) {
			return OapResponse.success().setBody(uploadResult);
		} else {
			return OapResponse.fail("UPLOAD_FAIL", uploadResult.getMessage());
		}
	}
}
