package com.project.zcustom.controller.engineering;

import com.project.common.config.ProjectConfig;
import com.project.common.core.controller.BaseController;
import com.project.common.core.domain.AjaxResult;
import com.project.common.utils.file.FileUploadUtils;
import com.project.zcustom.domain.addional.LargeIssue;
import com.project.zcustom.domain.addional.LargePlan;
import com.project.zcustom.service.unit.ILargeIssueService;
import com.project.zcustom.service.unit.ILargePlanService;
import com.project.zcustom.service.unit.ILargeProjectService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Objects;

@RestController
@RequestMapping("/large/check")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class PlatProjectCheckController extends BaseController {

    private final ILargeProjectService largeProjectService;

    private final ILargeIssueService largeIssueService;

    private final ILargePlanService largePlanService;

    @Value("${upload.directory}")
    private String uploadDirectory;

    /**
     * 邮件发送接口
     */
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 邮件发送人
     */
    @Value("${spring.mail.username}")
    private String sender;

    /**
     * 问题数量
     */
    @GetMapping("/getIssueNum/{appOrg}")
    public AjaxResult getIssueNum(@PathVariable String appOrg) {
        return AjaxResult.success("查询成功", largeIssueService.getIssueNum(appOrg));
    }

    /**
     * 已整改问题数量
     */
    @GetMapping("/getOverIssueNum/{appOrg}")
    public AjaxResult getOverIssueNum(@PathVariable String appOrg) {
        return AjaxResult.success("查询成功", largeIssueService.getOverIssueNum(appOrg));
    }

    /**
     * 本周检查项目数量
     */
    @GetMapping("/getProjectNumThisWeek/{appOrg}")
    public AjaxResult getProjectNumThisWeek(@PathVariable String appOrg) {
        return AjaxResult.success("查询成功", largeProjectService.getProjectNumThisWeek(appOrg));
    }

    /**
     * 近一周问题列表
     */
    @GetMapping("/getIssueListLastWeek/{appOrg}")
    public AjaxResult getIssueListLastWeek(@PathVariable String appOrg,
                                           @RequestParam(required = false, name = "day") Date day,
                                           @RequestParam(required = false, name = "status") Integer status) {
        return AjaxResult.success("查询成功", largeIssueService.getIssueListLastWeek(appOrg, day,status));
    }

    /**
     * 问题列表
     * */
    @GetMapping("/issueList")
    public AjaxResult issueList(LargeIssue entity) {
        return AjaxResult.success("查询成功", largeIssueService.selectList(entity));
    }

    /**
     * 更改问题状态
     * */
    @PostMapping("/changeIssueStatus")
    public AjaxResult changeIssueStatus(@RequestPart("issue") LargeIssue entity, @RequestPart(value = "file",required = false) MultipartFile file) {
        try {
            if (Objects.nonNull(file)) {
                // 上传文件路径
                String filePath = ProjectConfig.getUploadPath();
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                entity.setImagePath("/uploadPath" + fileName.substring(8));
            }
        }catch (Exception e){
        }
        return toAjax(largeIssueService.updateById(entity));
    }

    /**
     * 新增问题
     * */
    @PostMapping("/add")
    public AjaxResult add(@RequestPart("issue") LargeIssue entity, @RequestPart(value = "file" , required = false) MultipartFile multipartFile) {
        if (!multipartFile.isEmpty()) {
            try {
                String originalFilename = multipartFile.getOriginalFilename();
                /*Path path = Paths.get(uploadDirectory, originalFilename);

                Files.createDirectories(path.getParent());
                multipartFile.transferTo(path);
                entity.setImagePath(path.toString());*/

            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error("文件上传失败");
            }

            // TODO 发生邮箱待调试
            //enclosureEmail(multipartFile, entity.getDescription() + "\n" + entity.getNeed());
        }
        return toAjax(largeIssueService.save(entity));
    }

    public AjaxResult enclosureEmail(MultipartFile multipartFile, String content) {
        //创建一个MINE消息
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //谁发
            helper.setFrom(sender);
            //谁接收
            helper.setTo("qwer20030522@163.com");
            //邮件主题
            helper.setSubject("问题上报");
            //邮件内容   true 表示带有附件或html
            helper.setText(content, true);
            File multipartFileToFile = MultipartFileToFile(multipartFile);
            if (multipartFileToFile == null) {
                return AjaxResult.error("文件转换失败");
            }
            FileSystemResource file = new FileSystemResource(multipartFileToFile);
            String filename = file.getFilename();
            //添加附件
            if (filename == null) {
                return AjaxResult.error("文件名称获取失败");
            }
            helper.addAttachment(filename, file);
            mailSender.send(message);
            return AjaxResult.success("发送邮件成功");
        }  catch (javax.mail.MessagingException e) {
            e.printStackTrace();
            return AjaxResult.error("发送邮件失败");
        }
    }

    private File MultipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若需要防止生成的临时文件重复,可以在文件名后添加随机码

        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 本周检查计划
     * */
    @GetMapping("/planCheckList")
    public AjaxResult planCheckList() {
        return AjaxResult.success("查询成功", largePlanService.planCheckList());
    }

    /**
     * 本周施工计划
     * */
    @GetMapping("/planDoneList")
    public AjaxResult planDoneList() {
        return AjaxResult.success("查询成功", largePlanService.planDoneList());
    }
}
