package com.yeejoin.amos.boot.module.hygf.biz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yeejoin.amos.boot.module.hygf.api.Enum.*;
import com.yeejoin.amos.boot.module.hygf.api.config.UserLimits;
import com.yeejoin.amos.boot.module.hygf.api.dto.*;
import com.yeejoin.amos.boot.module.hygf.api.entity.*;
import com.yeejoin.amos.boot.module.hygf.api.fegin.IdxFeginService;
import com.yeejoin.amos.boot.module.hygf.api.mapper.*;
import com.yeejoin.amos.boot.module.hygf.api.service.IPowerStationService;
import com.yeejoin.amos.boot.module.hygf.api.util.RedisLockUtil;
import com.yeejoin.amos.boot.module.hygf.biz.feign.WorkflowFeignClient;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.workflow.model.ProcessTaskDTO;
import com.yeejoin.amos.feign.workflow.model.TaskResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.exception.BaseException;
import org.typroject.tyboot.core.rdbms.annotation.Condition;
import org.typroject.tyboot.core.rdbms.annotation.Operator;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author system_generator
 * @date 2023-07-15
 */
@Service
@Slf4j
public class PowerStationServiceImpl extends BaseService<PowerStationDto, PowerStation, PowerStationMapper> implements IPowerStationService {

    @Autowired
    IdxFeginService idxFeginService;

    @Autowired
    IPowerStationService powerStationService;
    @Autowired
    DesignInformationMapper designInformationMapper;
    @Autowired
    DesignInformationServiceImpl designInformationService;
	@Autowired
	PowerStationEngineeringInfoMapper powerStationEngineeringInfoMapper;
    @Autowired
    PeasantHouseholdServiceImpl peasantHouseholdService;

    private static final String IDX_REQUEST_STATE="200";
    private static final String VERIFY_RESULT_YES="0";
    private static final String VERIFY_RESULT_NO="1";

    @Autowired
    WorkflowFeignClient workflowFeignClient;
    @Autowired
    HouseholdContractServiceImpl householdContractServiceImpl;
    @Autowired
    PersonnelBusinessMapper personnelBusinessMapper;
    @Autowired
    ToDoTasksMapper toDoTasksMapper;
    @Autowired
    protected EmqKeeper emqKeeper;
    @Autowired
    ToDoTasksServiceImpl toDoTasksServiceImpl;
    @Autowired
    UserMessageMapper userMessageMapper;
    @Autowired
    PowerStationMapper powerStationMapper;
    @Autowired
    AmosRequestContext requestContext;
    //    @Autowired
//    WorkflowImpl workflow;
    @Autowired
    WorkFlowService workFlowService;

    @Autowired
	HouseholdContractMapper householdContractMapper;
	@Resource (type = RedisLockUtil.class)
	private RedisLockUtil redisLockUtil;

