package com.ruoyi.zzb.common.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.zzb.common.domain.BaseFileInfo;
import com.ruoyi.zzb.common.domain.BaseFileSetDTO;
import com.ruoyi.zzb.common.service.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/base")
public class CommonController extends BaseController {

    @Value("${module.zyww.templateFilePath}")
    private String zywwTemplateFilePath;
    @Value("${module.dbjz.templateFilePath}")
    private String dbjzTemplateFilePath;
    @Value("${module.hybz.templateFilePath}")
    private String hybzTemplateFilePath;
    @Autowired
    private BaseService baseService;


    /**
     * 功能描述: 向目标邮箱地址发送一条带附件（支持多个）的邮件
     * @param: [reqBody]
     * @return: com.alibaba.fastjson.JSONObject
     * @author: peifjFantasy
     * @Date: 2024/12/2 10:48
     */
    @PostMapping("/send")
    public AjaxResult send(@RequestBody JSONObject reqBody){
        String subject;          // 邮件主题
        String text;             // 邮件内容
        String attachmentPath;   // 每一个模块对应的的申请模板文件在服务器的存储路径
        String toEmail = reqBody.getString("toEmail");
        if(StringUtils.isBlank(toEmail)/* || !CommonUtils.isRightEmail(toEmail)*/){
            log.error("toEmail参数非法");
            return error("toEmail参数非法");
        }
        // 模块编码  前端在对应页面获取申请模板文件时需手动传入该参数，后端根据该参数值向目标邮箱发送对应的申请模板文件
        String moduleCode = reqBody.getString("moduleCode");
        if(StringUtils.isBlank(moduleCode)){
            log.error("moduleCode参数为空");
            return error("moduleCode参数为空");
        }
        if("zyww".equals(moduleCode)){
            subject = "【住院慰问】";
            text = "住院慰问相关内容";
            attachmentPath = zywwTemplateFilePath;
        } else if ("dbjz".equals(moduleCode)) {
            subject = "【大病救助】";
            text = "大病救助相关内容";
            attachmentPath = dbjzTemplateFilePath;
        } else {
            subject = "【会员保障】";
            text = "会员保障相关内容";
            attachmentPath = hybzTemplateFilePath;
        }
        try {
            File directory = new File(attachmentPath);
            File[] files = directory.listFiles();
            baseService.sendEmail(toEmail, subject, text, attachmentPath, files);
            return success("服务器发送邮件成功");
        } catch (Exception e){
            log.error("服务器发送邮件失败", e);
            return error("服务器发送邮件失败 - " + e.getMessage());
        }
    }


    /**
     * 功能描述: 业务模块处理文件上传通用接口，并根据模块编码、申请单ID保存对应的文件信息记录到数据库
     * @param: [baseFileSetDTO]
     * @return: com.alibaba.fastjson.JSONObject
     * @author: peifjFantasy
     * @Date: 2024/11/28 14:47
     */
    @PostMapping("/upload")
    public AjaxResult upload(BaseFileSetDTO baseFileSetDTO){
        String moduleCode = baseFileSetDTO.getModuleCode();
        String applyFormId = baseFileSetDTO.getApplyFormId();
        if(StringUtils.isBlank(moduleCode) || StringUtils.isBlank(applyFormId)){
            log.error("文件上传参数为空");
            return error("文件上传参数为空");
        }
        try {
            // 文件上传路径
            String fileStoragePath = RuoYiConfig.getUploadPath();
            List<BaseFileInfo> baseFileInfoList = new ArrayList<>();
            String moduleName = "";
            if("zyww".equals(moduleCode)){
                moduleName = "住院慰问";
            } else if("dbjz".equals(moduleCode)){
                moduleName = "大病救助";
            } else {
                moduleName = "会员保障";
            }
            baseFileInfoList = baseService.processUploadAndBuildParams(baseFileSetDTO, moduleCode, moduleName, applyFormId, fileStoragePath);
            // 等上传的文件写盘成功，再向数据库写入对应的文件信息记录
            if(baseFileInfoList.size() > 0){
                BaseFileInfo baseFileInfo = baseFileInfoList.get(0);
                // 保存文件信息到数据库
                boolean optFlag = baseService.saveBaseFileInfo(baseFileInfo);
                return optFlag? success(baseFileInfo.getFileStorageId()) : error("文件信息保存/修改失败 - 申请单ID：" + applyFormId);
            }
            return error("文件对象为空，信息无法保存/修改");
        } catch (Exception e){
            log.error("文件信息保存/修改失败", e);
            return error("文件信息保存/修改失败 - " + e.getMessage());
        }
    }

    /**
     * 功能描述: 业务模块文件取消上传通用接口，根据文件上传成功时服务器返回的文件存储ID(fileStorageId)去删除数据库中对应的文件信息记录
     * @param: [reqBody]
     * @return: com.alibaba.fastjson.JSONObject
     * @author: peifjFantasy 
     * @Date: 2024/12/2 10:47
     */
    @PostMapping("/cancelUpload")
    public AjaxResult cancelUpload(@RequestBody JSONObject reqBody){
        String fileStorageId = reqBody.getString("fileStorageId");
        if(StringUtils.isBlank(fileStorageId)){
            return error("fileStorageId参数为空");
        }
        try {
            // 删除文件信息记录
            boolean optFlag = baseService.delBaseFileInfosByFileStorageId(fileStorageId);
            return optFlag? success(true) : error("文件信息删除失败 - 文件存储ID：" + fileStorageId);
        }catch (Exception e){
            log.error("文件信息删除失败", e);
            return error("文件信息删除失败 - " + e.getMessage());
        }
    }


}
