package io.renren.modules.sys.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import io.renren.common.utils.MailUtils;
import io.renren.common.utils.R;
import io.renren.modules.sys.entity.SysEmailEntity;
import io.renren.modules.sys.form.SysEmailForm;
import io.renren.modules.sys.service.SysEmailService;
import io.renren.modules.sys.controller.AbstractController;

/**
 * Captcha by huwhois time 2019/11/22
 */
@RestController
@RequestMapping("/sys/mail")
@Configuration
public class SysEmailController extends AbstractController  {
    @Value("${fyhs-meeting.file.datapath}")
    private String dataPath; // 读取配置文件中的指定目录

    @Value("${fyhs-meeting.file.uploadFolder}")
    private String uploadFolder; // 读取配置文件中的指定目录

    @Autowired
	private SysEmailService sysEmailService;
    
    @PostMapping("sendEmailTest")
    public R sendEmailTest() {
        String[] toEmail = {"3146695982@qq.com", "282188280@qq.com"};
        String subject = "Spring-boot Email 测试";
        String text = "<h2>测试<h2><p>这是一个测试</p>";
        String[] filename = {"测试.txt", "测试2.txt"};

        File file1 = new File(dataPath + uploadFolder + "/documents/" + "23123.txt");
        File file2 = new File(dataPath + uploadFolder + "/documents/" + "23123.txt");
        File[] file = {file1, file2};

        MailUtils.sendMail(toEmail, subject, text, filename, file);
        return R.ok();
    }

    @PostMapping("send")
    public R sendEmail(@RequestBody String[] emails) {
        SysEmailEntity sysEmail = sysEmailService.getById(1);
        if (emails.length == 0) {
            return R.error("邮箱不能为空");
        }

        String[] toEmail = emails;
        String subject = sysEmail.getSubject();
        String text = sysEmail.getText();
        String filename = sysEmail.getFilename();
        String[] filenames = filename.split(",");
        String  fileurl = sysEmail.getFileurl();
        String[] fileurls = fileurl.split(",");
        File[] files = new File[fileurls.length];
        for (int i = 0; i < fileurls.length; i++) {
            files[i] = new File(dataPath + fileurls[i]);
        }

        MailUtils.sendMail(toEmail, subject, text, filenames, files);
        return R.ok();
    }

    @PostMapping("update")
    public R update(@RequestBody SysEmailForm sysEmail) {
        SysEmailEntity email = new SysEmailEntity();
        email.setId(1L);
        email.setSubject(sysEmail.getSubject());
        email.setText(sysEmail.getText());
        email.setFilename(StringUtils.join(sysEmail.getFilename(), ","));
        email.setFileurl(StringUtils.join(sysEmail.getFileurl(), ","));
        
        sysEmailService.updateById(email);
        return R.ok();
    }

    @PostMapping("/upload")
    public R upload(@RequestParam(value = "upload_file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return R.error("文件不能为空");
        }
                
        String fileOldName = file.getOriginalFilename();
        // 上传的附件不允许是 exe、sh 或 bat 等中的格式
        if (fileOldName.contains(".exe") || fileOldName.contains(".sh") || fileOldName.contains(".bat")) {
            return R.error("上传文件失败, 不允许是 exe、sh 或 bat文件");
        }
        try {
            String useUploadPath = uploadFolder + "/documents"; // 文件上传使用的目录
            String dir = dataPath + useUploadPath; // 文件绝对路径
            
            File createFile = new File(dir);
            if (!createFile.exists()) {// 判断文件是否存在如果不存在则自动创建文件夹
                createFile.mkdir();
            }

            String uuid = UUID.randomUUID().toString().replace("-", "");// 随机生成一个唯一性的id 文件不重名
            String suffix = fileOldName.substring(fileOldName.lastIndexOf(".") + 1);
            String newFilename = uuid + "." + suffix;
            File f = new File(dir + newFilename);
            if (f.exists()) {
                return R.error("上传的文件已经存在,则提示用户重新上传附件或者重命名");
            } else {
                file.transferTo(f); // 将上传的文件写入到系统中
                return R.ok().put("filename", fileOldName).put("fileurl", useUploadPath + newFilename);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("文件上传出错");
        }
    }
}