package com.wsm.admin.api;

import com.alibaba.fastjson.JSONObject;
import com.wsm.common.api.BaseController;
import com.wsm.common.util.AjaxJson;
import com.wsm.common.util.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Controller
public class FileController extends BaseController {

    @Value("${web.upload.file.path}")
    private String path;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping(value = "/upload/file", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson uploadFile(HttpServletRequest req, MultipartFile file) {
        String newFileName = null;
        try {
            newFileName = FileUtils.uploadFile(req, file, path);
        } catch (Exception e) {
            logger.error("系统异常：", e);
            return AjaxJson.failure("系统异常：" + e);
        }
        return AjaxJson.success("SUCCESS", newFileName);
    }

    @RequestMapping(value = "/upload/audio", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson uploadAudio(HttpServletRequest req, MultipartFile file) {
        String fileName= null;
        try {
            fileName = FileUtils.uploadFile(req, file, path + "audio/");
            fileName = "/audio" + fileName;
        } catch (Exception e) {
            logger.error("系统异常：", e);
            return AjaxJson.failure("系统异常：" + e);
        }
        return AjaxJson.success("SUCCESS", fileName);
    }

    @RequestMapping(value = "/upload/image", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject uploadImage(HttpServletRequest req, MultipartFile upfile) {
        String newFileName = null;
        try {
            newFileName = FileUtils.uploadFile(req, upfile, path);
        } catch (Exception e) {
            logger.error("系统异常：", e);
            JSONObject error = new JSONObject();
            error.put("code", -1);
            return error;
        }
//        String src = server + newFileName;
        JSONObject data = new JSONObject();
        data.put("name", newFileName);
        data.put("originalName", upfile.getOriginalFilename());
        data.put("size", upfile.getSize());
        data.put("state", "SUCCESS");
        data.put("type", getFileExt(upfile.getOriginalFilename()));
        data.put("url", newFileName);

        return data;
    }

    private String getFileExt(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }
}
