package com.tiesheng.core.controller.tool;


import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.tiesheng.annotation.token.TokenIgnore;
import com.tiesheng.core.pojos.dto.ImageCodeDTO;
import com.tiesheng.core.pojos.vo.PicVerifyVo;
import com.tiesheng.core.service.FileUploadService;
import com.tiesheng.core.service.TimedCacheService;
import com.tiesheng.util.pojos.ApiResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 工具类
 *
 * @author hao
 */
@RestController
@RequestMapping("/tool")
public class ToolController {

    @Autowired
    TimedCacheService timedCacheService;
    @Autowired
    FileUploadService fileUploadService;


    /**
     * 图片验证码
     *
     * @return
     */
    @TokenIgnore
    @GetMapping("/code/image")
    public ApiResp<PicVerifyVo> picVerifyV2(ImageCodeDTO dto) {

        LineCaptcha lineCaptcha = dto.lineCaptcha();
        PicVerifyVo vo = new PicVerifyVo();
        vo.setBase64(lineCaptcha.getImageBase64Data());
        vo.setKey(IdUtil.simpleUUID());
        timedCacheService.setImageCode(vo.getKey(), lineCaptcha.getCode());

        return ApiResp.respOK(vo);
    }


    /**
     * 上传整个文件
     *
     * @param file
     * @return
     */
    @TokenIgnore
    @PostMapping("/file/whole_upload")
    public ApiResp<String> fileWholeUpload(@RequestParam("file") MultipartFile file) {
        String filePath = fileUploadService.saveMultipartFile(file);
        return ApiResp.respOK(filePath);
    }


    /**
     * 上传超大文件，建议超过20M的使用这个方法
     *
     * @return
     */
    @TokenIgnore
    @PostMapping(value = "/file/chunk_start")
    public ApiResp<String> fileChunkStart(String fileExt) {
        fileUploadService.chunkStart(fileExt);
        return ApiResp.respOK("");
    }


    /**
     * 校验文件块
     *
     * @return
     */
    @TokenIgnore
    @PostMapping("/file/chunk_check")
    public ApiResp<Boolean> fileChunkCheck(String fileMd5, Integer chunk) {
        boolean exist = fileUploadService.chunkCheck(fileMd5, chunk);
        return ApiResp.respOK(exist);
    }


    /**
     * 上传文件块
     *
     * @return
     */
    @TokenIgnore
    @PostMapping("/file/chunk_upload")
    public ApiResp<String> fileChunkUpload(@RequestParam("file") MultipartFile file, String fileMd5, Integer chunk) {
        fileUploadService.chunkUpload(file, fileMd5, chunk);
        return ApiResp.respOK("");
    }


    /**
     * 合并文件
     *
     * @param fileMd5
     * @return
     */
    @TokenIgnore
    @PostMapping("/file/chunk_merge")
    public ApiResp<String> fileChunkMerge(String fileMd5) {
        String path = fileUploadService.chunkMerge(fileMd5);
        return ApiResp.respOK(path);
    }


}
