package com.zzsn.modules.kgj.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzsn.modules.kgj.common.ResultModel;
import com.zzsn.modules.kgj.entity.BaseDataImage;
import com.zzsn.modules.kgj.entity.SiteType;
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.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

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

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

    @Autowired
    private BaseDataImageMapper imageMapper;

    @Autowired
    RestTemplate restTemplate;

    @Value("paserUrl")
    String paserUrl;

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

    /**
     * 视频图片解析
     * id
     * type
     * content
     *
     * @param
     * @return
     */
    @ApiOperation(value = "视频图片解析")
    @PostMapping(value="/paserMsg")
    public ResultModel paserMsg(@RequestParam("bid") String bid,
                                HttpServletRequest req) throws IOException {


        QueryWrapper<BaseDataImage> wrapper = new QueryWrapper<>();
        wrapper.eq("bid", bid);
        List<BaseDataImage> baseDataImages = imageMapper.selectList(wrapper);
        for (BaseDataImage baseDataImage :
                baseDataImages) {
            String fileId= baseDataImage.getId();
            String dataImage = baseDataImage.getDataImage();
            String type="";
            if(dataImage.contains("mp4")){
                type="video";
            }else if(dataImage.contains("mp3")){
                type="video";
            }else {
                type="image";
            }
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            String parmas = "{ \"type\": \""+type+"\",\"filePath\": \""+dataImage+"\",\"fileId\":" +fileId+"\"}";
            HttpEntity<String> request = new HttpEntity<>(parmas, headers);
            try {
                ResponseEntity<String> response = restTemplate.postForEntity(paserUrl, request, String.class);
                String body = response.getBody();
                JSONObject ob = JSON.parseObject(body);
                body = ob.getString("resultData");

                String text=  ob.getString("text");
                fileId = ob.getString("fileId");

            }catch (Exception e){

            }


        }

        return ResultModel.OK();
    }

    @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, ".");
    }
}
