package com.zcxk.process.activiti.Service;

import com.alibaba.fastjson.JSONObject;
import com.zcxk.entity.Message;
import com.zcxk.model.LoginUser;
import com.zcxk.process.dto.TaskUserDTO;
import com.zcxk.process.service.UserFormService;
import com.zcxk.util.MessageSendUtil;
import com.zcxk.util.UserUtil;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;
import java.util.UUID;

@Component
public class ProgressSevice {


    @Autowired
    private UserFormService userFormService;
    @Autowired
    private MessageSendUtil messageSendUtil;
    @Autowired
    TaskService taskService;
    public void execute(DelegateExecution delegateExecution) throws Exception {

     }
     public void runWithParticipants(DelegateExecution execution,String param){
         System.out.println("serviceTask已经执行已经执行！");
         Map<String, Object> variables = execution.getVariables();

         Message message=new Message();

         message.setStatus(1);
         LoginUser currentUser = UserUtil.getCurrentUser();
         message.setCreateBy(currentUser.getUsername());
         message.setTenantId(currentUser.getTenantId());
         message.setMessageContent(JSONObject.toJSONString(variables));
         message.setMessageId(UUID.randomUUID().toString());
         message.setMessageType((Integer) variables.get("msgType"));
         message.setUrl((String) variables.get("url"));
         message.setMessageTemplateId((Integer) variables.get("templateId"));

         TaskUserDTO taskUserDTO = JSONObject.parseObject(param, TaskUserDTO.class);
         message.setChannel(taskUserDTO.getChannel());

         Set<Integer> taskUsers = userFormService.getTaskUsers(taskUserDTO);
         if(taskUserDTO.getUserFormFlag()==1){
             String assineeFormUserId = (String)variables.get("assineeFormUserId");
             if(assineeFormUserId!=null){
                 String[] userIds=assineeFormUserId.split(",");
                 for (String userId : userIds) {
                     taskUsers.add(Integer.parseInt(userId));
                 }

             }
         }
         if(taskUsers!=null){

             taskUsers.forEach(id->{
                 message.setUserId(id);
                 messageSendUtil.send(message);
             });
         }

     }
}