	public Page<PowerStationDto> queryForPowerStationUserRoles(Page<PowerStationDto> page, String powerStationCode,
															   String ownersName, AgencyUserModel userInfo, String serviceAgent, String regionalCompaniesName, String processStatus,String province, String projectAddress, String status, String startTime, String endTime) {
//        Map<Long, List<RoleModel>> orgRoles = userInfo.getOrgRoles();
//        Collection<List<RoleModel>> roleModels = orgRoles.values();
//        if(roleModels !=null){
//            List<String> roleTypes = new ArrayList<>();
//            Iterator<List<RoleModel>> iterator = roleModels.iterator();
//            while (iterator.hasNext()){
//                List<RoleModel> next = iterator.next();
//                roleTypes.addAll(next.stream().map(RoleModel::getRoleType).collect(Collectors.toList()));
//            }
//            if(roleTypes.size()>0){
//                serviceAgent = !roleTypes.contains("HYGFGLY") ?  roleTypes.contains("HYGFJXS") ? userInfo.getCompanys().get(0).getCompanyName() : null : null ;
//            }
//        }

		// 获取用户所在经销商单位
//        UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto(userInfo.getUserId());
//
//        if(userUnitInformationDto!=null&&userUnitInformationDto.getAmosDealerName()!=null){
//            serviceAgent=userUnitInformationDto.getAmosDealerName();
//        }

		// return
		// this.queryForPowerStationPage(page,powerStationCode,ownersName,serviceAgent);

		Page<PowerStationDto> powerStationDtoPage = this.queryPage((int) page.getCurrent(), (int) page.getSize(), powerStationCode, ownersName,
				serviceAgent, regionalCompaniesName, processStatus,province, projectAddress, status, startTime, endTime);

//		if(powerStationDtoPage.getRecords() != null && powerStationDtoPage.getRecords().size() > 0) {
//			powerStationDtoPage.getRecords().forEach(e -> {
//				if(e.getPowerStationCode() != null) {
//					e.setScale(householdContractMapper.getHygfCommercialScale(e.getPowerStationCode()));
//					e.setRealScale(powerStationEngineeringInfoMapper.getRealScaleByPeasantHouseholdNo(e.getPowerStationCode()));
//				}
//			});
//
//		}
		//优化代码
		List<PowerStationDto> records = powerStationDtoPage.getRecords();
		if(CollectionUtil.isNotEmpty(records)) {
			List<String> powerStationCodeList = new ArrayList<>();
			records.forEach(e -> {
				if(e.getPowerStationCode() != null) {
					powerStationCodeList.add(e.getPowerStationCode());
				}
			});
			if(CollectionUtil.isNotEmpty(powerStationCodeList)){
				List<Map<String, Object>> hygfCommercialScaleList = householdContractMapper.getHygfCommercialScaleList(powerStationCodeList);
				Map<String,String> scaleMap = new HashMap<>();
				if(CollectionUtil.isNotEmpty(hygfCommercialScaleList)){
					for (Map<String, Object> stringStringMap : hygfCommercialScaleList) {
						scaleMap.put(String.valueOf(stringStringMap.get("peasant_household_no")),Objects.isNull(stringStringMap.get("scale")) ? "" : String.valueOf(stringStringMap.get("scale")));
					}
				}
				List<Map<String, Object>> realScaleByPeasantHouseholdNoList = powerStationEngineeringInfoMapper.getRealScaleByPeasantHouseholdNoList(powerStationCodeList);
				Map<String,String> realScaleMap = new HashMap<>();
				if(CollectionUtil.isNotEmpty(realScaleByPeasantHouseholdNoList)){
					for (Map<String, Object> stringStringMap : realScaleByPeasantHouseholdNoList) {
						realScaleMap.put(String.valueOf(stringStringMap.get("peasant_household_no")),Objects.isNull(stringStringMap.get("realScale")) ? "" : String.valueOf(stringStringMap.get("realScale")));
					}
				}
				records.forEach(e -> {
					e.setScale(scaleMap.get(e.getPowerStationCode()));
					e.setRealScale(realScaleMap.get(e.getPowerStationCode()));
				});
			}
		}
		return powerStationDtoPage;
	}

	// 查询电站审核记录
	public Page<PowerStationDto> queryPage(int current, int size, String powerStationCode, String ownersName,
										   String serviceAgent,String regionalCompaniesName,String processStatus,String province,String projectAddress, String status, String startTime, String endTime) {

		PageHelper.startPage(current, size);
		List<PowerStationDto> list = powerStationMapper.queryPage(powerStationCode, ownersName, serviceAgent,regionalCompaniesName,processStatus,province, projectAddress, status, startTime, endTime);

        PageInfo<PowerStationDto> pages = new PageInfo(list);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<PowerStationDto> pagenew = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<PowerStationDto>();
        pagenew.setCurrent(current);
        pagenew.setTotal(pages.getTotal());
        pagenew.setSize(size);
        pagenew.setRecords(pages.getList());

        return pagenew;
    }



