package com.imdroid.beidou.controller;

import com.imdroid.beidou.common.HttpResult;
import com.imdroid.beidou.utils.AliyunOssUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 文件上次接口
 *
 * @author LiGang
 */
@RestController
@RequestMapping("/file")
public class OssFileController {

    @Autowired
    private AliyunOssUtils aliyunOssUtils;

    /**
     * 上传文件通用接口
     *
     * @param multipartFile multipartFile
     * @return HttpResult
     * @throws Exception
     */
    @RequestMapping("/upload")
    public HttpResult upload(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        String originFilename = multipartFile.getOriginalFilename();
        if (originFilename == null) {
            originFilename = ".file";
        }
        String suffix = originFilename.substring(originFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString().replace("-", "") + suffix;
        String url = aliyunOssUtils.uploadFile(multipartFile, filename, "common");
        return HttpResult.success(url);
    }


    /**
     * 上传设备现场安装图片，保存到oss
     *
     * @param multipartFile multipartFile
     * @return HttpResult
     * @throws IOException
     */
    @RequestMapping("/upload-device-image")
    public HttpResult upload(@RequestParam("file") MultipartFile multipartFile, String deviceId) throws Exception {
        System.out.println("upload device image:" + multipartFile.getOriginalFilename());
        if (StringUtils.isEmpty(deviceId)) {
            return HttpResult.fail("设备编号不能为空");
        }

        String filename = deviceId + "_" + UUID.randomUUID().toString().replace("-", "") +  ".jpg";
        String url = aliyunOssUtils.uploadFile(multipartFile, filename, "device-img");
        return HttpResult.success(url);
    }

    /**
     * 删除oss上面的文件
     *
     * @param url 图片访问链接
     * @return HttpResult
     */
    @RequestMapping(value = "/delete")
    public HttpResult delete(String url) {
        System.out.println("delete file:" + url);
        aliyunOssUtils.deleteFile(url);
        return HttpResult.success(null);
    }
}
