package com.storlead.mail.controller;

import com.alibaba.fastjson.JSONObject;
import com.storlead.framework.common.util.DateUtils;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.common.result.Result;
import com.storlead.mail.pojo.entity.MailTempAttachmentEntity;
import com.storlead.mail.pojo.entity.SmtpPopSettingsEntity;
import com.storlead.mail.properties.MailFileProperties;
import com.storlead.mail.service.MailTempAttachmentService;
import com.storlead.mail.service.SmtpPopSettingsService;
import com.storlead.mail.util.FileHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FilenameUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2024-08-10 09:14
 */
@RestController
@RequestMapping("/mail/file")
@Api(tags = "邮件: 邮件管理")
@Log4j2
public class MaiAttachmentApiController {

    @Resource
    private MailFileProperties mailFileProperties;
    @Resource
    private SmtpPopSettingsService smtpPopSettingsService;
    @Resource
    private MailTempAttachmentService tempAttachmentService;

    @PostMapping(value = "/cache_mail_file")
    @ApiOperation(value = "缓存需要上传的附件" )
    public Result<?> cacheMailFile(@RequestParam("files") List<MultipartFile> files) {
        Result result = new Result();

        try {
            List<JSONObject> res = new ArrayList<>();

            for (MultipartFile file : files) {
                Long currentUserId = LoginUserUtil.getCurrentUserId();
                SmtpPopSettingsEntity smtpPop = smtpPopSettingsService.getDefaultSmtpPop(currentUserId);
                String recipient = DateUtils.date2Str(new Date(), DateUtils.yyyyMMdd);
                String downloadDir = mailFileProperties.getPath().getPath() + File.separator + smtpPop.getEmailAddress() + File.separator + recipient + File.separator;
                JSONObject jsonObject = new JSONObject();
                Long fileId = tempAttachmentService.saveTempAttachment(file, downloadDir, null);
                if (Objects.isNull(fileId)) {
                    return Result.error("上传错误");
                }
                jsonObject.put("id", fileId);
                jsonObject.put("fileShowName", file.getOriginalFilename());
                jsonObject.put("fileName", FilenameUtils.getBaseName(file.getOriginalFilename()));
                jsonObject.put("fileSize", file.getSize());
                jsonObject.put("fileSizeName", FileHelper.formatFileSize(file.getSize()));
                jsonObject.put("fileExt", FilenameUtils.getExtension(file.getOriginalFilename()));
                res.add(jsonObject);
            }
            return Result.result(res);

        } catch (Exception e) {
            log.error("--upload -- error =", e);
            return Result.error("上传错误");
        }
    }

    @PostMapping(value = "/cache_image_file")
    @ApiOperation(value = "缓存图片文件" )
    public Map cacheImageFile(@RequestParam("upload") MultipartFile file) {
        Map jsonObject = new HashMap();
        try {
            Long currentUserId = LoginUserUtil.getCurrentUserId();
            String downloadDir = mailFileProperties.getPath().getJpeg();
            MailTempAttachmentEntity tempAttachment = tempAttachmentService.saveTempImageAttachment(file, downloadDir);
            if (Objects.isNull(tempAttachment) || Objects.isNull(tempAttachment.getId())) {
                return jsonObject;
            }
            String fileName =  tempAttachment.getFileName()+"."+tempAttachment.getFileExt();
            jsonObject.put("id", tempAttachment.getId());
            jsonObject.put("fileName", fileName);
            jsonObject.put("uploaded", 1);
            jsonObject.put("url", "/sales/mail/file/images/"+fileName);
            return jsonObject;
        } catch (Exception e) {
            log.error("--upload -- error =", e);
            return jsonObject;
        }
    }

    @PostMapping(value = "/download_mail_file")
    @ApiOperation(value = "下载临时附件" )
    public void downLoadMailFile(Long fileId, HttpServletResponse response) {
        try {
            MailTempAttachmentEntity resource = tempAttachmentService.getById(fileId);
            String downloadDir = mailFileProperties.getPath().getPath() +resource.getFilePath();
            InputStream inputStream = new BufferedInputStream(new FileInputStream(downloadDir));
            response.reset();
            response.setContentType("application/octet-stream;charset=utf-8");
            /*
             * 跨域配置
             * */
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type");

            String filename = resource.getFileName()+"."+resource.getFileExt();
            filename = filename.replace(" ","");
            response.addHeader("content-disposition",
                    "attachment;filename=" + URLEncoder.encode(filename, "UTF-8")
                            + ";filename*=utf-8''" + URLEncoder.encode(filename, "UTF-8"));

            ServletOutputStream outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
//从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
            while ((len = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
            inputStream.close();
            outputStream.close();

        } catch (Exception e) {
            log.error("--upload -- error =", e);
        }
    }

    @GetMapping("/images/{imageName}")
    public ResponseEntity<FileSystemResource> getImage(@PathVariable String imageName) {

        String downloadDir = mailFileProperties.getPath().getJpeg();
        FileSystemResource resource = new FileSystemResource(downloadDir + imageName);
        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_JPEG)  // 根据图片类型调整
                .body(resource);
    }
}
