package com.mortals.xhx.base.system.upload.web;


import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.web.BaseController;
import com.mortals.xhx.base.system.upload.service.UploadService;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Title: 上传文件</p>
 * <p>Description: UploadfileController  </p>
 * <p>Copyright: Copyright &reg;  </p>
 * <p>Company: </p>
 *
 * @author
 * @version 1.0.0
 */
@RestController
@RequestMapping("file")
public class UploadController extends BaseController {

    @Resource
    private UploadService uploadService;

    @RequestMapping(value = "upload")
        public String doFileUpload(HttpServletRequest request, HttpServletResponse response, UploadForm form) {
        Map<String, Object> model = new HashMap<>();
        String jsonStr = "";
        try {
            String filePath = uploadService.saveFileUpload(form.getUploadFile(), form.getPrePath(), getCurUser());
            model.put("url", filePath);
            model.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            jsonStr = JSONObject.toJSONString(model);
        } catch (AppException e) {
            log.debug(e);
            model.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            model.put(KEY_RESULT_MSG, e.getMessage());
            jsonStr = JSONObject.toJSONString(model);
        } catch (Exception e) {
            doException(request, "上传文件", new HashMap<>(3), e);
            model.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            model.put(KEY_RESULT_MSG, "文件上传失败");
            jsonStr = JSONObject.toJSONString(model);
        }
        return jsonStr;
    }
}