package tech.glinfo.enbao.modules.oss.controller;

import tech.glinfo.enbao.common.utils.ConfigConstant;
import tech.glinfo.enbao.common.utils.R;
import tech.glinfo.enbao.modules.oss.cloud.CloudStorageConfig;
import tech.glinfo.enbao.modules.oss.cloud.OSSFactory;
import tech.glinfo.enbao.modules.oss.cloud.QiniuCloudStorageService;
import tech.glinfo.enbao.modules.sys.service.SysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("oss")
@Api(value = "云存储OSS",description="云存储OSS相关接口")
public class OssController {
    @Autowired
    private SysConfigService sysConfigService;

	/**
	 * 获取上传文件token
	 */
	@GetMapping("/getToken")
	@ApiOperation("获取token")
	public R getToken() {

		//获取云存储配置信息
		CloudStorageConfig config = sysConfigService.getConfigObject(ConfigConstant.CLOUD_STORAGE_CONFIG_KEY, CloudStorageConfig.class);

		QiniuCloudStorageService qiniuCloudStorageService = new QiniuCloudStorageService(config, null);

		return R.ok().put("token", qiniuCloudStorageService.getToken()).put("domain", config.getQiniuDomain());
	}


	/**
	 * 上传文件
	 */
	@PostMapping("/upload")
	@ApiOperation("上传文件")
	public R upload(@RequestParam("file") MultipartFile file) throws Exception {
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);
		return R.ok().put("url", url);
	}
}
