package cn.sh.stc.sict.theme.common.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.sh.stc.sh.cloud.common.minio.service.MinioTemplate;
import cn.sh.stc.sict.cloud.common.core.util.R;
import cn.sh.stc.sict.theme.common.model.HphyAttachment;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/file")
@Api(value = "file", tags = "文件上传管理模块")
public class FileController {
    private final MinioTemplate minioTemplate;

    /**
     * 上传文件
     * 文件名采用uuid,避免原始文件名中带"-"符号导致下载的时候解析出现异常
     *
     * @param file 资源
     * @return R(bucketName, filename)
     */
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file,
                    @RequestParam("bucketName") String bucketName) {
        if (!minioTemplate.getBucketNames().contains(bucketName)) {
            return new R().error("非法的bucketName！");
        }
        String fileName = IdWorker.getIdStr() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
        HphyAttachment attachment = new HphyAttachment();
        try {
            minioTemplate.putObject(bucketName, fileName, file.getInputStream());
            attachment.setBucketName(bucketName);
            attachment.setUuidName(fileName);
            attachment.setName(file.getOriginalFilename());
            attachment.setType(FileUtil.extName(file.getOriginalFilename()));
            attachment.setSize(String.valueOf(file.getSize()));
            return new R(attachment);
        } catch (Exception e) {
            log.error("上传失败", e);
            return new R().error(e.getMessage());
        }
    }

    @ApiOperation("多文件上传")
    @PostMapping("/batch/upload")
    public R handleFileUpload(HttpServletRequest request) {
        try {
            List<MultipartFile> fileList = ((MultipartHttpServletRequest) request).getFiles("file");
            if (CollectionUtil.isEmpty(fileList)) {
                return new R().error("上传的文件列表不能为空！");
            }
            if (fileList.size() > 5) {
                return new R().error("上传失败，一次最多上传5个文件！");
            }
            String bucketName = request.getParameter("bucketName");
            if (!minioTemplate.getBucketNames().contains(bucketName)) {
                return new R().error("非法的bucketName！");
            }

            List<HphyAttachment> attachmentList = new ArrayList<>();

            for (MultipartFile file : fileList) {
                String fileName = IdWorker.getIdStr() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
                HphyAttachment attachment = new HphyAttachment();
                minioTemplate.putObject(bucketName, fileName, file.getInputStream());
                attachment.setBucketName(bucketName);
                attachment.setUuidName(fileName);
                attachment.setName(file.getOriginalFilename());
                attachment.setType(FileUtil.extName(file.getOriginalFilename()));
                attachment.setSize(String.valueOf(file.getSize()));
                attachmentList.add(attachment);
            }
            return new R().success(attachmentList);
        } catch (Exception e) {
            log.error("多文件上传失败！失败原因：【{}】，失败原因详情：【{}】", e.toString(), e.getMessage());
            return new R().error(e.getMessage());
        }
    }

    /**
     * 获取文件
     *
     * @param fileName 文件空间-名称
     * @param response
     * @return
     */
    @GetMapping("/{fileName}")
    public void file(@PathVariable String fileName, HttpServletResponse response) {
        String[] nameArray = StrUtil.split(fileName, StrUtil.DASHED);

        try (InputStream inputStream = minioTemplate.getObject(nameArray[0], nameArray[1])) {
            response.setContentType("application/octet-stream; charset=UTF-8");
            IoUtil.copy(inputStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("文件读取异常", e);
        }
    }

    // public static void main(String[] args) {
        // appid = "wx83895a8250e891f0";
        // secretKey = "4926930da6795ecc43f911e81a8e384a";
        // token = "sict@hp@guide@2020"
        // System.out.println(IdWorker.get32UUID());
//        String xml = "<xml>\n" +
//                "  <ToUserName><![CDATA[gh_a91bd9d9f6d1]]></ToUserName>\n" +
//                "  <FromUserName><![CDATA[12324]]></FromUserName>\n" +
//                "  <CreateTime>1348831860</CreateTime>\n" +
//                "  <MsgType><![CDATA[text]]></MsgType>\n" +
//                "  <Content><![CDATA[30岁高血压]]></Content>\n" +
//                "  <MsgId>1234567890123456</MsgId>\n" +
//                "</xml>";
//
//        String body = HttpRequest.post("http://www.365jqr.com/jqrsvr.ashx?Command=talk_66")
//                .body(xml)
//                .execute()
//                .body();
//
//        System.out.println(body);
    // }
}
