package com.ruoyi.system.service.impl;

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

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.entity.BpmNodeHandleUser;
import com.ruoyi.system.entity.BpmNodeScriptRelevance;
import com.ruoyi.system.entity.vo.NodeVo;
import com.ruoyi.system.service.IBpmNodeHandleUserService;
import com.ruoyi.system.service.IBpmNodeScriptRelevanceService;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.BpmProcessConfigurationMapper;
import com.ruoyi.system.entity.BpmProcessConfiguration;
import com.ruoyi.system.service.IBpmProcessConfigurationService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 流程配置Service业务层处理
 *
 * @author hzh
 * @date 2023-10-20
 */
@Service
public class BpmProcessConfigurationServiceImpl implements IBpmProcessConfigurationService {

    @Autowired  // 流程节点配置
    private BpmProcessConfigurationMapper bpmProcessConfigurationMapper;
    @Autowired  // 节点执行用户
    private IBpmNodeHandleUserService iBpmNodeHandleUserService;
    @Autowired  // 节点执行脚本
    private IBpmNodeScriptRelevanceService iBpmNodeScriptRelevanceService;

    /**
     * 查询流程配置
     *
     * @param id 流程配置主键
     * @return 流程配置
     */
    @Override
    public BpmProcessConfiguration selectBpmProcessConfigurationById(Long id) {
        return bpmProcessConfigurationMapper.selectBpmProcessConfigurationById(id);
    }

    /**
     * 查询流程配置列表
     *
     * @param bpmProcessConfiguration 流程配置
     * @return 流程配置
     */
    @Override
    public List<BpmProcessConfiguration> selectBpmProcessConfigurationList(BpmProcessConfiguration bpmProcessConfiguration) {
        return bpmProcessConfigurationMapper.selectBpmProcessConfigurationList(bpmProcessConfiguration);
    }

    /**
     * 新增流程配置
     *
     * @param bpmProcessConfigurationList 流程配置
     * @return 结果
     */
    @Override
    public int insertBpmProcessConfiguration(List<BpmProcessConfiguration> bpmProcessConfigurationList) {
        return bpmProcessConfigurationMapper.insertBpmProcessConfiguration(bpmProcessConfigurationList);
    }

    /**
     * 修改流程配置
     *
     * @param bpmProcessConfigurationList 流程配置
     * @return 结果
     */
    @Override
    public int updateBpmProcessConfiguration(BpmProcessConfiguration bpmProcessConfigurationList) {
         //bpmProcessConfigurationList.forEach(node -> node.setUpdateTime(DateUtils.getNowDate()));
        return bpmProcessConfigurationMapper.updateBpmProcessConfiguration(bpmProcessConfigurationList);
    }

    /**
     * 批量删除流程配置
     *
     * @param ids 需要删除的流程配置主键
     * @return 结果
     */
    @Override
    public int deleteBpmProcessConfigurationByIds(Long[] ids) {
        return bpmProcessConfigurationMapper.deleteBpmProcessConfigurationByIds(ids);
    }

