package com.nantian.cloud.jljc.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nantian.cloud.jljc.entity.TTraining;
import com.nantian.cloud.jljc.entity.TTrainingVideo;
import com.nantian.cloud.jljc.service.TTrainingService;
import com.nantian.cloud.jljc.service.TTrainingVideoService;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import com.nantian.sc.cloud.common.minio.MinioProperties;
import com.nantian.sc.cloud.common.minio.service.MinioTemplate;
import com.nantian.sc.cloud.common.security.annotation.Inner;
import io.minio.MinioClient;
import io.minio.errors.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.xmlpull.v1.XmlPullParserException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static com.nantian.cloud.jljc.vo.util.FileUtil.getFileSize;


/**
 * 培训活动
 *
 * @date 2020-09-03 13:23:34
 */
@Slf4j
@CrossOrigin
@AllArgsConstructor
@Api(value = "ttrainingVideo", tags = "培训活动")
@RestController
@RequestMapping("/ttrainingVideo")
public class TTrainingVideoController {
    @Autowired
    private TTrainingVideoService tTrainingVideoService;
    @Autowired
    private TTrainingService tTrainingService;

    private final MinioTemplate minioTemplate;

    @Autowired
    private MinioProperties properties;


    /**
     * 列表
     */
    @SysLog("上传培训文件")
    @ApiOperation(value = "上传文件", notes = "上传文件")
    @PostMapping("/uploadFile")
    @ApiImplicitParam(name = "files", value = "文件", required = true)
    public R uploadFile(HttpServletRequest request,@RequestParam("downState")String downState,@RequestParam("trainingId")Integer trainingId, @RequestParam("files") MultipartFile[] files) throws Exception{
        try {
            if(files!=null && files.length >0){
                for (int i=0;i<files.length;i++){
                    MultipartFile file = files[i];
                    //上传文件
                    String uuid = UUID.randomUUID().toString();
                    InputStream inputStream = file.getInputStream(); //得到文件流
                    String fileName = file.getOriginalFilename(); //文件名
                    //minioTemplate.putObject("jljc", uuid, inputStream);
                    minioTemplate.putObject("jljc", uuid, inputStream, inputStream.available(), "application/octet-stream");
                    //获取文件大小
                    String fileSize = getFileSize(file.getSize());
                    //获取文件名称（不含文件后缀）
                    String[] strings = fileName.split("\\.");
                    String newFileName = strings[0];
                    //获取文件后缀
                    String fileSuffix = strings[strings.length - 1];
                    System.out.println(fileSuffix);
                    //fileName + "<" + uuid   文件名、uuid的拼接
                    TTrainingVideo tTrainingVideo=new TTrainingVideo();
                    tTrainingVideo.setFileBlob(fileName + "<" + uuid);
                    tTrainingVideo.setTrainingId(trainingId);
                    TTraining tTraining = tTrainingService.getById(trainingId);
                    tTrainingVideo.setDelFlag("1");
                    tTrainingVideo.setUpdateTime(new Date());
                    tTrainingVideo.setEndTime(tTraining.getEndTime());
                    tTrainingVideo.setStartTime(tTraining.getStartTime());
                    if ("jpg".equals(fileSuffix) || "jpeg".equals(fileSuffix)|| "png".equals(fileSuffix)){
                        tTrainingVideo.setType("2");
                    }else if("xls".equals(fileSuffix)|| "xlsx".equals(fileSuffix)|| "doc".equals(fileSuffix) || "docx".equals(fileSuffix)|| "ppt".equals(fileSuffix)|| "pptx".equals(fileSuffix)){
                        tTrainingVideo.setType("3");
                    }else {
                        tTrainingVideo.setType("1");
                    }
                    tTrainingVideo.setDownState(downState);
                    tTrainingVideo.setRemarks(tTraining.getRemarks());
                    tTrainingVideoService.save(tTrainingVideo);
                }
            }else {
                return R.failed("未选择文件!");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.ok("上传成功");
    }
    /**
     * 根据uuidStr下载文件
     */
    @Inner(value = false)
    @SneakyThrows
    @GetMapping("/download2")
    @SysLog("根据uuidStr下载培训文件")
    @ApiOperation(value = "根据uuidStr下载文件", notes = "根据uuidStr下载文件（uuidStr为文件名、uuid的拼接）")
    @ApiImplicitParam(name = "uuidStr", value = "文件名和uuid字符串", required = true, dataType = "string", paramType = "path")
    public R download2(String uuidStr, HttpServletResponse response) {
        if (uuidStr == null || "".equals(uuidStr)) {
            return R.ok("文件下载失败，uuidStr不能为空！");
        }

        //uuidStr   文件名<uuid
        String[] split = uuidStr.split("<");
        String uuid = split.length == 2 ? split[1] : ""; //uuid
        if ("".equals(uuid)) {
            return R.ok("文件下载失败，参数不是整个uuidStr！");
        }

        //InputStream fileInputStream = minioTemplate.getObject("jljc", split[1]);
        MinioClient minioClient = new MinioClient(properties.getUrl(), properties.getAccessKey(), properties.getSecretKey());
        InputStream object = minioClient.getObject("jljc", uuid);
        byte buf[] = new byte[1024];
        int length = 0;
        response.reset();

        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(split[0], "UTF-8"));
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        OutputStream outputStream = response.getOutputStream();
        while ((length = object.read(buf)) > 0) {
            outputStream.write(buf, 0, length);
        }
        outputStream.close();
        return null;

    }

    @SneakyThrows
    @Inner(value = false)
    @GetMapping("/onlinePreview")
    @SysLog("根据uuidStr在线预览培训文件")
    @ApiOperation(value = "根据uuidStr在线预览文件", notes = "根据uuidStr在线预览文件（uuidStr为文件名、uuid的拼接）")
    public R onlinePreview(String uuidStr, HttpServletResponse response) throws IOException, InvalidPortException, InvalidEndpointException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InvalidExpiresRangeException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException {
        if (uuidStr == null || "".equals(uuidStr)) {
            return R.ok("文件预览失败，uuidStr不能为空！");
        }

        //uuidStr   文件名<uuid
        String[] split = uuidStr.split("<");
        String uuid = split.length == 2 ? split[1] : ""; //uuid
        if ("".equals(uuid)) {
            return R.ok("文件预览失败，参数不是整个uuidStr！");
        }

        String fileName = split[0]; //文件名
        String[] strings = fileName.split("\\.");
        String fileSuffix = strings[strings.length - 1];  //文件后缀
        System.err.println("文件名称：" + fileName + "，文件后缀：" + fileSuffix + "，文件名称：" + strings[0]);

        //InputStream fileInputStream = minioTemplate.getObject("jljc", uuid);
        MinioClient minioClient = new MinioClient(properties.getUrl(), properties.getAccessKey(), properties.getSecretKey());
        InputStream fileInputStream = minioClient.getObject("jljc", uuid);

        if ("png".equals(fileSuffix) || "jpg".equals(fileSuffix) || "gif".equals(fileSuffix) || "jpeg".equals(fileSuffix)) {
            // 读取图片字节数组
            /*System.err.println("文件大小（字节）=" + fileInputStream.available());
            byte[] data = new byte[fileInputStream.available()];

            fileInputStream.read(data);
            fileInputStream.close();
            String base64Str = Base64.getEncoder().encodeToString(data);
            System.err.println("图片的base64编码：" + "data:image/png;base64," + base64Str);
            return  R.ok("data:image/png;base64," + base64Str);*/
            response.setContentType("image/jpeg;charset=utf-8");
            OutputStream sos = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len;
            while ((len = fileInputStream.read(buf)) > 0) {
                sos.write(buf, 0, len);
            }
            response.flushBuffer();
            fileInputStream.close();
            sos.close();
            return null;
        } else if ("xls".equals(fileSuffix) || "xlsx".equals(fileSuffix)) {
            return R.ok("excel文件");
        } else if ("doc".equals(fileSuffix) || "docx".equals(fileSuffix)) {
            return R.ok("word文件");
        } else if ("ppt".equals(fileSuffix)|| "pptx".equals(fileSuffix)) {
            return R.ok("ppt文件");
        } else if ("pdf".equals(fileSuffix)) {
            response.setContentType("application/pdf;charset=utf-8");
            OutputStream sos = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len;
            while ((len = fileInputStream.read(buf)) > 0) {
                sos.write(buf, 0, len);
            }
            response.flushBuffer();
            fileInputStream.close();
            return null;
        } else {
            return R.ok("该文件需下载查看！");
        }
    }

    /**
     * 删除
     */
    @SysLog("删除培训文件")
    @ApiOperation(value = "删除培训文件", notes = "删除培训文件")
    @DeleteMapping("/delete")
    public R delete(Integer id) {
        TTrainingVideo tTrainingVideo = tTrainingVideoService.getById(id);
        if(tTrainingVideo==null) {
            return R.failed("删除失败，培训文件不存在！");
        }
        tTrainingVideo.setDelFlag("4");
        tTrainingVideo.setUpdateTime(new Date());
        return R.ok(tTrainingVideoService.updateById(tTrainingVideo));
    }
    /**
     * 查询
     */
    @SysLog("根据培训iD查询文件")
    @ApiOperation(value = "根据培训iD查询文件", notes = "根据培训iD查询文件")
    @PostMapping("/query")
    public R query(@RequestParam("trainingId") Integer trainingId) {
        List<TTrainingVideo> list= tTrainingVideoService.list(new QueryWrapper<>(new TTrainingVideo())
        .eq("training_id",trainingId));
        return R.ok(list);
    }

}