        /**
         * 分页查询
         */
    public Page<PowerStationDto> queryForPowerStationPage(Page<PowerStationDto> page,@Condition(Operator.like) String powerStationCode,@Condition(Operator.like) String ownersName,String serviceAgent)   {
        return this.queryForPage(page, "rec_date", false,powerStationCode,ownersName,serviceAgent);
    }

    /**
     * 列表查询 示例
     */
    public List<PowerStationDto> queryForPowerStationList()   {
        return this.queryForList("" , false);
    }


    @Override
    @Transactional
    public boolean savePowerStation(PowerStation powerStation, boolean flag,String name,String meg) {
		try {
            //流程节点code
//            if (flag) {
//                String flowTaskIdnext = this.getTaskNoAuth(powerStation.getProcessInstanceId());
//                WorkDto workDto=this.getNodeInfoCode(flowTaskIdnext);
//                powerStation.setNextProcessNode(workDto.getNextProcessNode());
//                powerStation.setNodeRole(workDto.getNodeRole());
//                powerStation.setNodeRouting(workDto.getNodeRouting());
//            }

			powerStation.setRecDate(new Date());

			//Boolean fl = this.saveOrUpdate(powerStation);
			// 避免生成多份数据
			Boolean fl = this.saveOrUpdate(powerStation,new LambdaQueryWrapper<PowerStation>()
					.eq(PowerStation::getPeasantHouseholdId,powerStation.getPeasantHouseholdId()));

			PowerStationNodeEnum powerStationNodeEnum = PowerStationNodeEnum
					.getNodeByCode(powerStation.getNextProcessNode());

			if (flag) {

				ToDoTasks toDoTasks = null;
				if (PowerStationNodeEnum.经销商上传图纸.getCode().equals(powerStationNodeEnum.getCode())
						|| PowerStationNodeEnum.经销商审核.getCode().equals(powerStationNodeEnum.getCode())) {
					// 获取经销商orgcode
					PeasantHousehold peasantHouseholdd = peasantHouseholdService
							.getById(powerStation.getPeasantHouseholdId());
					toDoTasks = new ToDoTasks(TaskTypeStationEnum.电站审核.getCode(), powerStation.getSequenceNbr(),
							"用户" + name + "电站勘察待" + powerStationNodeEnum.getName(),
							peasantHouseholdd.getDeveloperCode());
					if (PowerStationNodeEnum.经销商审核.getCode().equals(powerStationNodeEnum.getCode())) {
						toDoTasksServiceImpl.addToDoTasksByUserId(peasantHouseholdd.getDeveloperUserId(), toDoTasks,
								meg);
					} else {
						toDoTasksServiceImpl.addToDoTasksByRole(powerStation.getNodeRole(), toDoTasks, meg);
					}
				} else {
					toDoTasks = new ToDoTasks(TaskTypeStationEnum.电站审核.getCode(), powerStation.getSequenceNbr(),
							"用户" + name + "电站勘察待" + powerStationNodeEnum.getName(), null);
					toDoTasksServiceImpl.addToDoTasksByRole(powerStation.getNodeRole(), toDoTasks, meg);
				}
			} else {
				LambdaQueryWrapper<ToDoTasks> wrapper = new LambdaQueryWrapper<>();
				wrapper.eq(ToDoTasks::getType, TaskTypeStationEnum.电站审核.getCode());
				wrapper.eq(ToDoTasks::getState, "待办");
				wrapper.eq(ToDoTasks::getBusinessId, powerStation.getSequenceNbr());
				ToDoTasks doTasks = toDoTasksMapper.selectOne(wrapper);
				if (doTasks != null) {
					doTasks.setState("已办");
					doTasks.setCompleteTime(new Date());

					toDoTasksMapper.updateById(doTasks);
					emqKeeper.getMqttClient().publish("TASK_MESSAGE", JSON.toJSONString(doTasks).getBytes(), 2, false);

					UserMessage userMessage = new UserMessage(doTasks.getType(), doTasks.getBusinessId(),
							doTasks.getAmosUserId(), new Date(), doTasks.getTaskName() + "已完成." + meg,
							doTasks.getAmosOrgCode());
					userMessageMapper.insert(userMessage);
					emqKeeper.getMqttClient().publish("MY_MESSAGE", JSON.toJSONString(userMessage).getBytes(), 2,
							false);

				}
			}

			return fl;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public PowerStation getObjByNhId(String id, String state) {
		LambdaQueryWrapper<PowerStation> wrapper = new LambdaQueryWrapper<>();
		wrapper.ne(PowerStation::getProcessStatus, state);
		wrapper.eq(PowerStation::getPeasantHouseholdId, id);
		return this.baseMapper.selectOne(wrapper);
	}

	@Override
	public String powerStationExamine(long pageId, String nodeCode, String stationId, String taskId,
									  String planInstanceId, Map<String, Object> kv) {
		String lockName = String.format("LockName:powerStationExamine:%s", stationId);
		Boolean isLocked = redisLockUtil.tryLock(lockName, lockName, 10, 1);
		if (BooleanUtils.isNotTrue(isLocked)) {
			throw new com.yeejoin.amos.component.robot.BadRequest("其他用户正在操作，请刷新后再试！");
		}
		String meg = "";
		// 1. 业务相关数据落表
		PowerStation powerStation = this.baseMapper.selectById(stationId);
		PowerStationNodeEnum nodeByCode = PowerStationNodeEnum.getNodeByCode(nodeCode);
		String result = String.valueOf(kv.get("approvalStatus"));
		boolean flag = true;
		if (PowerStationNodeEnum.设计上传图纸.getCode().equals(nodeCode) && Objects.isNull(powerStation.getSjCreateTime())){
			powerStation.setSjCreateTime(new Date());
		}
		if (PowerStationNodeEnum.设计上传图纸.getCode().equals(nodeCode)
				|| PowerStationNodeEnum.经销商上传图纸.getCode().equals(nodeCode)) {

			powerStation.setProcessStatus(PowerStationProcessStateEnum.进行中.getName());
			powerStation.setDrawingReview("");
			this.updateSeve(nodeCode, powerStation.getPeasantHouseholdId(), kv);
		} else {

			if (VERIFY_RESULT_NO.equals(result)) {
				powerStation.setProcessStatus(PowerStationProcessStateEnum.不通过.getName());
			}
			PowerStationProcessStateEnum resultObj = PowerStationProcessStateEnum.getStateByResult(result);
			switch (nodeByCode) {
				case 设计审核:
					powerStation.setTechnologyStatus(resultObj.getName());

					break;
				case 投融审核:
					powerStation.setDesignStatus(resultObj.getName());
					break;
				case 法务审核:
					powerStation.setBusinessStatus(resultObj.getName());

					if (VERIFY_RESULT_YES.equals(result)) {
						LambdaUpdateWrapper<HouseholdContract> lambdaUw = new LambdaUpdateWrapper<>();
						lambdaUw.eq(HouseholdContract::getPeasantHouseholdId, powerStation.getPeasantHouseholdId());
						lambdaUw.set(HouseholdContract::getSurveyStatus, HouseholdContractEnum.勘察状态_已勘察.getCode());
						householdContractServiceImpl.update(lambdaUw);
						powerStation.setKcEndTime(new Date());
					}

					break;
				case 文件审核:
					if (VERIFY_RESULT_YES.equals(result)) {
						flag = false;
						powerStation.setProcessStatus(PowerStationProcessStateEnum.完成.getName());
						powerStation.setSjEndTime(new Date());
					}
					powerStation.setDrawingReview(resultObj.getName());
					break;
				default:
					break;
			}
		}
		meg = "任务明细：" + nodeByCode + (VERIFY_RESULT_YES.equals(result) ? "通过" : "不通过");
		// 2. 更新流程状态
		String code = null;
		try {
			// 3. 工作流执行
			// FeignClientResult<String> submit = idxFeginService.submit(pageId, taskId,
			// planInstanceId, null, null, null, kv);
			// if (IDX_REQUEST_STATE.equals(String.valueOf(submit.getStatus()))) {
			// code = submit.getResult();
			// log.info("流程执行成功：{}", code);
			// 获取流程信息
//                FeignClientResult<JSONObject> record = idxFeginService.getRecord(code);
//                if (IDX_REQUEST_STATE.equals(String.valueOf(record.getStatus()))) {
//                    JSONObject resultObj = record.getResult();
//                    String flowTaskId = String.valueOf(resultObj.get("flowTaskId"));
//
//                }

            // 执行工作流
            BasicGridAcceptance basicGridAcceptance = new BasicGridAcceptance();
//            StandardDto standardDto = new StandardDto();
//            if (PowerStationNodeEnum.设计上传图纸.getCode().equals(nodeCode)
//                    || PowerStationNodeEnum.经销商上传图纸.getCode().equals(nodeCode)) {
//
//                standardDto.setComment(kv.get("approvalInfo") != null ? String.valueOf(kv.get("approvalInfo")) : "");
//                standardDto.setResult("0");
//                standardDto.setTaskId(powerStation.getFlowTaskId());
//                VariableDto variable = new VariableDto();
//                variable.setApprovalStatus("0");
//                variable.setComment(kv.get("approvalInfo") != null ? String.valueOf(kv.get("approvalInfo")) : "");
//                variable.setOperationTime(String.valueOf(kv.get("approveDate")));
//                variable.setOperator("");
//                standardDto.setVariable(variable);
//            } else {
//                standardDto.setComment(kv.get("approvalInfo") != null ? String.valueOf(kv.get("approvalInfo")) : "");
//                standardDto.setResult(String.valueOf(kv.get("approvalStatus")));
//                standardDto.setTaskId(powerStation.getFlowTaskId());
//                VariableDto variable = new VariableDto();
//                variable.setApprovalStatus(String.valueOf(kv.get("approvalStatus")));
//                variable.setComment(kv.get("approvalInfo") != null ? String.valueOf(kv.get("approvalInfo")) : "");
//                variable.setOperationTime(String.valueOf(kv.get("approveDate")));
//                variable.setOperator(String.valueOf(kv.get("approveName")));
//                standardDto.setVariable(variable);
//            }
//            BasicGridAcceptance workBasicGridAcceptance = workflow.standard(basicGridAcceptance, standardDto,
//                    requestContext.getUserId());
            TaskResultDTO taskResultDTO = new TaskResultDTO();
            if (PowerStationNodeEnum.设计上传图纸.getCode().equals(nodeCode)
                    || PowerStationNodeEnum.经销商上传图纸.getCode().equals(nodeCode)) {
                taskResultDTO.setComment(kv.get("approvalInfo") != null ? String.valueOf(kv.get("approvalInfo")) : "");
                taskResultDTO.setResult("0");
                taskResultDTO.setTaskId(powerStation.getFlowTaskId());
                HashMap<String, Object> variableMap = new HashMap<>();
                variableMap.put("approvalStatus", "0");
                variableMap.put("comment", kv.get("approvalInfo") != null ? String.valueOf(kv.get("approvalInfo")) : "");
                variableMap.put("operationTime", String.valueOf(kv.get("approveDate")));
                variableMap.put("operator", "");
                taskResultDTO.setVariable(variableMap);
            } else {
                taskResultDTO.setComment(kv.get("approvalInfo") != null ? String.valueOf(kv.get("approvalInfo")) : "");
                taskResultDTO.setResult(String.valueOf(kv.get("approvalStatus")));
                taskResultDTO.setTaskId(powerStation.getFlowTaskId());
                HashMap<String, Object> variableMap = new HashMap<>();
                variableMap.put("approvalStatus", String.valueOf(kv.get("approvalStatus")));
                variableMap.put("comment", kv.get("approvalInfo") != null ? String.valueOf(kv.get("approvalInfo")) : "");
                variableMap.put("operationTime", String.valueOf(kv.get("approveDate")));
                variableMap.put("operator", String.valueOf(kv.get("approveName")));
                taskResultDTO.setVariable(variableMap);
            }
            ProcessTaskDTO processTaskDTO = workFlowService.standard(basicGridAcceptance, taskResultDTO, requestContext.getUserId());
            powerStation.setFlowTaskId(basicGridAcceptance.getNextTaskId());
            powerStation.setNodeRole(basicGridAcceptance.getNextExecutorIds());
            powerStation.setNodeRouting(basicGridAcceptance.getNextNodeKey() != null
                    ? PowerStationEnum.getNodeByKey(basicGridAcceptance.getNextNodeKey())
                    : "");
            powerStation.setNextProcessNode(basicGridAcceptance.getNextNodeKey());
            powerStation.setPromoter(basicGridAcceptance.getPromoter());
            powerStation.setNextExecuteUserIds(basicGridAcceptance.getNextExecuteUserIds());
            powerStation.setNextNodeName(basicGridAcceptance.getNextNodeName());
            powerStationService.savePowerStation(powerStation, flag, powerStation.getOwnersName(), meg);

			//更新待办
//			WorkflowResultDto workflowResultDto = workFlowService.buildWorkFlowInfo(CollectionUtil.newArrayList(processTaskDTO)).get(0);
//			workflowResultDto.setInstanceId(powerStation.getProcessInstanceId());
//			commonService.updateTaskModelAndAddTask(powerStation, workflowResultDto,BusinessTypeEnum.HYGF_DZ_SH);
			if (!flag) {
				// 更新农户状态
				String peasantHouseholdId = powerStation.getPeasantHouseholdId();
				PeasantHousehold peasantHousehold = peasantHouseholdService.getBaseMapper()
						.selectById(Long.valueOf(peasantHouseholdId));
				peasantHousehold.setSurveyOrNot(3);
				peasantHousehold.setConstructionState(ArrivalStateeEnum.勘察完成.getCode());
				//当勘察完成并且合同双方已盖章 则为待发货
				LambdaQueryWrapper<HouseholdContract> queryWrapper = new LambdaQueryWrapper<>();
				queryWrapper.eq(HouseholdContract::getStatus,"双方已签署");
				queryWrapper.eq(HouseholdContract::getPeasantHouseholdId,peasantHousehold.getSequenceNbr());
				List<HouseholdContract> householdContracts = householdContractMapper.selectList(queryWrapper);
				if (CollectionUtil.isNotEmpty(householdContracts) &&  householdContracts.size()>0 ){
					peasantHousehold.setPreparationMoneyState(ArrivalStateeEnum.待发货.getCode());
				}


				peasantHouseholdService.saveOrUpdate(peasantHousehold);
			}
			// }
		} catch (Exception e) {
			e.printStackTrace();
			log.error("powerStationExamine error:", e);

		} finally {
			redisLockUtil.releaseLock(lockName);
		}
		return code;

//        String meg="";
//        // 1. 业务相关数据落表
//        PowerStation powerStation = this.baseMapper.selectById(stationId);
//        PowerStationNodeEnum nodeByCode = PowerStationNodeEnum.getNodeByCode(nodeCode);
//        String result = String.valueOf(kv.get("approvalStatus"));
//        boolean flag = true;
//        if (PowerStationNodeEnum.设计上传图纸.getCode().equals(nodeCode)||PowerStationNodeEnum.经销商上传图纸.getCode().equals(nodeCode)) {
//
//            powerStation.setProcessStatus(PowerStationProcessStateEnum.进行中.getName());
//
//            this.updateSeve(nodeCode,powerStation.getPeasantHouseholdId(),kv);
//        }  else {
//
//            if (VERIFY_RESULT_NO.equals(result)) {
//                powerStation.setProcessStatus(PowerStationProcessStateEnum.不通过.getName());
//            }
//            PowerStationProcessStateEnum resultObj = PowerStationProcessStateEnum.getStateByResult(result);
//            switch (nodeByCode) {
//                case 设计审核:
//                    powerStation.setTechnologyStatus(resultObj.getName());
//                    break;
//                case 投融审核:
//                    powerStation.setDesignStatus(resultObj.getName());
//                    break;
//                case 法务审核:
//                    powerStation.setBusinessStatus(resultObj.getName());
//
//                    if (VERIFY_RESULT_YES.equals(result)) {
//                        LambdaUpdateWrapper<HouseholdContract> lambdaUw = new LambdaUpdateWrapper<>();
//                        lambdaUw.eq(HouseholdContract::getPeasantHouseholdId, powerStation.getPeasantHouseholdId());
//                        lambdaUw.set(HouseholdContract::getSurveyStatus, HouseholdContractEnum.勘察状态_已勘察.getCode());
//                        householdContractServiceImpl.update(lambdaUw);
//                    }
//
//                    break;
//                case 文件审核:
//                    if (VERIFY_RESULT_YES.equals(result)) {
//                        flag = false;
//                        powerStation.setProcessStatus(PowerStationProcessStateEnum.完成.getName());
//                    }
//                    powerStation.setDrawingReview(resultObj.getName());
//                    break;
//                default:
//                    break;
//            }
//        }
//        meg="任务明细："+nodeByCode+(VERIFY_RESULT_YES.equals(result)?"通过":"不通过");
//        // 2. 更新流程状态
//        String code = null;
//        try{
//            // 3. 工作流执行
//            FeignClientResult<String> submit = idxFeginService.submit(pageId, taskId, planInstanceId, null, null, null, kv);
//            if (IDX_REQUEST_STATE.equals(String.valueOf(submit.getStatus()))) {
//                code = submit.getResult();
//                log.info("流程执行成功：{}", code);
//                // 获取流程信息
//                FeignClientResult<JSONObject> record = idxFeginService.getRecord(code);
//                if (IDX_REQUEST_STATE.equals(String.valueOf(record.getStatus()))) {
//                    JSONObject resultObj = record.getResult();
//                    String flowTaskId = String.valueOf(resultObj.get("flowTaskId"));
//                    powerStation.setFlowTaskId(flowTaskId);
//                }
//                powerStationService.savePowerStation(powerStation, flag,powerStation.getOwnersName(),meg);
//                if(!flag){
//                    //更新农户状态
//                    String peasantHouseholdId = powerStation.getPeasantHouseholdId();
//                    PeasantHousehold peasantHousehold = peasantHouseholdService.getBaseMapper().selectById(Long.valueOf(peasantHouseholdId));
//                    peasantHousehold.setSurveyOrNot(3);
//                    peasantHouseholdService.saveOrUpdate(peasantHousehold);
//                }
//            }
//        }catch (Exception e){
//            throw new  BaseException("获取工作流节点失败！","400","获取工作流节点失败！");
//
//        }
//        return code;
	}



    public WorkDto getNodeInfoCode(String flowTaskId) {
		WorkDto workDto = null;
		FeignClientResult<JSONObject> jSONObject = workflowFeignClient.getNodeInfo(flowTaskId);
		if (IDX_REQUEST_STATE.equals(String.valueOf(jSONObject.getStatus()))) {
			JSONObject js = jSONObject.getResult();
			if (js == null) {
				throw new BaseException("获取工作流节点失败！", "400", "获取工作流节点失败！");
			}
			LinkedHashMap taskInfo = js.get("taskInfo") != null ? (LinkedHashMap) js.get("taskInfo") : null;
			String nextProcessNode = taskInfo != null ? taskInfo.get("taskDefinitionKey").toString() : null;
			List<LinkedHashMap> executor = js.get("executor") != null ? (List<LinkedHashMap>) js.get("executor")
					: null;
			String nodeRole = null;
			if (!executor.isEmpty()) {
				List<String> idList = executor.stream().map(e -> e.get("groupId").toString())
						.collect(Collectors.toList());
				nodeRole = StringUtils.join(idList, ",");
			}

			LinkedHashMap extensionInfo = js.get("extensionInfo") != null ? (LinkedHashMap) js.get("extensionInfo")
					: null;
			String nodeRouting = extensionInfo != null ? extensionInfo.get("nodeRole").toString() : null;
			workDto = new WorkDto(nodeRouting, nodeRole, nextProcessNode);
		}

		return workDto;

	}

	public String getTaskNoAuth(String processInstanceId) {
		String flowTaskId = null;

		JSONObject jSONObject = workflowFeignClient.getTaskNoAuth(processInstanceId);
		if (IDX_REQUEST_STATE.equals(String.valueOf(jSONObject.get("code")))) {
			LinkedHashMap jsd = jSONObject.get("data") != null ? (LinkedHashMap) jSONObject.get("data") : null;
			flowTaskId = jsd != null ? jsd.get("id").toString() : null;
		}
		if (flowTaskId == null) {
			throw new BaseException("获取工作流节点失败！", "400", "获取工作流节点失败！");
		}
		return flowTaskId;

	}

	// 设计信息填充

	public void updateSeve(String nodeCode, String peasantHouseholdId, Map<String, Object> kv) {
		LambdaQueryWrapper<DesignInformation> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(DesignInformation::getPeasantHouseholdId, peasantHouseholdId);
		DesignInformation designInformation = designInformationMapper.selectOne(wrapper);
		if (designInformation != null) {
			DesignInformation designInformationnew = this.mapToBean(kv, DesignInformation.class);

			if (PowerStationNodeEnum.经销商上传图纸.getCode().equals(nodeCode)) {
				designInformation.setPeasantHouseholdId(peasantHouseholdId);
				designInformation.setComponentLayout(designInformationnew.getComponentLayout());
				designInformation.setComponentBracket(designInformationnew.getComponentBracket());
				designInformation.setConnectionLine(designInformationnew.getConnectionLine());
				designInformation.setOnceLine(designInformationnew.getOnceLine());
				designInformationMapper.updateById(designInformation);
			} else {
				// designInformationnew.setTypicalDiagram(designInformationnew.getTypicalDiagram());
				designInformationnew.setPeasantHouseholdId(peasantHouseholdId);
				designInformationnew.setComponentLayout(designInformation.getComponentLayout());
				designInformationnew.setComponentBracket(designInformation.getComponentBracket());
				designInformationnew.setConnectionLine(designInformation.getConnectionLine());
				designInformationnew.setOnceLine(designInformation.getOnceLine());
				designInformationnew.setSequenceNbr(designInformation.getSequenceNbr());
				designInformationnew.setRecDate(designInformation.getRecDate());
				designInformationnew.setRecUserId(designInformation.getRecUserId());
				designInformationnew.setRecUserName(designInformation.getRecUserName());
				designInformationnew.setIsDelete(designInformation.getIsDelete());
				designInformationnew.setCable(designInformation.getCable());
				designInformationMapper.updateById(designInformationnew);
			}
		} else {
			DesignInformation designInformationnew = this.mapToBean(kv, DesignInformation.class);
			designInformationnew.setTypicalDiagram((List<Object>) kv.get("typicalDiagram"));
			designInformationnew.setPeasantHouseholdId(peasantHouseholdId);
			designInformationMapper.insert(designInformationnew);

		}

	}

	public <T> T mapToBean(Map<String, Object> map, Class<T> clazz) {
		ObjectMapper objectMapper = new ObjectMapper();

		T bean = null;
		try {
			bean = clazz.newInstance();
			bean = objectMapper.convertValue(map, clazz);

		} catch (Exception e) {
			throw new BaseException(" 数据转化异常！", "400", "数据转化异常！");
		}
		return bean;
	}

//    private CollectionToList(Collection<? extends E> c){
//        Object[] objects = c.toArray();
//    }

}