package cn.fateverse.workflow.service;

import cn.fateverse.admin.dubbo.DubboUserService;
import cn.fateverse.admin.entity.User;
import cn.fateverse.admin.vo.UserVo;
import cn.fateverse.common.core.exception.CustomException;
import cn.fateverse.common.email.entity.SendEmailInfo;
import cn.fateverse.common.email.service.EmailService;
import cn.fateverse.workflow.constant.ProcessConstant;
import cn.fateverse.workflow.entity.bpmn.SettingsInfo;
import cn.fateverse.notice.dto.NoticeDto;
import cn.fateverse.notice.dubbo.DubboNoticeService;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 消息通知服务
 *
 * @author Clay
 * @date 2023-03-22
 */
@Slf4j
@Service
public class NotifyService {

    @DubboReference
    private DubboUserService userService;

    @DubboReference
    private DubboNoticeService noticeService;

    private final EmailService emailService;

    public NotifyService(EmailService emailService) {
        this.emailService = emailService;
    }

    /**
     * 通知任务
     *
     * @param deploymentName 部署的名称
     * @param list           任务通知list
     * @param settingsInfo   设置信息
     */
    public void notifyTaskList(String deploymentName, List<Task> list, SettingsInfo settingsInfo) {
        JSONObject notify = settingsInfo.getNotify();
        List<Long> userIds = list.stream().map(task -> Long.valueOf(task.getAssignee())).collect(Collectors.toList());
        Map<Long, UserVo> userMap = new HashMap<>();
        if (!userIds.isEmpty()) {
            userMap = userService.searchUserListByUserIds(userIds).stream().collect(Collectors.toMap(UserVo::getUserId, Function.identity()));
        }
        Map<Long, UserVo> finalUserMap = userMap;
        list.forEach(task -> {
            JSONArray types = notify.getJSONArray("types");
            for (Object type : types) {
                switch (type.toString()) {
                    case "APP":
                        // 应用内通知
                        NoticeDto notice = new NoticeDto();
                        notice.setNoticeTitle(notify.getString("title"));
                        //noticeService.syncSend();
                        break;
                    case "EMAIL":
                        // 邮件通知
                        sendEmail(deploymentName, notify.getString("title"), task, finalUserMap.get(Long.valueOf(task.getAssignee())));
                        break;
                    case "SMS":
                        // 短信通知
                        break;
                    case "WX":
                        // 微信通知
                        break;
                    case "DING":
                        // 钉钉通知
                        break;
                    default:
                        throw new CustomException("通知方式还未实现!");
                }
            }
        });
    }

    /**
     * 发送邮件
     *
     * @param deploymentName 部署的名称
     * @param title          通知的title
     * @param task           任务
     * @param user           用户信息
     */
    private void sendEmail(String deploymentName, String title, Task task, UserVo user) {
        if (!user.checkEmail()) {
            return;
        }
        User startUser = (User) task.getProcessVariables().get(ProcessConstant.START_USER_INFO);
        SendEmailInfo emailInfo = new SendEmailInfo();
        if ("消息通知标题".equals(title)) {
            emailInfo.setSubject("您有新的审批任务");
        }
        emailInfo.setContent(startUser.getNickName() + " 提交 [" + deploymentName + "] 需要您审批,请立即处理");
        emailInfo.setSenders(Collections.singletonList(user.getEmail()));
        emailService.asyncSendMail(emailInfo);
    }

}
