package com.cm.common.plugin.controller.routes.file;

import com.cm.common.base.AbstractController;
import com.cm.common.config.properties.FileProperties;
import com.cm.common.constants.ISystemConstant;
import com.cm.common.exception.FileException;
import com.cm.common.exception.ParamsException;
import com.cm.common.exception.SearchException;
import com.cm.common.plugin.service.file.IFileService;
import com.cm.common.result.ErrorResult;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @ClassName: FileController
 * @Description: 文件
 * @Author: WangGeng
 * @Date: 2019/3/11 2:45 PM
 * @Version: 1.0
 **/
@Api(tags = ISystemConstant.API_TAGS_SYSTEM_PREFIX + "文件管理接口")
@Controller
@RequestMapping(ISystemConstant.ROUTE_PREFIX + "/file")
public class FileRouteController extends AbstractController {

    @Autowired
    private IFileService fileService;
    @Autowired
    private FileProperties fileProperties;

    @ApiOperation(value = "打开文件上传", notes = "打开文件上传接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uploadType", value = "文件类型,1:文件,2:图片,3:视频,4:音频", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("uploadfile/{uploadType}")
    public ModelAndView uploadFile(@PathVariable("uploadType") String uploadType) throws ParamsException {
        ModelAndView mv = new ModelAndView("file/file-upload");
        return getUploadFileModelAndView(mv, uploadType);
    }

    @ApiOperation(value = "打开文件上传V2", notes = "打开文件上传V2接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uploadType", value = "文件类型,1:文件,2:图片,3:视频,4:音频", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("uploadfile/v2/{uploadType}")
    public ModelAndView uploadFileV2(@PathVariable("uploadType") String uploadType) throws ParamsException {
        ModelAndView mv = new ModelAndView("file/file-upload-v2");
        return getUploadFileModelAndView(mv, uploadType);
    }

    private ModelAndView getUploadFileModelAndView(ModelAndView mv, String uploadType) throws ParamsException {
        if (!IFileService.UPLOAD_FILE_TYPE.equals(uploadType) &&
                !IFileService.UPLOAD_IMAGE_TYPE.equals(uploadType) &&
                !IFileService.UPLOAD_VIDEO_TYPE.equals(uploadType) &&
                !IFileService.UPLOAD_AUDIO_TYPE.equals(uploadType)) {
            throw new ParamsException("参数错误");
        }
        if (IFileService.UPLOAD_FILE_TYPE.equals(uploadType)) {
            mv.addObject("uploadPath", "uploadfile");
            mv.addObject("updateInputName", "file");
            mv.addObject("allowFiles", fileProperties.getFileTypes());
        }
        if (IFileService.UPLOAD_IMAGE_TYPE.equals(uploadType)) {
            mv.addObject("uploadPath", "uploadimage");
            mv.addObject("updateInputName", "image");
            mv.addObject("allowFiles", fileProperties.getImageTypes());
        }
        if (IFileService.UPLOAD_VIDEO_TYPE.equals(uploadType)) {
            mv.addObject("uploadPath", "uploadvideo");
            mv.addObject("updateInputName", "video");
            mv.addObject("allowFiles", fileProperties.getVideoTypes());
        }
        if (IFileService.UPLOAD_AUDIO_TYPE.equals(uploadType)) {
            mv.addObject("uploadPath", "uploadaudio");
            mv.addObject("updateInputName", "audio");
            mv.addObject("allowFiles", fileProperties.getAudioTypes());
        }
        mv.addObject("uploadType", uploadType);
        mv.addObject("maxFileCount", fileProperties.getMaxFileCount());
        return mv;
    }

    /**
     * 上传图片
     *
     * @return
     */
    @GetMapping("uploadimage")
    public ModelAndView uploadImage() {
        Map<String, Object> params = requestParams();
        ModelAndView mv = new ModelAndView("file/image-upload");
        return getUploadImageModelAndView(mv, params);
    }

    /**
     * 上传图片版本2
     *
     * @return
     */
    @GetMapping("uploadimage/v2")
    public ModelAndView uploadImageV2() {
        Map<String, Object> params = requestParams();
        ModelAndView mv = new ModelAndView("file/image-upload-v2");
        return getUploadImageModelAndView(mv, params);
    }

    private ModelAndView getUploadImageModelAndView(ModelAndView mv, Map<String, Object> params) {
        if (!StringUtils.isBlank(params.get("fileId") == null ? null : params.get("fileId").toString())) {
            mv.addObject("fileId", params.get("fileId"));
        } else {
            mv.addObject("fileId", "");
        }
        return mv;
    }

    @ApiOperation(value = "下载文件", notes = "下载文件接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "isOpen", value = "是否打开,true和false", paramType = "path"),
            @ApiImplicitParam(name = "fileId", value = "文件ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("downloadfile/{isOpen}/{fileId}")
    public void downLoadFile(HttpServletRequest request, HttpServletResponse response, @PathVariable("isOpen") String isOpen, @PathVariable("fileId") String fileId) throws FileException, ParamsException {
        if (!ISystemConstant.IS_TRUE.equals(isOpen) && !ISystemConstant.IS_FALSE.equals(isOpen)) {
            throw new ParamsException("参数错误");
        }
        if (fileId.indexOf(".") > 0) {
            fileId = fileId.split("\\.")[0];
        }
        Map<String, Object> params = requestParams();
        params.put("fileId", fileId);
        params.put("isOpen", isOpen);
        fileService.downLoadFile(request, response, params);
    }

    /**
     * 显示文件
     *
     * @param type
     * @param fileId
     * @return
     */
    @GetMapping("showfile/{type}/{fileId}")
    public ModelAndView showFile(@PathVariable("type") String type, @PathVariable("fileId") String fileId) {
        ModelAndView mv = new ModelAndView("file/show-file");
        mv.addObject("type", type);
        mv.addObject("fileId", fileId);
        return mv;
    }

}
