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

import com.alibaba.fastjson.JSONObject;
import com.cm.common.base.AbstractController;
import com.cm.common.config.properties.FileProperties;
import com.cm.common.constants.ISystemConstant;
import com.cm.common.enums.UploadTypeEnum;
import com.cm.common.exception.RemoveException;
import com.cm.common.exception.SearchException;
import com.cm.common.exception.base.SystemException;
import com.cm.common.plugin.pojo.dtos.file.FileInfoDTO;
import com.cm.common.plugin.service.file.IFileService;
import com.cm.common.pojo.ListPage;
import com.cm.common.pojo.dtos.FileDTO;
import com.cm.common.result.ErrorResult;
import com.cm.common.result.SuccessResult;
import com.cm.common.result.SuccessResultData;
import com.cm.common.result.SuccessResultList;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: FileController
 * @Description: 文件处理
 * @Author: WangGeng
 * @Date: 2019/3/10 7:03 PM
 * @Version: 1.0
 **/
@Api(tags = ISystemConstant.API_TAGS_SYSTEM_PREFIX + "文件管理接口")
@RestController
@RequestMapping(ISystemConstant.API_PREFIX + "/file")
public class FileController extends AbstractController {

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

    @ApiOperation(value = "文件分页列表", notes = "文件分页列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "int", defaultValue = "1"),
            @ApiImplicitParam(name = "rows", value = "显示数量", paramType = "query", dataType = "int", defaultValue = "20"),
            @ApiImplicitParam(name = "keywords", value = "关键字", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query", dataType = "String")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listpagefileinfo")
    public SuccessResultList<List<FileInfoDTO>> listPageFileInfo(ListPage page) throws SearchException {
        Map<String, Object> params = requestParams();
        page.setParams(params);
        return fileService.listPageFileInfo(page);
    }

    @ApiOperation(value = "删除文章类别(id列表)", notes = "删除文章类别(id列表)接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ID列表，用下划线分隔", paramType = "path", example = "1_2_3")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @DeleteMapping("removefile/{isRemoveSource}/{ids}")
    public synchronized SuccessResult removeFile(@PathVariable() Integer isRemoveSource, @PathVariable("ids") String ids) throws RemoveException {
        if (isRemoveSource == 0) {
            fileService.removeFile(ids);
        }
        if (isRemoveSource == 1) {
            fileService.deleteFile(ids);
        }
        return new SuccessResult();
    }

    @ApiOperation(value = "上传文件", notes = "上传文件接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件name", paramType = "query")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("uploadfile")
    public SuccessResultData<String> uploadFile(@RequestParam("file") MultipartFile file) throws SystemException {
        Map<String, Object> params = requestParams();
        return uploadSingle(file, UploadTypeEnum.FILE, params);
    }

    @ApiOperation(value = "上传图片", notes = "上传图片接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "image", value = "文件name", paramType = "query")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("uploadimage")
    public SuccessResultData<String> uploadImage(@RequestParam("image") MultipartFile image) throws SystemException {
        Map<String, Object> params = requestParams();
        return uploadSingle(image, UploadTypeEnum.IMAGE, params);
    }

    @ApiOperation(value = "上传视频", notes = "上传视频接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "video", value = "文件video", paramType = "query")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("uploadvideo")
    public SuccessResultData<String> uploadVideo(@RequestParam("video") MultipartFile video) throws SystemException {
        if (fileProperties.getMediaMaxDuration() != null && fileProperties.getMediaMaxDuration().getBackend() != null) {
            fileService.checkVideoDurationAllow(video, fileProperties.getMediaMaxDuration().getBackend().getVideo());
        }
        Map<String, Object> params = requestParams();
        return uploadSingle(video, UploadTypeEnum.VIDEO, params);
    }

    @ApiOperation(value = "上传音频", notes = "上传音频接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "audio", value = "文件audio", paramType = "query")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("uploadaudio")
    public SuccessResultData<String> uploadAudio(@RequestParam("audio") MultipartFile audio) throws SystemException {
        if (fileProperties.getMediaMaxDuration() != null && fileProperties.getMediaMaxDuration().getBackend() != null) {
            fileService.checkAudioDurationAllow(audio, fileProperties.getMediaMaxDuration().getBackend().getAudio());
        }
        Map<String, Object> params = requestParams();
        return uploadSingle(audio, UploadTypeEnum.AUDIO, params);
    }

    @ApiOperation(value = "文件列表", notes = "文件列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "id列表，逗号分隔", paramType = "query")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listfilebyfileid")
    public List<FileDTO> listFileByFileId(@RequestParam("ids") String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        return fileService.listFileByFileId(idList);
    }

    /**
     * 上传文件
     *
     * @param uploadFile
     * @param params
     * @return
     */
    private SuccessResultData<String> uploadSingle(MultipartFile uploadFile, UploadTypeEnum uploadTypeEnum, Map<String, Object> params) throws SystemException {
        return fileService.uploadSingle(uploadFile, uploadTypeEnum, params);
    }

    /**
     * 百度富文本编辑器
     *
     * @param file
     * @return
     * @throws IOException
     * @throws SystemException
     */
    @RequestMapping("ueditor")
    public JSONObject uEditor(MultipartFile file, HttpServletRequest request) throws IOException, SystemException {
        Map<String, Object> params = requestParams();
        return fileService.uEditor(file, request, params);
    }

    @ApiOperation(value = "上传图片", notes = "上传图片接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "image", value = "文件name", paramType = "query")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("wangeditorimage")
    public JSONObject wangEditorImage(MultipartFile image, HttpServletRequest request) {
        Map<String, Object> params = requestParams();
        return fileService.wangEditorImage(image, UploadTypeEnum.IMAGE, params);
    }

}
