package com.zzsn.modules.kgj.controller;

import com.zzsn.modules.kgj.common.ResultModel;
import com.zzsn.modules.kgj.entity.BaseDataImage;
import com.zzsn.modules.kgj.mapper.BaseDataImageMapper;
import com.zzsn.modules.kgj.utils.DateUtil;
import com.zzsn.modules.kgj.utils.FileValidateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 图片上传访问
 */
@Api(tags = "图片上传访问")
@RestController
public class FileController {

    @Autowired
    private BaseDataImageMapper imageMapper;

    // 允许上传图片的格式
    private static final String[] IMAGE_TYPE = new String[] { ".gif", ".jpeg", ".bmp", ".jpg", ".png" };

    @ApiOperation(value = "根据图片ID,访问图片")
    @GetMapping("/image/{id}")
    public void getImg(@PathVariable("id") String id, HttpServletResponse response){
        if(StringUtils.isBlank(id)){
            return;
        }
        if (id.contains("."))
            id = id.substring(0,id.lastIndexOf("."));
        BaseDataImage baseDataImage = imageMapper.queryById(id);
        if(baseDataImage!=null && !(StringUtils.isBlank(baseDataImage.getDataImage()))){
            String dataImage = baseDataImage.getDataImage();
            OutputStream outputStream =null;
            try {
                outputStream = response.getOutputStream();
                // 解密处理数据
                byte[] bytes = new BASE64Decoder().decodeBuffer(dataImage);
                for (int i = 0; i < bytes.length; ++i) {
                    if (bytes[i] < 0) {
                        bytes[i] += 256;
                    }
                }
                outputStream.write(bytes);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (outputStream != null) {
                    try {
                        // 关闭outputStream流
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 上传图片
     * @param file
     * @return
     */
    @ApiOperation(value = "图片上传，返回图片ID")
    @PostMapping(value="/upload/image")
    public ResultModel uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
        if(file.isEmpty()){
            return ResultModel.FAIL("");
        }
        //校验文件是否合法
        boolean flag = FileValidateUtil.validateType(file, IMAGE_TYPE);
        //图片不允许上传
        if(!flag){
            return ResultModel.FAIL("图片格式不正确");
        }
        String path = getFilePath(file.getOriginalFilename());//生成文件名及路径
        String imgUrlToBase64 = new BASE64Encoder().encode(file.getBytes());

        String md5 = DigestUtils.md5DigestAsHex(path.getBytes(StandardCharsets.UTF_8));
        BaseDataImage baseDataImage = new BaseDataImage();
        baseDataImage.setId(md5);
        baseDataImage.setDataImage(imgUrlToBase64);
        imageMapper.save(baseDataImage);

        return ResultModel.OK(baseDataImage.getId());
    }

    private String getFilePath(String sourceFileName) {
        Date nowDate = new Date();
        // 生成新的文件名
        return DateUtil.format(nowDate, "yyyyMMddHHmmssSSS") + RandomUtils.nextInt(100, 9999)
                + "." + StringUtils.substringAfterLast(sourceFileName, ".");
    }
}