    /**
     * 删除流程配置信息
     *
     * @param id 流程配置主键
     * @return 结果
     */
    @Override
    public int deleteBpmProcessConfigurationById(Long id) {
        return bpmProcessConfigurationMapper.deleteBpmProcessConfigurationById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBpmProcessNodeConfig(NodeVo nodeVo) {
        // 新增节点配置
        if (nodeVo.getBpmProcessConfigurationList().size() != 0)
            nodeVo.getBpmProcessConfigurationList().stream().forEach(e->{
                e.setCreateById(SecurityUtils.getUserId());
                e.setCreateBy(SecurityUtils.getUsername());
                e.setCreateTime(DateUtils.getNowDate());
            });
            bpmProcessConfigurationMapper.insertBpmProcessConfiguration(nodeVo.getBpmProcessConfigurationList());
        // 新增节点执行用户
        if (nodeVo.getBpmNodeHandleUserList().size() != 0)
            iBpmNodeHandleUserService.insertBpmNodeHandleUser(nodeVo.getBpmNodeHandleUserList());
        // 新增节点脚本关系
        if (nodeVo.getBpmNodeScriptRelevanceList().size() != 0)
            iBpmNodeScriptRelevanceService.insertBpmNodeScriptRelevance(nodeVo.getBpmNodeScriptRelevanceList());
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBpmProcessNodeConfig(NodeVo nodeVo) {
        // 修改节点配置
        if (nodeVo.getBpmProcessConfigurationList().size() != 0) {
            // 定义存储修改操作中新增节点，根据id为null来判断是否新增数据条
            List<BpmProcessConfiguration> addList = new ArrayList<>();
            // List<BpmProcessConfiguration> removeList = new ArrayList<>();
            nodeVo.getBpmProcessConfigurationList().forEach(item -> {
                if (item.getId() == null) {
                    // 把需要新增的数据添加到addList集合里边
                    addList.add(item);
                }
            });

            // 从大集合里边移除需要添加的节点
            nodeVo.getBpmProcessConfigurationList().removeAll(addList);

            //修改操作(一共四个节点、)
            nodeVo.getBpmProcessConfigurationList().forEach(item->{
                item.setUpdateTime(DateUtils.getNowDate());
                item.setUpdateById(SecurityUtils.getUserId());
                item.setUpdateBy(SecurityUtils.getUsername());
                bpmProcessConfigurationMapper.updateBpmProcessConfiguration(item);
            });

            // 新增操作
            if (addList.size() != 0){
                addList.parallelStream().forEach(item->{
                    item.setCreateTime(DateUtils.getNowDate());
                    item.setCreateBy(SecurityUtils.getUsername());
                    item.setCreateById(SecurityUtils.getUserId());
                });
                bpmProcessConfigurationMapper.insertBpmProcessConfiguration(addList);
            }

        }

        // 修改节点执行用户
        if (nodeVo.getBpmNodeHandleUserList().size() != 0) {
            List<BpmNodeHandleUser> addList1 = new ArrayList<>();
            Iterator<BpmNodeHandleUser> iterator = nodeVo.getBpmNodeHandleUserList().iterator();
            while (iterator.hasNext()) {
                BpmNodeHandleUser item = iterator.next();
                if (item.getId() == null) {
                    addList1.add(item);
                    iterator.remove();
                }
            }
            iBpmNodeHandleUserService.updateBpmNodeHandleUser(nodeVo.getBpmNodeHandleUserList());
            if (addList1.size() != 0)
                iBpmNodeHandleUserService.insertBpmNodeHandleUser(addList1);
        }

        // 修改节点脚本关系
        if (nodeVo.getBpmNodeScriptRelevanceList().size() != 0) {
            List<BpmNodeScriptRelevance> addList2 = new ArrayList<>();
            Iterator<BpmNodeScriptRelevance> iterator = nodeVo.getBpmNodeScriptRelevanceList().iterator();
            while (iterator.hasNext()) {
                BpmNodeScriptRelevance item = iterator.next();
                if (item.getId() == null) {
                    addList2.add(item);
                    iterator.remove();
                }
            }

            iBpmNodeScriptRelevanceService.updateBpmNodeScriptRelevance(nodeVo.getBpmNodeScriptRelevanceList());
            if (addList2.size() != 0)
                iBpmNodeScriptRelevanceService.insertBpmNodeScriptRelevance(addList2);
        }
        // 删除废弃的节点
        if(nodeVo.getRemoveNodeIds().length>0){
            //要删除的节点更新状态
            for (Long removeNodeId : nodeVo.getRemoveNodeIds()) {
                BpmProcessConfiguration bpmProcessConfiguration=new BpmProcessConfiguration();
                bpmProcessConfiguration.setUpdateBy(SecurityUtils.getUsername());
                bpmProcessConfiguration.setUpdateById(SecurityUtils.getUserId());
                bpmProcessConfiguration.setUpdateTime(DateUtils.getNowDate());
                bpmProcessConfiguration.setId(removeNodeId);
                bpmProcessConfiguration.setDelFlag("2");
                bpmProcessConfigurationMapper.updateBpmProcessConfiguration(bpmProcessConfiguration);
            }
            //bpmProcessConfigurationMapper.deleteBpmProcessConfigurationByIds(nodeVo.getRemoveNodeIds());
        }
        return 1;
    }

    @Override
    public NodeVo selectByProcessByKey(String nodeProcessKey) {
        // 根据流程别名的到所有节点信息
        List<BpmProcessConfiguration> bpmProcessConfigurationList = bpmProcessConfigurationMapper.selectBpmProcessConfigurationList(new BpmProcessConfiguration(nodeProcessKey));
        // 根据节点别名得到所有脚本信息
        List<BpmNodeScriptRelevance> bpmNodeScriptRelevanceList = new ArrayList<>();
        // 根据节点别名得到所有执行用户信息
        List<BpmNodeHandleUser> bpmNodeHandleUserList = new ArrayList<>();
        bpmProcessConfigurationList.forEach(item -> {
            if (item.getNodeKey() != null)
                bpmNodeScriptRelevanceList.addAll(iBpmNodeScriptRelevanceService.selectBpmNodeScriptRelevanceList(new BpmNodeScriptRelevance(item.getNodeKey())));
            if (item.getNodeRolePermission() != null)
                bpmNodeHandleUserList.addAll(iBpmNodeHandleUserService.selectBpmNodeHandleUserList(new BpmNodeHandleUser(item.getNodeRolePermission())));
        });
        NodeVo nodeVo = new NodeVo();
        nodeVo.setBpmNodeHandleUserList(bpmNodeHandleUserList);
        nodeVo.setBpmProcessConfigurationList(bpmProcessConfigurationList);
        nodeVo.setBpmNodeScriptRelevanceList(bpmNodeScriptRelevanceList);
        return nodeVo;
    }
}
