package cn.iocoder.yudao.module.bpm.service.message;

import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.framework.web.config.WebProperties;
import cn.iocoder.yudao.module.bpm.convert.message.BpmMessageConvert;
import cn.iocoder.yudao.module.bpm.enums.message.BpmMessageEnum;
import cn.iocoder.yudao.module.bpm.service.message.dto.BpmMessageSendWhenProcessInstanceApproveReqDTO;
import cn.iocoder.yudao.module.bpm.service.message.dto.BpmMessageSendWhenProcessInstanceRejectReqDTO;
import cn.iocoder.yudao.module.bpm.service.message.dto.BpmMessageSendWhenTaskCreatedReqDTO;
import cn.iocoder.yudao.module.bpm.service.message.dto.BpmMessageSendWhenTaskTimeoutReqDTO;
import cn.iocoder.yudao.module.system.api.dingtalk.DingtalkSendApi;
import cn.iocoder.yudao.module.system.api.notify.NotifyMessageSendApi;
import cn.iocoder.yudao.module.system.api.notify.dto.NotifySendSingleToUserReqDTO;
import cn.iocoder.yudao.module.system.api.sms.SmsSendApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * BPM 消息 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class BpmMessageServiceImpl implements BpmMessageService {

    @Resource
    private SmsSendApi smsSendApi;

    @Resource
    private DingtalkSendApi dingtalkSendApi;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private WebProperties webProperties;
    @Autowired
    private NotifyMessageSendApi notifyMessageSendApi;
    @Value("${system.url}")
    private String systemUrl;

    @Override
    public void sendMessageWhenProcessInstanceApprove(BpmMessageSendWhenProcessInstanceApproveReqDTO reqDTO) {
        Map<String, Object> templateParams = new HashMap<>();
        templateParams.put("processInstanceName", reqDTO.getProcessInstanceName());
        templateParams.put("detailUrl", getProcessInstanceDetailUrl(reqDTO.getProcessInstanceId()));
        //todo
//        smsSendApi.sendSingleSmsToAdmin(BpmMessageConvert.INSTANCE.convert(reqDTO.getStartUserId(),
//                BpmMessageEnum.PROCESS_INSTANCE_APPROVE.getSmsTemplateCode(), templateParams));
    }

    @Override
    public void sendMessageWhenProcessInstanceReject(BpmMessageSendWhenProcessInstanceRejectReqDTO reqDTO) {
        Map<String, Object> templateParams = new HashMap<>();
        templateParams.put("processInstanceName", reqDTO.getProcessInstanceName());
        templateParams.put("reason", reqDTO.getReason());
        templateParams.put("detailUrl", getProcessInstanceDetailUrl(reqDTO.getProcessInstanceId()));
        //todo
//        smsSendApi.sendSingleSmsToAdmin(BpmMessageConvert.INSTANCE.convert(reqDTO.getStartUserId(),
//                BpmMessageEnum.PROCESS_INSTANCE_REJECT.getSmsTemplateCode(), templateParams));
    }

    @Override
    public void sendMessageWhenTaskAssigned(BpmMessageSendWhenTaskCreatedReqDTO reqDTO) {
        Map<String, Object> templateParams = new HashMap<>();
        templateParams.put("processInstanceName", reqDTO.getProcessInstanceName());
        templateParams.put("taskName", reqDTO.getTaskName());
        templateParams.put("startUserNickname", reqDTO.getStartUserNickname());
        templateParams.put("detailUrl", getProcessInstanceDetailUrl(reqDTO.getProcessInstanceId()));
        /* smsSendApi.sendSingleSmsToAdmin(BpmMessageConvert.INSTANCE.convert(reqDTO.getAssigneeUserId(),
                BpmMessageEnum.TASK_ASSIGNED.getSmsTemplateCode(), templateParams)); */
        // 任务指定到具体人时 钉钉提醒
        // 根据审批人的id查询手机号
        AdminUserRespDTO user = adminUserApi.getUser(reqDTO.getAssigneeUserId());
        String msg = "【DeepOil】供应商审核流程 - 有新的供应商信息需要审核"+"，请前往 http://1.94.244.160:91/ 处理。"+"["+new Date()+"]";
        String url = "";
        if ("故障上报流程".equals(reqDTO.getProcessInstanceName())||"瑞恒故障上报".equals(reqDTO.getProcessInstanceName())) {
            String templateCode = "failure-report";
            templateParams.put("businessType", "failureReport");
            templateParams.put("businessId", reqDTO.getProcessInstanceId());
            templateParams.put("processcode", reqDTO.getProcessInstanceId());
            notifyMessageSendApi.sendSingleMessageToAdmin(new NotifySendSingleToUserReqDTO()
                    .setUserId(reqDTO.getAssigneeUserId()).setTemplateCode(templateCode).setTemplateParams(templateParams));
            msg = "您有新的故障上报流程待处理，请审批。"+"["+ DateUtil.format(new Date(),"yyyy-MM-dd hh:mm:ss")+"]";
            url=systemUrl + "dingding?id="+reqDTO.getProcessInstanceId()+"&type=failureReport&userId="+reqDTO.getAssigneeUserId();
        } else if ("委外维修工单流程".equals(reqDTO.getProcessInstanceName())){
            String templateCode = "maintain-out";
            templateParams.put("businessType", "maintainOut");
            templateParams.put("businessId", reqDTO.getProcessInstanceId());
            templateParams.put("processcode", reqDTO.getProcessInstanceId());
            notifyMessageSendApi.sendSingleMessageToAdmin(new NotifySendSingleToUserReqDTO()
                    .setUserId(reqDTO.getAssigneeUserId()).setTemplateCode(templateCode).setTemplateParams(templateParams));
            msg = "您有新的委外维修流程，请审批。"+"["+ DateUtil.format(new Date(),"yyyy-MM-dd hh:mm:ss")+"]";
            url=systemUrl + "dingding?id="+reqDTO.getProcessInstanceId()+"&type=maintainOut&userId="+reqDTO.getAssigneeUserId();
        } else if ("QHSE事故上报".equals(reqDTO.getProcessInstanceName())){
            String templateCode = "qhse-accident";
            templateParams.put("businessType", "qhseAccident");
            templateParams.put("businessId", reqDTO.getProcessInstanceId());
            templateParams.put("processcode", reqDTO.getProcessInstanceId());
            notifyMessageSendApi.sendSingleMessageToAdmin(new NotifySendSingleToUserReqDTO()
                    .setUserId(reqDTO.getAssigneeUserId()).setTemplateCode(templateCode).setTemplateParams(templateParams));
            url=systemUrl + "dingding?id="+reqDTO.getProcessInstanceId()+"&type=qhseAccident&userId="+reqDTO.getAssigneeUserId();
        }
        dingtalkSendApi.send(user.getMobile(), msg,"link",url,"DeepOil-PMS消息提醒");
    }

    @Override
    public void sendMessageWhenTaskTimeout(BpmMessageSendWhenTaskTimeoutReqDTO reqDTO) {
        Map<String, Object> templateParams = new HashMap<>();
        templateParams.put("processInstanceName", reqDTO.getProcessInstanceName());
        templateParams.put("taskName", reqDTO.getTaskName());
        templateParams.put("detailUrl", getProcessInstanceDetailUrl(reqDTO.getProcessInstanceId()));
        smsSendApi.sendSingleSmsToAdmin(BpmMessageConvert.INSTANCE.convert(reqDTO.getAssigneeUserId(),
                BpmMessageEnum.TASK_TIMEOUT.getSmsTemplateCode(), templateParams));
    }

    private String getProcessInstanceDetailUrl(String taskId) {
        return webProperties.getAdminUi().getUrl() + "/bpm/process-instance/detail?id=" + taskId;
    }

}
