package nckd.jimin.jyyy.bd.plugin.msg.ecology;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.exception.ErrorCode;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.workflow.engine.msg.AbstractMessageServiceHandler;
import kd.bos.workflow.engine.msg.ctx.MessageContext;
import kd.bos.workflow.engine.msg.info.MessageInfo;
import kd.bos.workflow.engine.msg.info.ToDoInfo;
import kd.bos.workflow.exception.WFMessageServiceException;
import org.apache.commons.collections.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 插件说明：消息渠道插件，泛微消息处理
 * @author wanghaiwu_kd
 * @date 2025/04/15
 */
public class FanweiServiceHelper extends AbstractMessageServiceHandler {
    private static Log logger = LogFactory.getLog(FanweiServiceHelper.class);

    public FanweiServiceHelper() {
    }

    /**
     * 待办创建
     * @param ctx
     * @param info
     */
    @Override
    public void createToDo(MessageContext ctx, ToDoInfo info) {
        logger.info("泛微待办创建开始 ctx: " + ctx.toString() + ",taskId:" + ctx.getTaskId() + ", taskId:" + info.getTaskId());

        DynamicObject taskInfo = BusinessDataServiceHelper.loadSingleFromCache(info.getTaskId(), "wf_task");
        //获取到的taskInfo可能是空的
        String handlestate = taskInfo == null ? "" : taskInfo.getString("handlestate");

        List<Long> userIds = info.getUserIds();
        if (CollectionUtils.isEmpty(userIds)) {
            logger.info("人员为空，推送失败!");
            return;
        }

        logger.info("泛微待办 人员：" + userIds.toString());

        Map<String, String> params = new HashMap<>(3);
        params.put("isremark", "0");
        params.put("viewtype", "0");

        for(int i = 0; i < userIds.size(); i++){
            Long userId = userIds.get(i);

            if(userId == null){
                continue;
            }

            params.put("userId", userId.toString());

            try {
                FanweiCommonUtil.createUserToDo(ctx, info, params);
                logger.info("create todo content=" + info.getTaskId());
            } catch (Exception var8) {
                String message = ResManager.loadKDString("泛微待办创建失败，原因:%s", "WFErrorCode_10001", "bos-wf-engine", new Object[0]);
                ErrorCode error = new ErrorCode("bos.wf.rpa.", message);
                throw new WFMessageServiceException(var8, error, new Object[]{var8.getMessage()});
            }
        }
    }

    /**
     * 待办处理
     * @param ctx
     * @param info
     */
    @Override
    public void dealToDo(MessageContext ctx, ToDoInfo info) {
        logger.info("泛微待办处理开始 ctx: " + ctx.toString() + ",taskId:" + ctx.getTaskId() + ", taskId:" + info.getTaskId());

//        DynamicObject taskInfo = BusinessDataServiceHelper.loadSingleFromCache(info.getTaskId(), "wf_task");
//        //获取到的taskInfo可能是空的
//        String handlestate = taskInfo == null ? "" : taskInfo.getString("handlestate");

        //驳回状态的任务做提交处理时不做待办更新推送。
//        if("dismissed".equals(handlestate)){
//            return;
//        }

        List<Long> userIds = info.getUserIds();
        if (CollectionUtils.isEmpty(userIds)) {
            logger.info("人员为空，推送失败!");
            return;
        }

        logger.info("处理待办 人员：" + userIds.toString());

        Map<String, String> params = new HashMap<>(3);
        params.put("isremark", "2");
        params.put("viewtype", "1");

        for(int i = 0; i < userIds.size(); i++){
            Long userId = userIds.get(i);

            if(userId == null){
                continue;
            }

            params.put("userId", userId.toString());

            try {
                FanweiCommonUtil.dealUserToDo(ctx, info, params);
                logger.info("deal todo content=" + info.getTaskId());
            } catch (Exception var8) {
                String message = ResManager.loadKDString("泛微待办处理失败，原因:%s", "WFErrorCode_10001", "bos-wf-engine", new Object[0]);
                ErrorCode error = new ErrorCode("bos.wf.rpa.", message);
                throw new WFMessageServiceException(var8, error, new Object[]{var8.getMessage()});
            }
        }
    }

    /**
     * 待办删除
     * @param ctx
     * @param info
     */
    @Override
    public void deleteToDo(MessageContext ctx, ToDoInfo info) {
        logger.info("泛微待删除办开始 ctx: " + ctx.toString() + ",taskId:" + ctx.getTaskId() + ", taskId:" + info.getTaskId());

        List<Long> userIds = info.getUserIds();
        if (CollectionUtils.isEmpty(userIds)) {
            logger.info("人员为空，删除失败!");
            return;
        }

        logger.info("处理待办 人员：" + userIds.toString());

        Map<String, String> params = new HashMap<>(3);
        params.put("isremark", "-1");
        params.put("viewtype", "1");

        for(int i = 0; i < userIds.size(); i++){
            Long userId = userIds.get(i);

            if(userId == null){
                continue;
            }

            params.put("userId", userId.toString());

            try {
                FanweiCommonUtil.deleteUserToDo(ctx, info, params);
                logger.info("delete todo content=" + info.getTaskId());
            } catch (Exception var8) {
                String message = ResManager.loadKDString("泛微待办删除失败，原因:%s", "WFErrorCode_10001", "bos-wf-engine", new Object[0]);
                ErrorCode error = new ErrorCode("bos.wf.rpa.", message);
                throw new WFMessageServiceException(var8, error, new Object[]{var8.getMessage()});
            }
        }
    }

    /**
     * 发送消息
     * @param ctx
     * @param info
     */
    @Override
    public void sendMessage(MessageContext ctx, MessageInfo info) {
        //消息渠道
        String channel = info.getNotifyType();
        if(!"fanwei".equals(channel)){
            return;
        }

//        String type = info.getType();
//        //只发送传阅的消息
//        if(!"circulation".equals(info.getTplScene())){
//            return;
//        }

        if (ctx != null){
            logger.info("泛微消息url:" + info.getContentUrl() + ",mobileurl:" + info.getMobContentUrl()+ ", pk:" + ctx.getBusinessKey());
        }else {
            logger.info("泛微消息url:" + info.getContentUrl() + ",mobileurl:" + info.getMobContentUrl());
        }
        List<Long> userIds = info.getUserIds();
        if (CollectionUtils.isEmpty(userIds)) {
            logger.info("人员为空，删除失败!");
            return;
        }

        Map<String, String> params = new HashMap<>(3);
        params.put("isremark", "8");
        params.put("viewtype", "0");

        for(int i = 0; i < userIds.size(); i++){
            Long userId = userIds.get(i);
            params.put("userId", userId.toString());

            try {
                FanweiCommonUtil.sendMessage(ctx, info, params);
                logger.info("create todo content=" + info.getChannelMsgId());
            } catch (Exception var8) {
                String message = ResManager.loadKDString("泛微消息创建失败，原因:%s", "WFErrorCode_10001", "bos-wf-engine", new Object[0]);
                ErrorCode error = new ErrorCode("bos.wf.rpa.", message);
                throw new WFMessageServiceException(var8, error, new Object[]{var8.getMessage()});
            }
        }
    }
}
