package org.dromara.wflow.workflow.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.dromara.common.sse.dto.SseMessageDto;
import org.dromara.common.sse.utils.SseMessageUtils;
import org.dromara.common.sse.vo.SseMessageVo;
import org.dromara.wflow.bean.entity.WflowModelHistorys;
import org.dromara.wflow.mapper.WflowModelHistorysMapper;
import org.dromara.wflow.mapper.WflowNotifysMapper;
import org.dromara.wflow.workflow.service.NotifyService;
import org.dromara.wflow.bean.entity.WflowNotifys;
import org.dromara.wflow.config.AsyncTaskTheadPoolConfig;
import org.dromara.wflow.utils.UserUtil;
import org.dromara.wflow.workflow.bean.dto.NotifyDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.GregorianCalendar;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 消息通知服务
 *
 * @author : willian fu
 * @date : 2022/9/17
 */
@Slf4j
@Service
public class DefaultNotifyServiceImpl implements NotifyService {

    @Autowired
    private WflowNotifysMapper notifysMapper;

    @Autowired
    private ScheduledExecutorService scheduledExecutorService;

    @Autowired
    private WflowModelHistorysMapper modelHistorysMapper;

    /**
     * 发送消息通知到自定义的渠道
     *
     * @param notify      消息实体类
     * @param model       该消息关联的流程模型
     * @param notifySetUp 该流程消息通知设置项
     */
    private void notifyCustom(NotifyDto notify, WflowModelHistorys model, JSONObject notifySetUp) {
        //TODO 大家自定义通知到自己想要的地方
    }

    @Override
    public void notify(NotifyDto notify) {
        AsyncTaskTheadPoolConfig.taskScheduler.submit(() -> {
            WflowModelHistorys model = modelHistorysMapper.selectOne(new LambdaQueryWrapper<WflowModelHistorys>()
                    .select(WflowModelHistorys::getSettings)
                    .eq(WflowModelHistorys::getProcessDefId, notify.getProcessDefId()));
            Optional.ofNullable(model).ifPresent(md -> {
                JSONObject notifySetUp = JSONObject.parseObject(md.getSettings()).getJSONObject("notify");
                notifyCustom(notify, model, notifySetUp);
                //保存通知消息
                notifysMapper.insert(WflowNotifys.builder()
                        .id(IdUtil.objectId())
                        .title(notify.getTitle())
                        .instanceId(notify.getInstanceId())
                        .content(notify.getContent())
                        .userId(notify.getTarget())
                        .link(null)
                        .nodeId(notify.getNodeId())
                        .type(notify.getType())
                        .readed(false)
                        .createTime(null == notify.getCreateTime() ?
                                GregorianCalendar.getInstance().getTime()
                                : notify.getCreateTime())
                        .build());
                pushMessage(notify.getTitle(), notify.getContent(), Long.valueOf(notify.getTarget()));
            });
        });
    }

    @Override
    public void pushMessage(String title, String content, Long target) {
        // 调用SSE实时推送通知
        scheduledExecutorService.schedule(() -> {
            SseMessageDto dto = new SseMessageDto();
            SseMessageVo vo = new SseMessageVo();
            vo.setMessage(content);
            if ("您提交的审批被驳回".equals(title) || "您的审批被退回".equals(title) || "您的审批已通过".equals(title)) {
                vo.setType("1");
            } else if ("待处理的转交任务".equals(title) || "您有新的任务待处理".equals(title)) {
                vo.setType("3");
            } else if ("审批超时提醒".equals(title) || "审批抄送送通知".equals(title) || "您有新的待办任务".equals(title)){
                vo.setType("2");
            }
            dto.setMessage(JSON.toJSONString(vo));
            dto.setUserIds(List.of(target));
            SseMessageUtils.publishMessage(dto);
        }, 5, TimeUnit.SECONDS);
        log.info("推送通知[{}]给[{} 内容为{}]", target, title, content);
    }

    @Override
    public Page<WflowNotifys> getNotify(Integer pageSize, Integer pageNo) {
        return notifysMapper.selectPage(new Page<>(pageNo, pageSize),
                new LambdaQueryWrapper<WflowNotifys>()
                        .eq(WflowNotifys::getReaded, false)
                        .eq(WflowNotifys::getUserId, UserUtil.getLoginUserId())
                        .orderByDesc(WflowNotifys::getCreateTime)
        );
    }

    @Override
    public void readNotify(List<String> ids) {
        notifysMapper.update(WflowNotifys.builder().readed(true).build(),
                new LambdaQueryWrapper<WflowNotifys>().in(WflowNotifys::getId, ids)
                        .eq(WflowNotifys::getUserId, UserUtil.getLoginUserId()));
    }
}
