package cn.iocoder.yudao.module.pms.listener;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.module.pms.controller.admin.stat.DeptUtil;
import cn.iocoder.yudao.module.pms.dal.dataobject.qhse.accident.IotAccidentReportDO;
import cn.iocoder.yudao.module.pms.dal.mysql.qhse.accident.IotAccidentReportMapper;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.PostApi;
import cn.iocoder.yudao.module.system.api.dept.dto.PostRespDTO;
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.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictDataDO;
import cn.iocoder.yudao.module.system.service.dict.DictDataService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
public class AccidentSpringExpressionExecutionListener {

    private final IotAccidentReportMapper iotAccidentReportMapper;
    private final DeptUtil deptUtil;
    private final DictDataService dictDataService;
    private final PostApi postApi;
    private final AdminUserApi adminUserApi;
    private final DeptApi deptApi;
    private final NotifyMessageSendApi notifyMessageSendApi;
    private final DingtalkSendApi dingtalkSendApi;
    @Value("${system.url}")
    private String systemUrl;

    public AccidentSpringExpressionExecutionListener(IotAccidentReportMapper iotAccidentReportMapper, DeptUtil deptUtil, DictDataService dictDataService, PostApi postApi, AdminUserApi adminUserApi, DeptApi deptApi, NotifyMessageSendApi notifyMessageSendApi, DingtalkSendApi dingtalkSendApi) {
        this.iotAccidentReportMapper = iotAccidentReportMapper;
        this.deptUtil = deptUtil;
        this.dictDataService = dictDataService;
        this.postApi = postApi;
        this.adminUserApi = adminUserApi;
        this.deptApi = deptApi;
        this.notifyMessageSendApi = notifyMessageSendApi;
        this.dingtalkSendApi = dingtalkSendApi;
    }

    public void execute(DelegateExecution execution) {
        //最后一步执行完成之后处理更新状态
        String processInstanceBusinessKey = execution.getProcessInstanceBusinessKey();

        IotAccidentReportDO iotAccidentReportDO = iotAccidentReportMapper.selectById(processInstanceBusinessKey);
        if (iotAccidentReportDO == null) {throw new ServiceException(new ErrorCode(22,"不存在事故上报信息"));}
        iotAccidentReportDO.setStatus("finished");
        iotAccidentReportMapper.updateById(iotAccidentReportDO);
    }


    public void noticeGeneralManager(DelegateExecution execution) {
        //业务主键
        String businessKey = execution.getProcessInstanceBusinessKey();
        IotAccidentReportDO iotAccidentReportDO1 = iotAccidentReportMapper.selectById(businessKey);
        if (iotAccidentReportDO1 == null) {throw new ServiceException(new ErrorCode(22,"不存在事故上报信息"));}
        String companyCode = deptUtil.getCompanyCode(iotAccidentReportDO1.getDeptId());
        Long deptId = null;
        if ("rh".equals(companyCode)) {
            deptId = 157L;
        } else if ("ry".equals(companyCode)) {
            deptId = 158L;
        } else if ("rd".equals(companyCode)) {
            deptId = 163L;
        }
        if (deptId == null) {
            throw new ServiceException(new ErrorCode(3,"没有定位到专业公司"));
        }
        List<DictDataDO> dictDataList = dictDataService.getDictDataListByDictType("qhse-zjl");
        if (CollUtil.isEmpty(dictDataList)) {
            throw new ServiceException();
        }
        String label = dictDataList.get(0).getLabel();
        PostRespDTO postByName = postApi.getPostByName(label);
        if (postByName == null) {
            throw new ServiceException();
        }
        Set<AdminUserRespDTO> users = adminUserApi.getUserListByDept(deptId).stream().filter(e -> {
            if (CollUtil.isNotEmpty(e.getPostIds())) {
                return e.getPostIds().contains(postByName.getId());
            } else {
                return false;
            }
        }).collect(Collectors.toSet());
        if (CollUtil.isNotEmpty(users)) {
            AdminUserRespDTO adminUserRespDTO = users.stream().findFirst().get();
            Map<String, Object> templateParams = new HashMap<>();
            String url = "";
            String templateCode = "qhse-accident";
            templateParams.put("businessType", "qhseAccident");
            templateParams.put("businessId", execution.getProcessInstanceBusinessKey());
            templateParams.put("processcode", execution.getProcessInstanceBusinessKey());
            notifyMessageSendApi.sendSingleMessageToAdmin(new NotifySendSingleToUserReqDTO()
                    .setUserId(adminUserRespDTO.getId()).setTemplateCode(templateCode).setTemplateParams(templateParams));
            url=systemUrl + "dingding?id="+execution.getProcessInstanceBusinessKey()+"&type=qhseAccident&userId="+adminUserRespDTO.getId();
            dingtalkSendApi.send(adminUserRespDTO.getMobile(), "","link",url,"DeepOil-QHSE消息提醒");
        }
    }
}
