package com.yunzhupaas.flowable.util;

import cn.hutool.core.util.ObjectUtil;
import com.yunzhupaas.exception.WorkFlowException;
import com.yunzhupaas.flowable.entity.CirculateEntity;
import com.yunzhupaas.flowable.entity.OperatorEntity;
import com.yunzhupaas.flowable.entity.TaskEntity;
import com.yunzhupaas.flowable.entity.TemplateNodeEntity;
import com.yunzhupaas.flowable.enums.RecordEnum;
import com.yunzhupaas.flowable.model.task.FlowMethod;
import com.yunzhupaas.flowable.model.task.FlowModel;
import com.yunzhupaas.flowable.model.templatenode.nodejson.NodeModel;
import com.yunzhupaas.flowable.model.util.FlowNature;
import com.yunzhupaas.flowable.service.CirculateService;
import com.yunzhupaas.permission.entity.UserEntity;
import com.yunzhupaas.permission.entity.UserRelationEntity;
import com.yunzhupaas.util.JsonUtil;
import com.yunzhupaas.util.RandomUtil;
import com.yunzhupaas.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ：云筑产品开发平台组
 * @version: V3.1.0
 * @copyright 深圳市乐程软件有限公司
 * @date ：2024/4/29 下午3:12
 */
@Component
public class CirculateUtil {

    @Autowired
    private ServiceUtil serviceUtil;
    @Autowired
    private TaskUtil taskUtil;
    @Autowired
    private CirculateService circulateService;

    public List<CirculateEntity> circulateList(FlowMethod flowMethod) throws WorkFlowException {
        FlowModel flowModel = flowMethod.getFlowModel();
        List<CirculateEntity> circulateList = new ArrayList<>();
        TaskEntity task = flowMethod.getTaskEntity();
        OperatorEntity operator = flowMethod.getOperatorEntity();
        TemplateNodeEntity nodeEntity = flowMethod.getNodeEntity();
        NodeModel nodeModel = JsonUtil.getJsonToBean(nodeEntity.getNodeJson(), NodeModel.class);
        List<String> userIdAll = new ArrayList<>();
        //附加规则
        if (!ObjectUtil.equals(flowMethod.getType(), RecordEnum.reject.getCode())) {
            List<String> all = taskUtil.getSub(nodeModel.getCirculateUser());
            userIdAll = serviceUtil.getUserListAll(all);
            taskUtil.rule(userIdAll, task.getId(), nodeModel.getExtraCopyRule());
        }
        //指定传阅人
        userIdAll.addAll(Arrays.asList(StringUtil.isNotEmpty(flowModel.getCopyIds()) ? flowModel.getCopyIds().split(",") : new String[]{}));
        //抄送自己
        if (nodeModel.getIsInitiatorCopy()) {
            userIdAll.add(task.getCreatorUserId());
        }
        //抄送表单变量
        if (nodeModel.getIsFormFieldCopy()) {
            flowMethod.setIsAssign(false);
            flowMethod.setIsData(true);
            Map<String, Object> dataAll = taskUtil.createOrUpdate(flowMethod);
            Object data = dataAll.get(nodeModel.getCopyFormField() + FlowNature.FORM_FIELD_SUFFIX);
            if (data != null) {
                List<String> list = new ArrayList<>();
                try {
                    list.addAll(JsonUtil.getJsonToList(String.valueOf(data), String.class));
                } catch (Exception e) {}
                if (data instanceof List) {
                    list.addAll((List) data);
                } else {
                    list.addAll(Arrays.asList(String.valueOf(data).split(",")));
                }
                List<String> id = new ArrayList<>();
                for (String s : list) {
                    id.add(s.split("--")[0]);
                }
                List<UserRelationEntity> listByObjectIdAll = serviceUtil.getListByObjectIdAll(id);
                List<String> userPosition = listByObjectIdAll.stream().map(UserRelationEntity::getUserId).collect(Collectors.toList());
                List<String> handleIdAll = new ArrayList<>();
                handleIdAll.addAll(userPosition);
                handleIdAll.addAll(id);
                userIdAll.addAll(handleIdAll);
            }
        }
        //获取最新用户
        List<UserEntity> userList = serviceUtil.getUserName(userIdAll, true);
        for (UserEntity userEntity : userList) {
            CirculateEntity circulate = new CirculateEntity();
            circulate.setId(RandomUtil.uuId());
            circulate.setUserId(userEntity.getId());
            circulate.setNodeCode(nodeModel.getNodeId());
            circulate.setNodeName(nodeModel.getNodeName());
            circulate.setTaskId(task.getId());
            circulate.setCirculateRead(0);
            circulate.setOperatorId(operator.getId());
            circulate.setNodeId(operator.getNodeId());
            circulate.setCreatorTime(new Date());
            circulateList.add(circulate);
        }
        circulateService.saveBatch(circulateList);
        return circulateList;
    }
}

