package ink.wgink.module.file.controller.api.v2;

import ink.wgink.common.base.DefaultBaseController;
import ink.wgink.interfaces.consts.ISystemConstant;
import ink.wgink.module.file.enums.UploadTypeEnum;
import ink.wgink.module.file.pojo.dtos.FileInfoDTO;
import ink.wgink.module.file.pojo.dtos.v2.FileUploadSuccessDTO;
import ink.wgink.module.file.service.v2.IFileService;
import ink.wgink.pojo.ListPage;
import ink.wgink.pojo.result.ErrorResult;
import ink.wgink.pojo.result.SuccessResult;
import ink.wgink.pojo.result.SuccessResultData;
import ink.wgink.pojo.result.SuccessResultList;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

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 + "文件接口-V2")
@RestController("fileControllerV2")
@RequestMapping(ISystemConstant.API_PREFIX + "/file/v2")
public class FileController extends DefaultBaseController {

    @Autowired
    private IFileService fileService;

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

    @ApiOperation(value = "上传文件", notes = "上传文件接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件name", paramType = "query")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("upload-file-inputstream")
    public SuccessResultData<FileUploadSuccessDTO> uploadFileInputStream(@RequestParam("file") MultipartFile file) throws IOException {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:7008/study/api/file/v2/upload-file";
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        InputStreamResource inputStreamResource = new InputStreamResource(file.getInputStream()) {
            @Override
            public String getFilename() {
                return file.getOriginalFilename();
            }

            @Override
            public long contentLength() {
                return file.getSize();
            }
        };
        params.add("file", inputStreamResource);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        System.out.println(result);
        return new SuccessResultData<>();
    }

    @ApiOperation(value = "上传文件", notes = "上传文件接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件name", paramType = "query")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("upload-file-bytearray")
    public SuccessResultData<FileUploadSuccessDTO> uploadFileByteArray(@RequestParam("file") MultipartFile file) throws IOException {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:7008/study/api/file/v2/upload-file";
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        ByteArrayResource fileAsResource = new ByteArrayResource(file.getBytes()) {
            @Override
            public String getFilename() {
                return file.getOriginalFilename();
            }

            @Override
            public long contentLength() {
                return file.getSize();
            }
        };
        params.add("file", fileAsResource);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        System.out.println(result);
        return new SuccessResultData<>();
    }

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

    @ApiOperation(value = "上传视频", notes = "上传视频接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "video", value = "文件video", paramType = "query")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("upload-video")
    public SuccessResultData<FileUploadSuccessDTO> uploadVideo(@RequestParam("video") MultipartFile video) {
        return uploadSingle(video, UploadTypeEnum.VIDEO);
    }

    @ApiOperation(value = "上传音频", notes = "上传音频接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "audio", value = "文件audio", paramType = "query")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("upload-audio")
    public SuccessResultData<FileUploadSuccessDTO> uploadAudio(@RequestParam("audio") MultipartFile audio) {
        return uploadSingle(audio, UploadTypeEnum.AUDIO);
    }

    @ApiOperation(value = "删除文件", notes = "删除文件接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ID列表，用下划线分隔", paramType = "path", example = "1_2_3")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @DeleteMapping("delete/{ids}")
    public synchronized SuccessResult delete(@PathVariable("ids") String ids) {
        fileService.delete(Arrays.asList(ids.split("\\_")));
        return new SuccessResult();
    }

    @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")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listpage")
    public SuccessResultList<List<FileInfoDTO>> listPage(ListPage page) {
        Map<String, Object> params = requestParams();
        page.setParams(params);
        return fileService.listPage(page);
    }

    /**
     * 上传文件
     *
     * @param uploadFile
     * @return
     */
    private SuccessResultData<FileUploadSuccessDTO> uploadSingle(MultipartFile uploadFile, UploadTypeEnum uploadTypeEnum) {
        return new SuccessResultData<>(fileService.uploadSingle(uploadFile, uploadTypeEnum));
    }

}
