package com.zkqy.execution.produce.dispersed.service.impl;

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

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zkqy.common.utils.http.Sending;
import com.zkqy.execution.produce.dispersed.entity.BpmExecuteNodeMiddle;
import com.zkqy.execution.produce.dispersed.entity.runbpm.SysBpmNodeScriptVO;
import com.zkqy.system.entity.CommonEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.zkqy.execution.produce.dispersed.mapper.BpmExecuteNodeMiddleMapper;

import com.zkqy.execution.produce.dispersed.service.IBpmExecuteNodeMiddleService;
import org.springframework.web.client.RestTemplate;

/**
 * 执行流程用户、节点关联脚本中间Service业务层处理
 *
 * @author hzh
 * @date 2023-11-01
 */
@Service
public class BpmExecuteNodeMiddleServiceImpl implements IBpmExecuteNodeMiddleService {

    @Autowired
    private BpmExecuteNodeMiddleMapper bpmExecuteNodeMiddleMapper;


    @Autowired
    private Sending sending;

    // 创建RestTemplate实例
    RestTemplate restTemplate = new RestTemplate();

    /**
     * 查询执行流程用户、节点关联脚本中间
     *
     * @param id 执行流程用户、节点关联脚本中间主键
     * @return 执行流程用户、节点关联脚本中间
     */
    @Override
    public BpmExecuteNodeMiddle selectBpmExecuteNodeMiddleById(Long id) {
        return bpmExecuteNodeMiddleMapper.selectBpmExecuteNodeMiddleById(id);
    }

    /**
     * 查询执行流程用户、节点关联脚本中间列表
     *
     * @param bpmExecuteNodeMiddle 执行流程用户、节点关联脚本中间
     * @return 执行流程用户、节点关联脚本中间
     */
    @Override
    public List<BpmExecuteNodeMiddle> selectBpmExecuteNodeMiddleList(BpmExecuteNodeMiddle bpmExecuteNodeMiddle) {
        return bpmExecuteNodeMiddleMapper.selectBpmExecuteNodeMiddleList(bpmExecuteNodeMiddle);
    }

    /**
     * 新增执行流程用户、节点关联脚本中间
     *
     * @param bpmExecuteNodeMiddle 执行流程用户、节点关联脚本中间
     * @return 结果
     */
    @Override
    public int insertBpmExecuteNodeMiddle(BpmExecuteNodeMiddle bpmExecuteNodeMiddle) {
        return bpmExecuteNodeMiddleMapper.insertBpmExecuteNodeMiddle(bpmExecuteNodeMiddle);
    }

    /**
     * 修改执行流程用户、节点关联脚本中间
     *
     * @param bpmExecuteNodeMiddle 执行流程用户、节点关联脚本中间
     * @return 结果
     */
    @Override
    public int updateBpmExecuteNodeMiddle(BpmExecuteNodeMiddle bpmExecuteNodeMiddle) {
        return bpmExecuteNodeMiddleMapper.updateBpmExecuteNodeMiddle(bpmExecuteNodeMiddle);
    }

    /**
     * 批量删除执行流程用户、节点关联脚本中间
     *
     * @param ids 需要删除的执行流程用户、节点关联脚本中间主键
     * @return 结果
     */
    @Override
    public int deleteBpmExecuteNodeMiddleByIds(Long[] ids) {
        return bpmExecuteNodeMiddleMapper.deleteBpmExecuteNodeMiddleByIds(ids);
    }

    /**
     * 删除执行流程用户、节点关联脚本中间信息
     *
     * @param id 执行流程用户、节点关联脚本中间主键
     * @return 结果
     */
    @Override
    public int deleteBpmExecuteNodeMiddleById(Long id) {
        return bpmExecuteNodeMiddleMapper.deleteBpmExecuteNodeMiddleById(id);
    }

    @Override
    public List<CommonEntity> addExceptionScript(List<CommonEntity> commonEntityList) throws Exception {
        //循环得到所有异常脚本key
        Set<String> scriptKeys = new LinkedHashSet<>();
        commonEntityList.forEach(m -> {
            scriptKeys.addAll(Arrays.asList(m.getResultMap().get("benmTaskArtificialScriptKey").toString().split(",")));
        });
        if(scriptKeys.size() == 0){
            return commonEntityList;
        }
        //根据异常脚本key得到所有异常脚本信息
        ResponseEntity responseEntity;
        try {
             responseEntity = sending.sendGetScriptInfo(scriptKeys);
        }catch (Exception e){
            throw new Exception("网络错误");
        }
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> map = objectMapper.readValue(responseEntity.getBody().toString(),Map.class);
            List<Object> sysBpmNodeScriptVOList = (List<Object>) map.get("data");
            return commonEntityList.stream().map(m -> {
                List<String> scriptKeyList = Arrays.asList(m.getResultMap().get("benmTaskArtificialScriptKey").toString().split(","));
                List<SysBpmNodeScriptVO> exceptionScriptList = new ArrayList<>();
                sysBpmNodeScriptVOList.forEach(s -> {
                    SysBpmNodeScriptVO sysBpmNodeScriptVO= JSONObject.parseObject(JSON.toJSONString(s),SysBpmNodeScriptVO.class);
                    if (scriptKeyList.contains(sysBpmNodeScriptVO.getScriptKey())) {
                        exceptionScriptList.add(sysBpmNodeScriptVO);
                    }
                });
                m.getResultMap().put("exceptionScriptList", exceptionScriptList);
                return m;
            }).collect(Collectors.toList());
        } else {
            return commonEntityList;
        }

    }
}
