package com.nantian.cloud.jljc.controller;


import cn.hutool.core.text.StrBuilder;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.nantian.cloud.jljc.entity.TOperation;
import com.nantian.cloud.jljc.service.TOperationService;
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 com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import io.minio.MinioClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.UUID;

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

@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/tOperation")
@Api(value = "TOperation", tags = "操作手册")
public class TOperationController {
    private final MinioTemplate minioTemplate;
    private final MinioProperties minioProperties;
    private final TOperationService tOperationService;


    /**
     * 根据编码获取模板文件
     */
    @SneakyThrows
    @Inner(value = false)
    @GetMapping("/getByCode")
    @SysLog("根据编码获取模板文件")
    @ApiOperation(value = "根据编码获取模板文件", notes = "根据编码获取模板文件")
    @ApiImplicitParam(name = "code", value = "编码", required = true, dataType = "int", paramType = "path")
    public R getByCode(String type, HttpServletResponse response) {
        TOperation tOperation = new TOperation();
//        tOperation.setCode(code);
//        tOperation.setFileType(type);
        tOperation.setDelFlag("1");
        List<TOperation> moduleFileList = tOperationService.list(Wrappers.query(tOperation).in("file_type",type.split(",")));
        if (moduleFileList == null || moduleFileList.size()==0) {
            return R.failed("文件不存在，下载模板文件失败！");
        } else {
            for (TOperation moduleFile : moduleFileList) {
                String[] split = moduleFile.getFileUrl().split("<");

                MinioClient minioClient = new MinioClient(minioProperties.getUrl(), minioProperties.getAccessKey(), minioProperties.getSecretKey());
                InputStream object = minioClient.getObject("jljc", split[1]);
                int length = 0;
                byte buf[] = new byte[1024];

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


    /**
     * 更新模板文件
     */
    @PostMapping("/update")
    @SysLog("更新模板文件")
    @ApiOperation(value = "更新模板文件", notes = "更新模板文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "模板文件（文件流）", required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "tModuleFile", value = "模板文件信息", required = true, dataType = "int", paramType = "path")
    })
    public R getByAdvancedFileDto(MultipartFile file, TOperation tOperation) throws Exception {

        if (file == null) {
            return R.failed("模板文件不存在，上传文件失败！");
        }

        ScUser u = SecurityUtils.getUser();
        TOperation old = new TOperation();
        old.setCode(tOperation.getCode());
        old.setDelFlag("1");
        old = tOperationService.getOne(Wrappers.query(old));
        if(old!=null){ //code存在，修改
            tOperation.setId(old.getId());
        }else{ //新增
            tOperation.setDeptId(u.getDeptId());
            tOperation.setDelFlag("1");
        }
        tOperation.setUserid(u.getId());
        tOperation.setUpdateTime(new Date());

        //上传文件
        String uuid = UUID.randomUUID().toString();
        InputStream inputStream = file.getInputStream(); //得到文件流
        String fileName = file.getOriginalFilename();    //文件名（含后缀）
        minioTemplate.putObject("jljc", uuid, inputStream, inputStream.available(), "application/octet-stream");
        tOperation.setFileUrl(fileName + "<" + uuid);

        //文件大小
        tOperation.setFileSize(getFileSize(file.getSize()));
        //文件名称（不含文件后缀）
        if(tOperation.getFileName()==null){
            String[] strings = fileName.split("\\.");
            String[] strings1 = fileName.split("." + strings[strings.length - 1]);
            tOperation.setFileName(strings1[0]);
        }

        boolean flag = tOperationService.saveOrUpdate(tOperation);
        return flag ? R.ok(fileName + "<" + uuid) : R.ok(false);
    }
}
