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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
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.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.module.hygf.api.Enum.*;
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.mapper.*;
import com.yeejoin.amos.boot.module.hygf.api.service.IBasicGridAcceptanceService;
import com.yeejoin.amos.boot.module.hygf.api.util.CommonResponseNewUtil;
import com.yeejoin.amos.boot.module.hygf.api.util.NumberUtil;
import com.yeejoin.amos.boot.module.hygf.biz.vo.RouthPathVO;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowBatchDTO;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowStartDTO;
import com.yeejoin.amos.feign.workflow.model.ProcessTaskDTO;
import com.yeejoin.amos.feign.workflow.model.TaskResultDTO;
import com.yeejoin.amos.boot.module.hygf.api.util.RedisLockUtil;
import com.yeejoin.amos.component.robot.BadRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

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

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class BasicGridAcceptanceServiceImpl extends BaseService<BasicGridAcceptanceDto, BasicGridAcceptance, BasicGridAcceptanceMapper> implements IBasicGridAcceptanceService {

	@Autowired
	BasicGridAcceptanceMapper basicGridAcceptanceMapper;
	@Autowired
	HygfOnGridMapper onGridMapper;
	@Autowired
	private WorkFlowService workFlowService;
	@Autowired
	HygfOnGridServiceImpl hygfOnGridServiceImpl;
	@Autowired
	PersonnelBusinessMapper personnelBusinessMapper;
	@Autowired
	PowerStationEngineeringInfoMapper powerStationEngineeringInfoMapper;
//	@Autowired
//	WorkflowImpl workflow;
	@Autowired
	AcceptanceCheckItemMapper acceptanceCheckItemMapper;
	@Autowired
	AcceptanceRectificationOrderMapper acceptanceRectificationOrderMapper;
	@Autowired
	RegionalCompaniesMapper regionalCompaniesMapper;
	@Autowired
	WorkOrderMapper workOrderMapper;
	@Resource(type = RedisLockUtil.class)
	private RedisLockUtil redisLockUtil;
	@Autowired
	PeasantHouseholdMapper peasantHouseholdMapper;
	@Autowired
	HouseholdContractMapper householdContractMapper;

	@Autowired
	RectificationOrderAuditingServiceImpl rectificationOrderAuditingService;
	@Autowired
	HygfRectificationOrderServiceImpl rectificationOrderService;
	@Autowired
	BasicGridAuditingServiceImpl basicGridAuditingService;
	@Autowired
	BasicGridRecordServiceImpl basicGridRecordService;
	@Autowired
	AcceptanceCheckServiceImpl acceptanceCheckService;
	@Autowired
	ConstructionGirdRecordsServiceImpl constructionGirdRecords;
	@Autowired
	ToDoTasksServiceImpl toDoTasksService;

	private final String OK = "0";
	private final String PASS = "5";

	public Page<BasicGridRecordDto> selectPage(Long regionCompanyId, Long amosDealerId, int current, int size,
											   String projectAddress, String powerStationCode, String ownersName, String gridStatus,
											   String gridConnectionTime, String formType, List<String> basicGridNodes, String type, String province, String developerName, String regionalCompaniesName, String startTime, String endTime,String routhPathId)
			throws Exception {
		PageHelper.startPage(current, size);
		Map<String, Object> map = new HashMap<>();
		Date date = null;
//        if (StringUtils.isNotEmpty(gridConnectionTime)) {
//            date = DateUtil.formatStringToDate(gridConnectionTime, "yyyy-MM-dd HH:mm:ss");
//        }
		map.put("projectAddress", projectAddress);
		map.put("powerStationCode", powerStationCode);
		map.put("ownersName", ownersName);
		map.put("gridStatus", gridStatus);
		map.put("gridConnectionTime", gridConnectionTime);
		map.put("formType", formType);
		map.put("regionCompanyId", regionCompanyId);
		map.put("amosDealerId", amosDealerId);
		map.put("basicGridNodes", basicGridNodes);
		map.put("type", type);
		map.put("province", province);
		map.put("developerName", developerName);
		map.put("regionalCompaniesName", regionalCompaniesName);
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		map.put("routhPathId", routhPathId);
		List<BasicGridRecordDto> list = basicGridAcceptanceMapper.selectPageList(map);
		PageInfo<BasicGridRecordDto> page = new PageInfo(list);
		Page<BasicGridRecordDto> pageNew = new Page<>();
		pageNew.setCurrent(current);
		pageNew.setTotal(page.getTotal());
		pageNew.setSize(size);

		if (page.getList() != null && page.getList().size() > 0) {
			page.getList().forEach(e -> {
				if (e.getPeasantHouseholdNo() != null) {
					e.setScale(householdContractMapper.getHygfCommercialScale(e.getPeasantHouseholdNo()));
					e.setRealScale(powerStationEngineeringInfoMapper
							.getRealScaleByPeasantHouseholdNo(e.getPeasantHouseholdNo()));
				}
			});
		}

		pageNew.setRecords(page.getList());
		return pageNew;
	}

	public synchronized HygfOnGrid saveEntity(HygfOnGrid grid) {
		LambdaQueryWrapper<HygfOnGrid> hog = new LambdaQueryWrapper<>();
		hog.eq(HygfOnGrid::getPeasantHouseholdId, grid.getPeasantHouseholdId());
		hygfOnGridServiceImpl.saveOrUpdate(grid, hog);
		return grid;
	}

	public void testKAIQI() {
		// 开启工作流 并执行一步
		ActWorkflowBatchDTO actWorkflowBatchDTO = new ActWorkflowBatchDTO();
		List<ActWorkflowStartDTO> params = new ArrayList<>();
		ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
		dto.setProcessDefinitionKey("BINGWANGTEST");
		dto.setBusinessKey(String.valueOf(new Date().getTime()));
		dto.setCompleteFirstTask(true);
		HashMap<String, Object> map = new HashMap<>();
		map.put("approvalStatus", "0");
		dto.setVariables(map);
		params.add(dto);
		actWorkflowBatchDTO.setProcess(params);
		List<ProcessTaskDTO> processTaskDTOS = workFlowService.startBatch(actWorkflowBatchDTO);
		List<WorkflowResultDto> workflowResultDtos = workFlowService.buildWorkFlowInfos(processTaskDTOS);

		workflowResultDtos.forEach(e -> {
			BasicGridAuditingDto basicGridAuditingDto = new BasicGridAuditingDto();
			BeanUtils.copyProperties(e, basicGridAuditingDto);
			basicGridAuditingDto.setPeasantHouseholdId(20248001107L);
			basicGridAuditingDto.setPromoter(RequestContext.getExeUserId());
			basicGridAuditingService.createWithModel(basicGridAuditingDto);
		});

	}

	public void zhixing(String approvalStatus, String comment) {
		LambdaQueryWrapper<BasicGridAuditing> query = new LambdaQueryWrapper<>();
		query.eq(BasicGridAuditing::getPeasantHouseholdId, 20248001107L);
		query.eq(BasicGridAuditing::getNextNodeKey, "gongchengshenhe");
		query.orderByDesc(BaseEntity::getRecDate);
		query.last("limit 1");
		BasicGridAuditing basicGridAuditing = basicGridAuditingService.getBaseMapper().selectOne(query);

		// 组装信息
		TaskResultDTO task = new TaskResultDTO();

		task.setTaskId(basicGridAuditing.getNextTaskId());
		HashMap<String, Object> map = new HashMap<>();
		BasicGridAuditingDto basicGridAuditingDto = new BasicGridAuditingDto();
		task.setResultCode("approvalStatus");
		map.put("approvalStatus", approvalStatus);
		task.setComment(comment == null ? "" : comment);
		task.setVariable(map);
		// 执行流程
		ProcessTaskDTO processTaskDTO = workFlowService.complete(basicGridAuditing.getNextTaskId(), task);
		List<WorkflowResultDto> workflowResultDtos = workFlowService
				.buildWorkFlowInfo(CollectionUtil.newArrayList(processTaskDTO));
		WorkflowResultDto workflowResultDto = workflowResultDtos.get(0);
		BeanUtils.copyProperties(workflowResultDto, basicGridAuditingDto);
		basicGridAuditingDto.setPeasantHouseholdId(basicGridAuditing.getPeasantHouseholdId());
		basicGridAuditingDto.setPromoter(basicGridAuditing.getPromoter());
		basicGridAuditingDto.setStatus(approvalStatus);
		if (null == basicGridAuditingDto.getInstanceId()) {
			basicGridAuditingDto.setInstanceId(basicGridAuditing.getInstanceId());
		}
		basicGridAuditingService.createWithModel(basicGridAuditingDto);
	}

	public synchronized HygfOnGrid saveAndCommit(HygfOnGrid grid, String realName) {

		BasicGridRecord basicGridRecord = basicGridRecordService.getBaseMapper()
				.selectOne(new LambdaQueryWrapper<BasicGridRecord>().eq(BasicGridRecord::getWorkOrderPowerStationId,
						grid.getWorkOrderPowerStationId()));

		LambdaUpdateWrapper<BasicGridRecord> update = new LambdaUpdateWrapper<>();
		update.set(BasicGridRecord::getGridStatus, GridStatusEnum.JXSGLYDSH.getCode());
		update.set(BasicGridRecord::getBasicGridNode, "jxsAdmin");
		if (grid.getType() != null && "1".equals(grid.getType())) {
			// 执行工作流
			this.wofkflowExcute(basicGridRecord.getInstanceId(), "0", "重新登记", BusinessWorkflowKey.并网登记.getCode());
			update.set(BasicGridRecord::getPowerStationAreaStatus, null);
			update.set(BasicGridRecord::getPowerStationDesignStatus, null);
			update.set(BasicGridRecord::getPowerStationEngineeringStatus, null);
		} else {
			// 开启工作流 并执行一步
			ActWorkflowBatchDTO actWorkflowBatchDTO = new ActWorkflowBatchDTO();
			List<ActWorkflowStartDTO> params = new ArrayList<>();
			ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
			dto.setProcessDefinitionKey("GridConnected");
			dto.setBusinessKey(String.valueOf(new Date().getTime()));
			dto.setCompleteFirstTask(true);
			HashMap<String, Object> map = new HashMap<>();
			map.put("approvalStatus", "0");
			dto.setVariables(map);
			params.add(dto);
			actWorkflowBatchDTO.setProcess(params);
			List<ProcessTaskDTO> processTaskDTOS = workFlowService.startBatch(actWorkflowBatchDTO);
			List<WorkflowResultDto> workflowResultDtos = workFlowService.buildWorkFlowInfo(processTaskDTOS);

			WorkflowResultDto workflowResultDto = workflowResultDtos.get(0);
			BasicGridAuditingDto basicGridAuditingDto = new BasicGridAuditingDto();
			BeanUtils.copyProperties(workflowResultDto, basicGridAuditingDto);
			basicGridAuditingDto.setPeasantHouseholdId(grid.getPeasantHouseholdId());
			basicGridAuditingDto.setPromoter(RequestContext.getExeUserId());
			basicGridAuditingService.createWithModel(basicGridAuditingDto);
			update.set(BasicGridRecord::getInstanceId, basicGridAuditingDto.getInstanceId());

			// 线上验收
			LambdaUpdateWrapper<PeasantHousehold> up = new LambdaUpdateWrapper<>();
			up.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.并网中.getCode());
			long idsk = basicGridRecord.getPeasantHouseholdId();
			up.eq(PeasantHousehold::getSequenceNbr, idsk);
			peasantHouseholdMapper.update(null, up);
			//完成新增并网
			ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.并网.getCode(), idsk);
			toDoTasksService.completeToDoTasks(toDoTasks1,"");
			//发起待办
			PeasantHousehold peasantHousehold = peasantHouseholdMapper.selectById(grid.getPeasantHouseholdId());
			String taskName="您有一条并网的待办";
			String orgCode="";
			if(Objects.nonNull(peasantHousehold)){
				taskName=peasantHousehold.getOwnersName() +"待经销商管理员审核" ;
				orgCode=peasantHousehold.getRegionalCompaniesCode();
			}
			RouthPathVO routhPathVO = new RouthPathVO();
			routhPathVO.setRouthPathId(String.valueOf(grid.getPeasantHouseholdId()));
			String routhPath = toDoTasksService.getRouthPath(TaskTypeStationEnum.并网.getCode(),workflowResultDto.getNextNodeKey(), routhPathVO);
			String wxRouthPath = toDoTasksService.getWxRouthPath(TaskTypeStationEnum.并网.getCode(),workflowResultDto.getNextNodeKey(), routhPathVO);
			ToDoTasks toDoTasks=  new ToDoTasks (TaskTypeStationEnum.并网.getCode(),  grid.getPeasantHouseholdId(),  taskName, orgCode,routhPath,wxRouthPath);
			List<String> userIds = Arrays.asList(Optional.ofNullable(workflowResultDto.getNextExecuteUserIds()).orElse("").split(","));
			List<String> filterUsers = toDoTasksService.filterUsers(TaskTypeStationEnum.并网.getCode(), workflowResultDto.getNextNodeKey(),userIds, orgCode, peasantHousehold.getDeveloperCode());
			toDoTasksService.addToDoTasksByUserIds(filterUsers,toDoTasks);
		}

		// 防止重复提交
//		if (grid.getSequenceNbr() != null) {
//			onGridMapper.updateById(grid);
//		} else {
//			onGridMapper.insert(grid);
//		}
		LambdaQueryWrapper<HygfOnGrid> hog = new LambdaQueryWrapper<>();
		hog.eq(HygfOnGrid::getPeasantHouseholdId, grid.getPeasantHouseholdId());
		hygfOnGridServiceImpl.saveOrUpdate(grid, hog);

		update.eq(BaseEntity::getSequenceNbr, basicGridRecord.getSequenceNbr());
		basicGridRecordService.update(null, update);
		Date date = new Date();
		ConstructionGirdRecords da = new ConstructionGirdRecords(realName, "提交并网资料", date, "",
				basicGridRecord.getSequenceNbr(), basicGridRecord.getWorkOrderPowerStationId(),
				basicGridRecord.getPeasantHouseholdId(), "");
		constructionGirdRecords.save(da);

		//更新并网创建时间
		BasicGridRecord gridRecord = basicGridRecordService.getBaseMapper().selectById(basicGridRecord.getSequenceNbr());
		if(Objects.nonNull(gridRecord) && Objects.isNull(gridRecord.getBwCreateTime())){
			LambdaUpdateWrapper<BasicGridRecord> wrapper = new LambdaUpdateWrapper<>();
			wrapper.set(BasicGridRecord::getBwCreateTime, date);
			wrapper.eq(BaseEntity::getSequenceNbr, basicGridRecord.getSequenceNbr());
			basicGridRecordService.update(null, wrapper);
		}

		return grid;
	}

	public HygfOnGrid modifyEntity(HygfOnGrid grid) {
		onGridMapper.updateById(grid);
		return grid;
	}

	public Boolean deleteForBatch(Long[] sequenceNbrs) {
		if (Objects.isNull(sequenceNbrs) || sequenceNbrs.length == 0) {
			return false;
		}
		Boolean bool = Boolean.TRUE;
		Collection<HygfOnGrid> grids = onGridMapper.selectBatchIds(Arrays.asList(sequenceNbrs));
		for (HygfOnGrid x : grids) {
			x.setIsDelete(true);
			int num = onGridMapper.updateById(x);
			BasicGridAcceptance acceptance = basicGridAcceptanceMapper
					.selectOne(new LambdaQueryWrapper<BasicGridAcceptance>()
							.eq(BasicGridAcceptance::getWorkOrderPowerStationId, x.getWorkOrderPowerStationId()));
			acceptance.setIsDelete(true);
			int count = basicGridAcceptanceMapper.updateById(acceptance);
			if (0 == num || 0 == count) {
				bool = Boolean.FALSE;
				break;
			}
		}
		return bool;
	}

	@Transactional
	public void execute(AcceptanceCheckItem dto, String userId) {
		String lockName = String.format("LockName:executeWorkflow:%s", dto.getBasicGridAcceptanceId());
		Boolean isLocked = redisLockUtil.tryLock(lockName, lockName, 10, 1);
		if (BooleanUtils.isNotTrue(isLocked)) {
			throw new BadRequest("其他用户正在操作，请刷新后再试！");
		}
		try {
			// 查询并网审批信息
			BasicGridAcceptance basicGridAcceptanc = basicGridAcceptanceMapper
					.selectById(dto.getBasicGridAcceptanceId());
			String beforeAcceptanceStatus = basicGridAcceptanc.getAcceptanceStatus();
			String nextNodeKey = basicGridAcceptanc.getNextNodeKey();
			if (OK.equals(dto.getApprovalStatus())) {
				if (BasicGridAcceptancEnum.并网管理端工程审核.getCode().equals(nextNodeKey)) {
					basicGridAcceptanc.setGridStatus(GridStatusEnum.YWC.getCode());
					basicGridAcceptanc.setAcceptanceStatus(AcceptanceStatusEnum.待提交验收.getCode());
					// 并网时间
					LambdaUpdateWrapper<HygfOnGrid> upq = new LambdaUpdateWrapper();
					upq.eq(HygfOnGrid::getSequenceNbr, dto.getFonGridId());
					upq.set(HygfOnGrid::getGridConnectionTime, new Date());
					onGridMapper.update(null, upq);
					// 并网完成
					LambdaUpdateWrapper<PeasantHousehold> up = new LambdaUpdateWrapper<>();
					up.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.并网完成.getCode());
					long idsk = basicGridAcceptanc.getPeasantHouseholdId();
					up.eq(PeasantHousehold::getSequenceNbr, idsk);
					peasantHouseholdMapper.update(null, up);

					//生成验收待办
					PeasantHousehold peasantHousehold = peasantHouseholdMapper.selectById(basicGridAcceptanc.getPeasantHouseholdId());
					RouthPathVO routhPathVO = new RouthPathVO();
					routhPathVO.setRouthPathId(String.valueOf(basicGridAcceptanc.getPeasantHouseholdId()));
					String routhPath = toDoTasksService.getRouthPath(TaskTypeStationEnum.验收.getCode(), HygfRouthTypeEnum.HYGF_XZYSTJ.getCode(), routhPathVO);
					String wxRouthPath = toDoTasksService.getWxRouthPath(TaskTypeStationEnum.验收.getCode(), HygfRouthTypeEnum.HYGF_XZYSTJ.getCode(), routhPathVO);
					ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.验收.getCode(),  basicGridAcceptanc.getPeasantHouseholdId(),   peasantHousehold.getOwnersName()+"待新增验收提交",peasantHousehold.getRegionalCompaniesCode(),routhPath,wxRouthPath);
					String roleId = toDoTasksService.getRoleIdByName("户用光伏-经销商-工程");
					List<String> todoUserIds = toDoTasksService.getTodoUserIds(peasantHousehold.getRegionalCompaniesCode(), roleId);
					List<String> filterUsers = toDoTasksService.filterUsers(TaskTypeStationEnum.验收.getCode(), HygfRouthTypeEnum.HYGF_XZYSTJ.getCode(), todoUserIds, peasantHousehold.getRegionalCompaniesCode(), peasantHousehold.getDeveloperCode());
					toDoTasksService.addToDoTasksByUserIds(filterUsers,toDoTasks1);
				} else {
					AcceptanceStatusEnum acceptanceStatus = AcceptanceStatusEnum.getAcceptanceStatusByKey(nextNodeKey,
							dto.getApprovalStatus());
					if (acceptanceStatus == null) {
						// 说明工作流节点状态执行错误
						throw new BadRequest("其他用户正在操作，请刷新后再试！");
					}
					basicGridAcceptanc.setAcceptanceStatus(
							AcceptanceStatusEnum.getNodeByKey(nextNodeKey, dto.getApprovalStatus()));
				}

			} else {
				if (BasicGridAcceptancEnum.并网管理端工程审核.getCode().equals(nextNodeKey)) {
					basicGridAcceptanc.setGridStatus(GridStatusEnum.WTG.getCode());
					basicGridAcceptanc.setAcceptanceStatus(
							AcceptanceStatusEnum.getNodeByKey(nextNodeKey, dto.getApprovalStatus()));
				}
				// 投融/法务/工程/线下验收审核不通过
				else if (BasicGridAcceptancEnum.管理端投融审核.getCode().equals(nextNodeKey)
						|| BasicGridAcceptancEnum.管理端法务审核.getCode().equals(nextNodeKey)
						|| BasicGridAcceptancEnum.管理端工程审核.getCode().equals(nextNodeKey)
						|| BasicGridAcceptancEnum.管理端工程线下验.getCode().equals(nextNodeKey)) {
					AcceptanceRectificationOrder rectificationOrder = new AcceptanceRectificationOrder();
					try {
						WorkOrder workOrder = workOrderMapper.selectById(basicGridAcceptanc.getWorkOrderId());
						RegionalCompanies regionalCompanies = regionalCompaniesMapper
								.selectRegionName(workOrder.getRegionCompanyId());
						String code = NumberUtil.getCode(CodeEnum.整改单.getCode(), regionalCompanies.getCompanyCode(),
								regionalCompanies.getRegionalAddress());
						rectificationOrder.setRectificationOrderCode(code);
						rectificationOrder.setWorkOrderId(basicGridAcceptanc.getWorkOrderId());
						rectificationOrder.setWorkOrderPowerStationId(basicGridAcceptanc.getWorkOrderPowerStationId());
						rectificationOrder.setPeasantHouseholdId(basicGridAcceptanc.getPeasantHouseholdId());
						rectificationOrder.setProblemDescription(dto.getComment());
						rectificationOrder
								.setRectificationStatus(String.valueOf(RectificationStatusEnum.待整改.getCode()));
					} catch (Exception e) {
						throw new RuntimeException(e);
					}
					acceptanceRectificationOrderMapper.insert(rectificationOrder);
					basicGridAcceptanc.setAcceptanceStatus(
							AcceptanceStatusEnum.getNodeByKey(nextNodeKey, dto.getApprovalStatus()));
				} else {
					AcceptanceStatusEnum acceptanceStatus = AcceptanceStatusEnum.getAcceptanceStatusByKey(nextNodeKey,
							dto.getApprovalStatus());
					if (acceptanceStatus == null) {
						// 说明工作流节点状态执行错误
						throw new BadRequest("其他用户正在操作，请刷新后再试！");
					}
					basicGridAcceptanc.setAcceptanceStatus(
							AcceptanceStatusEnum.getNodeByKey(nextNodeKey, dto.getApprovalStatus()));
				}
			}

			if (AcceptanceStatusEnum.线下验收不通过.getCode().equals(basicGridAcceptanc.getAcceptanceStatus())) {
				if (AcceptanceStatusEnum.线下验收完成.getCode().equals(beforeAcceptanceStatus)) {
					throw new BadRequest("验收状态已更改为线下验收不通过，请刷新后再试！");
				}
			}

			if (nextNodeKey.equals(BasicGridAcceptancEnum.管理端工程线下验.getCode())) {
				dto.setWorkOrderId(basicGridAcceptanc.getWorkOrderId());
				dto.setWorkOrderPowerStationId(basicGridAcceptanc.getWorkOrderPowerStationId());
				dto.setPeasantHouseholdId(basicGridAcceptanc.getPeasantHouseholdId());
				acceptanceCheckItemMapper.insert(dto);
			}
            // 执行工作流
//        StandardDto standardDto = new StandardDto();
//        standardDto.setComment(dto.getComment());
//        standardDto.setResult(dto.getApprovalStatus());
//        standardDto.setTaskId(basicGridAcceptanc.getNextTaskId());
//        VariableDto variable = new VariableDto();
//        variable.setApprovalStatus(dto.getApprovalStatus());
//        variable.setComment(dto.getComment());
//        variable.setOperationTime(dto.getOperationTime());
//        variable.setOperator(dto.getOperator());
//        standardDto.setVariable(variable);
//        BasicGridAcceptance workBasicGridAcceptance = workflow.standard(basicGridAcceptanc, standardDto, userId);
            // 执行流程
            TaskResultDTO taskResultDTO = new TaskResultDTO();
            taskResultDTO.setComment(dto.getComment());
            taskResultDTO.setResult(dto.getApprovalStatus());
            taskResultDTO.setTaskId(basicGridAcceptanc.getNextTaskId());
            HashMap<String, Object> variableMap = new HashMap<>();
            variableMap.put("approvalStatus", dto.getApprovalStatus());
            variableMap.put("comment", dto.getComment());
            variableMap.put("operationTime", dto.getOperationTime());
            variableMap.put("operator", dto.getOperator());
            taskResultDTO.setVariable(variableMap);
            ProcessTaskDTO processTaskDTO = workFlowService.standard(basicGridAcceptanc, taskResultDTO, userId);

            if (basicGridAcceptanc.getNextNodeKey().equals(BasicGridAcceptancEnum.管理端工程线下验.getCode())) {
				// 线下验收
				LambdaUpdateWrapper<PeasantHousehold> up = new LambdaUpdateWrapper<>();
				up.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.线下验收.getCode());
				long idsk = basicGridAcceptanc.getPeasantHouseholdId();
				up.eq(PeasantHousehold::getSequenceNbr, idsk);
				peasantHouseholdMapper.update(null, up);
			}

			// 验收完成
			System.out.println("验收完成===============================" + basicGridAcceptanc.getNextTaskId());
			System.out.println(
					"验收完成888888===============================" + basicGridAcceptanc.getAcceptanceStatus());

			if ("10".equals(basicGridAcceptanc.getAcceptanceStatus())) {
				// 更新状态
				LambdaUpdateWrapper<PeasantHousehold> up = new LambdaUpdateWrapper<>();
				up.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.验收完成.getCode());
				long idsk = basicGridAcceptanc.getPeasantHouseholdId();
				up.eq(PeasantHousehold::getSequenceNbr, idsk);
				peasantHouseholdMapper.update(null, up);
				//生成新增投融资待办
				PeasantHousehold peasantHousehold = peasantHouseholdMapper.selectById(basicGridAcceptanc.getPeasantHouseholdId());
				RouthPathVO routhPathVO = new RouthPathVO();
				routhPathVO.setRouthPathId(String.valueOf(basicGridAcceptanc.getPeasantHouseholdId()));
				String routhPath = toDoTasksService.getRouthPath(TaskTypeStationEnum.投融资.getCode(), HygfRouthTypeEnum.HYGF_XZTSRZ.getCode(), routhPathVO);
				String wxRouthPath = toDoTasksService.getWxRouthPath(TaskTypeStationEnum.投融资.getCode(), HygfRouthTypeEnum.HYGF_XZTSRZ.getCode(), routhPathVO);
				ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.投融资.getCode(),  basicGridAcceptanc.getPeasantHouseholdId(),   peasantHousehold.getOwnersName()+"待新增推送融资",peasantHousehold.getRegionalCompaniesCode(),routhPath,wxRouthPath);
				String roleId = toDoTasksService.getRoleIdByName("户用光伏-投融");
				List<String> todoUserIds = toDoTasksService.getTodoUserIds(peasantHousehold.getRegionalCompaniesCode(), roleId);
				toDoTasksService.addToDoTasksByUserIds(todoUserIds,toDoTasks1);
			}

			basicGridAcceptanceMapper.updateById(basicGridAcceptanc);
			//更新待办
//			WorkflowResultDto workflowResultDto = workFlowService.buildWorkFlowInfo(CollectionUtil.newArrayList(processTaskDTO)).get(0);
//			workflowResultDto.setInstanceId(basicGridAcceptanc.getInstanceId());
//			commonService.updateTaskModelAndAddTask(basicGridAcceptanc,workflowResultDto,BusinessTypeEnum.HYGF_BWYS);
		} finally {
			redisLockUtil.releaseLock(lockName);
		}
	}

	// 工作流执行一步
	public void wofkflowExcute(String instanceId, String approvalStatus, String comment, String taskKey) {
		LambdaQueryWrapper<BasicGridAuditing> query = new LambdaQueryWrapper<>();
		query.eq(BasicGridAuditing::getInstanceId, instanceId);
		query.orderByDesc(BaseEntity::getSequenceNbr);
		query.last("limit 1");
		BasicGridAuditing basicGridAuditing = basicGridAuditingService.getBaseMapper().selectOne(query);

		if (!taskKey.contains(basicGridAuditing.getNextNodeKey())) {
			throw new BadRequest("无可执行任务");
		}
		// 组装信息
		TaskResultDTO task = new TaskResultDTO();

		task.setTaskId(basicGridAuditing.getNextTaskId());
		HashMap<String, Object> map = new HashMap<>();
		BasicGridAuditingDto basicGridAuditingDto = new BasicGridAuditingDto();
		task.setResultCode("approvalStatus");
		map.put("approvalStatus", approvalStatus);
		task.setComment(comment == null ? "" : comment);
		task.setVariable(map);
		// 执行流程
		ProcessTaskDTO processTaskDTO = workFlowService.complete(basicGridAuditing.getNextTaskId(), task);
		List<WorkflowResultDto> workflowResultDtos = workFlowService
				.buildWorkFlowInfo(CollectionUtil.newArrayList(processTaskDTO));
		WorkflowResultDto workflowResultDto = workflowResultDtos.get(0);
		BeanUtils.copyProperties(workflowResultDto, basicGridAuditingDto);
		basicGridAuditingDto.setPeasantHouseholdId(basicGridAuditing.getPeasantHouseholdId());
		basicGridAuditingDto.setPromoter(basicGridAuditing.getPromoter());
		basicGridAuditingDto.setStatus(approvalStatus);
		if (null == basicGridAuditingDto.getInstanceId()) {
			basicGridAuditingDto.setInstanceId(basicGridAuditing.getInstanceId());
		}
		basicGridAuditingService.createWithModel(basicGridAuditingDto);
		if(BusinessWorkflowKey.设计审核.getCode().equals(taskKey) || BusinessWorkflowKey.工程审核.getCode().equals(taskKey)){
			//完成设计
			ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.并网.getCode(),  HygfRouthTypeEnum.HYGF_BWSJSH.getBusiness());
			toDoTasksService.completeToDoTasks(toDoTasks1,"");
			//完成工程
			ToDoTasks toDoTasks2=  new ToDoTasks (TaskTypeStationEnum.并网.getCode(),  HygfRouthTypeEnum.HYGF_BWGCSH.getBusiness());
			toDoTasksService.completeToDoTasks(toDoTasks2,"");
		}
		RouthPathVO routhPathVO = new RouthPathVO();
		routhPathVO.setRouthPathId(String.valueOf(basicGridAuditing.getPeasantHouseholdId()));
		String routhPath = toDoTasksService.getRouthPath(TaskTypeStationEnum.并网.getCode(),workflowResultDto.getNextNodeKey(), routhPathVO);
		String wxRouthPath = toDoTasksService.getWxRouthPath(TaskTypeStationEnum.并网.getCode(),workflowResultDto.getNextNodeKey(), routhPathVO);
		if("Activity_0k4o46e".equals(workflowResultDto.getNextNodeKey())){
			//完成待办
			ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.并网.getCode(),  basicGridAuditing.getPeasantHouseholdId());
			toDoTasksService.completeToDoTasks(toDoTasks1,"");
			//此处产生两条待办 设计、工程
			PeasantHousehold peasantHousehold = peasantHouseholdMapper.selectById(basicGridAuditing.getPeasantHouseholdId());
			String taskName="您有一条并网的待办";
			String orgCode="";
			if(Objects.nonNull(peasantHousehold)){
				taskName= peasantHousehold.getOwnersName() ;
				orgCode=peasantHousehold.getRegionalCompaniesCode();
			}
			//设计
			ToDoTasks toDoTasks=  new ToDoTasks (TaskTypeStationEnum.并网.getCode(),  HygfRouthTypeEnum.HYGF_BWSJSH.getBusiness(), taskName+ "待设计审核",orgCode,routhPath,wxRouthPath);
			String roleId = toDoTasksService.getRoleIdByName("户用光伏-设计");
			List<String> todoUserIds = toDoTasksService.getTodoUserIds(orgCode, roleId);
			toDoTasksService.addToDoTasksByUserIds(todoUserIds,toDoTasks);

			//工程
			ToDoTasks toDoTasks2=  new ToDoTasks (TaskTypeStationEnum.并网.getCode(),  HygfRouthTypeEnum.HYGF_BWGCSH.getBusiness(), taskName+ "待工程审核",orgCode,routhPath,wxRouthPath);
			String roleId1 = toDoTasksService.getRoleIdByName("户用光伏-工程");
			List<String> todoUserIds1 = toDoTasksService.getTodoUserIds(orgCode, roleId1);
			toDoTasksService.addToDoTasksByUserIds(todoUserIds1,toDoTasks2);

		}else {
			//更新待办
			PeasantHousehold peasantHousehold = peasantHouseholdMapper.selectById(basicGridAuditing.getPeasantHouseholdId());
			String taskName="您有一条并网的待办";
			String orgCode="";
			if(Objects.nonNull(peasantHousehold)){
				taskName= peasantHousehold.getOwnersName() + "待" +workflowResultDto.getNextNodeName() ;
				orgCode=peasantHousehold.getRegionalCompaniesCode();
			}
			if("Activity_0r2x1es".equals(workflowResultDto.getNextNodeKey())){
				taskName= peasantHousehold.getOwnersName() + "待经销商管理员审核";
			}
			ToDoTasks toDoTasks=  new ToDoTasks (TaskTypeStationEnum.并网.getCode(),  basicGridAuditing.getPeasantHouseholdId(),   taskName,orgCode,routhPath,wxRouthPath);
			List<String> userIds = Arrays.asList(Optional.ofNullable(workflowResultDto.getNextExecuteUserIds()).orElse("").split(","));
			List<String> filterUsers = toDoTasksService.filterUsers(TaskTypeStationEnum.并网.getCode(), workflowResultDto.getNextNodeKey(),userIds, orgCode, peasantHousehold.getDeveloperCode());
			toDoTasksService.completeAndAddToDoTask(filterUsers,toDoTasks,"");
		}
	}

	public void completeAdminAudit(Map<String, String> kv) {
		String instanceId = kv.get("instanceId");
		String sequenceNbr = kv.get("sequenceNbr");
		String comment = kv.get("comment");
		String approvalStatus = kv.get("approvalStatus");

		BasicGridRecord basicGridRecord = basicGridRecordService.getBaseMapper().selectById(sequenceNbr);
		// 执行工作流
		this.wofkflowExcute(instanceId, approvalStatus, comment, BusinessWorkflowKey.经销商管理员审核.getCode());
		// 修改并网数据状态
		basicGridRecord.setGridStatus(
				approvalStatus.equals("0") ? GridStatusEnum.PQYYDSH.getCode() : GridStatusEnum.WTG.getCode());
		basicGridRecord.setBasicGridNode(approvalStatus.equals("0") ? "bw-area" : null);
		basicGridRecordService.updateById(basicGridRecord);
		// 增加操作日志
		ConstructionGirdRecords da = new ConstructionGirdRecords();
		da.setOperationTime(new Date());
		da.setOperationContent("并网管理-经销商管理员审核-" + (approvalStatus.equals("0") ? "通过" : "驳回"));
		da.setOperator(kv.get("operator"));
		da.setOperationResults(approvalStatus.equals("0") ? "通过" : "驳回");
		da.setGridId(basicGridRecord.getSequenceNbr());
		da.setWorkOrderPowerStationId(basicGridRecord.getWorkOrderPowerStationId());
		da.setPeasantHouseholdId(basicGridRecord.getPeasantHouseholdId());
		da.setNotes(kv.get("comment"));
		constructionGirdRecords.save(da);
	}

	public ResponseModel completeAudit(Map<String, String> kv) {
		String instanceId = kv.get("instanceId");
		String sequenceNbr = kv.get("sequenceNbr");
		String comment = kv.get("comment");
		String status = kv.get("status");
		String approvalStatus = kv.get("approvalStatus");

		BasicGridRecord basicGridRecord = basicGridRecordService.getBaseMapper().selectById(sequenceNbr);
		ConstructionGirdRecords da = new ConstructionGirdRecords();

		LambdaUpdateWrapper<BasicGridRecord> up = new LambdaUpdateWrapper<>();
		switch (status) {
		case "bw-area":
			up.set(BasicGridRecord::getPowerStationAreaStatus, approvalStatus.equals("0") ? "通过" : "驳回");
			if (approvalStatus.equals("0")) {
				up.set(BasicGridRecord::getBasicGridNode, "bw-design,bw-engineering");
				up.set(BasicGridRecord::getGridStatus, GridStatusEnum.ROLESDSH.getCode());
				int num = 0;
				// 如果历史有未完成的整改单则片区审核完成的时候改变主流程状态为整改单的状态
				LambdaQueryWrapper<HygfRectificationOrder> query = new LambdaQueryWrapper<>();
				query.eq(HygfRectificationOrder::getPeasantHouseholeId, basicGridRecord.getPeasantHouseholdId());
				query.in(HygfRectificationOrder::getRectificationStatus, Arrays.asList("待整改", "待审核"));
				query.in(HygfRectificationOrder::getRectificationSource, Arrays.asList("bw-design", "bw-engineering"));
				List<HygfRectificationOrder> hygfRectificationOrders = rectificationOrderService.getBaseMapper()
						.selectList(query);
				for (HygfRectificationOrder hygfRectificationOrder : hygfRectificationOrders) {
					if (hygfRectificationOrder.getRectificationStatus().equals("待审核")) {
						up.set(BasicGridRecord::getGridStatus, GridStatusEnum.ZGDSH.getCode());
						num = 1;
						break;
					}
				}
				if (CollUtil.isNotEmpty(hygfRectificationOrders) && num == 0) {
					up.set(BasicGridRecord::getGridStatus, GridStatusEnum.DZG.getCode());
				}

			}

			da.setOperationContent("并网验收-片区运营审核-" + (approvalStatus.equals("0") ? "通过" : "驳回"));

			this.wofkflowExcute(instanceId, approvalStatus, comment, BusinessWorkflowKey.片区运营审核.getCode());
			break;
		case "bw-design":
			up.set(BasicGridRecord::getPowerStationDesignStatus, approvalStatus.equals("0") ? "通过" : "驳回");
			da.setOperationContent("并网验收-设计审核-" + (approvalStatus.equals("0") ? "通过" : "驳回"));
			if (basicGridRecord.getPowerStationEngineeringStatus() != null
					&& basicGridRecord.getPowerStationEngineeringStatus().equals("通过") && approvalStatus.equals("0")) {
				up.set(BasicGridRecord::getGridStatus, GridStatusEnum.YWC.getCode());
				this.wofkflowExcute(instanceId, approvalStatus, comment, BusinessWorkflowKey.设计审核.getCode());
				up.set(BasicGridRecord::getBasicGridNode, "all");
				up.set(BasicGridRecord::getGridTime, new Date());
				LambdaUpdateWrapper<PeasantHousehold> wrapper = new LambdaUpdateWrapper<>();
				wrapper.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.并网完成.getCode());
				wrapper.eq(BaseEntity::getSequenceNbr, basicGridRecord.getPeasantHouseholdId());
				peasantHouseholdMapper.update(null, wrapper);
				AcceptanceCheck acceptanceCheck = new AcceptanceCheck();
				BeanUtils.copyProperties(basicGridRecord, acceptanceCheck);
				acceptanceCheck.setSequenceNbr(null);
				acceptanceCheck.setRectificationStatus(null);
				acceptanceCheck.setBasicGridNode(null);
				acceptanceCheck.setInstanceId(null);
				acceptanceCheck.setPowerStationAreaStatus(null);
				acceptanceCheck.setAcceptanceCheckStatus(GridStatusEnum.DTJYS.getCode());
				acceptanceCheckService.saveOrUpdate(acceptanceCheck);
				//生成验收待办
				PeasantHousehold peasantHousehold = peasantHouseholdMapper.selectById(basicGridRecord.getPeasantHouseholdId());
				RouthPathVO routhPathVO = new RouthPathVO();
				routhPathVO.setRouthPathId(String.valueOf(basicGridRecord.getPeasantHouseholdId()));
				String routhPath = toDoTasksService.getRouthPath(TaskTypeStationEnum.验收.getCode(), HygfRouthTypeEnum.HYGF_XZYSTJ.getCode(), routhPathVO);
				String wxRouthPath = toDoTasksService.getWxRouthPath(TaskTypeStationEnum.验收.getCode(), HygfRouthTypeEnum.HYGF_XZYSTJ.getCode(), routhPathVO);
				ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.验收.getCode(),  basicGridRecord.getPeasantHouseholdId(),   peasantHousehold.getOwnersName()+"待新增验收提交",peasantHousehold.getRegionalCompaniesCode(),routhPath,wxRouthPath);
				String roleId = toDoTasksService.getRoleIdByName("户用光伏-经销商-工程");
				List<String> todoUserIds = toDoTasksService.getTodoUserIds(peasantHousehold.getRegionalCompaniesCode(), roleId);
				List<String> filterUsers = toDoTasksService.filterUsers(TaskTypeStationEnum.验收.getCode(), HygfRouthTypeEnum.HYGF_XZYSTJ.getCode(), todoUserIds, peasantHousehold.getRegionalCompaniesCode(), peasantHousehold.getDeveloperCode());
				toDoTasksService.addToDoTasksByUserIds(filterUsers,toDoTasks1);

			} else if (null == basicGridRecord.getPowerStationEngineeringStatus() && approvalStatus.equals("0")
					&& (Objects.isNull(basicGridRecord.getRectificationStatus())
							|| (!basicGridRecord.getRectificationStatus().contains("bw-engineering")))) {
				up.set(BasicGridRecord::getBasicGridNode, "bw-engineering");
				up.set(BasicGridRecord::getGridStatus, GridStatusEnum.GCDSH.getCode());
				//完成设计
				ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.并网.getCode(),  HygfRouthTypeEnum.HYGF_BWSJSH.getBusiness());
				toDoTasksService.completeToDoTasks(toDoTasks1,"");
			} else if (null == basicGridRecord.getPowerStationEngineeringStatus() && approvalStatus.equals("0")
					&& basicGridRecord.getRectificationStatus().contains("bw-engineering")) {
				up.set(BasicGridRecord::getBasicGridNode, "bw-engineering");
				LambdaQueryWrapper<HygfRectificationOrder> query2 = new LambdaQueryWrapper<>();
				query2.eq(HygfRectificationOrder::getPeasantHouseholeId, basicGridRecord.getPeasantHouseholdId());
				query2.in(HygfRectificationOrder::getRectificationStatus, Arrays.asList("待整改", "待审核", "待提交"));
				query2.eq(HygfRectificationOrder::getRectificationSource, "bw-engineering");
				HygfRectificationOrder hygfRectificationOrder = rectificationOrderService.getBaseMapper()
						.selectOne(query2);
				if (hygfRectificationOrder.getRectificationStatus().equals("待提交")) {
					up.set(BasicGridRecord::getGridStatus, GridStatusEnum.SJDSH.getCode());
				} else if (hygfRectificationOrder.getRectificationStatus().equals("待整改")) {
					up.set(BasicGridRecord::getGridStatus, GridStatusEnum.DZG.getCode());
				} else {
					up.set(BasicGridRecord::getGridStatus, GridStatusEnum.ZGDSH.getCode());
				}
			} else if (null != basicGridRecord.getPowerStationEngineeringStatus()
					&& basicGridRecord.getPowerStationEngineeringStatus().equals("驳回")) {
				return CommonResponseNewUtil.failureMessage("该流程已被工程人员审核驳回，请刷新列表");
			} else {
				this.wofkflowExcute(instanceId, approvalStatus, comment, BusinessWorkflowKey.设计审核.getCode());
			}
			break;
		default:
			up.set(BasicGridRecord::getPowerStationEngineeringStatus, approvalStatus.equals("0") ? "通过" : "驳回");
			da.setOperationContent("并网验收-工程审核-" + (approvalStatus.equals("0") ? "通过" : "驳回"));
			if (basicGridRecord.getPowerStationDesignStatus() != null
					&& basicGridRecord.getPowerStationDesignStatus().equals("通过") && approvalStatus.equals("0")) {
				up.set(BasicGridRecord::getGridStatus, GridStatusEnum.YWC.getCode());
				this.wofkflowExcute(instanceId, approvalStatus, comment, BusinessWorkflowKey.工程审核.getCode());
				up.set(BasicGridRecord::getBasicGridNode, "all");
				up.set(BasicGridRecord::getGridTime, new Date());
				LambdaUpdateWrapper<PeasantHousehold> wrapper = new LambdaUpdateWrapper<>();
				wrapper.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.并网完成.getCode());
				wrapper.eq(BaseEntity::getSequenceNbr, basicGridRecord.getPeasantHouseholdId());
				peasantHouseholdMapper.update(null, wrapper);

				AcceptanceCheck acceptanceCheck = new AcceptanceCheck();
				BeanUtils.copyProperties(basicGridRecord, acceptanceCheck);
				acceptanceCheck.setSequenceNbr(null);
				acceptanceCheck.setRectificationStatus(null);
				acceptanceCheck.setBasicGridNode(null);
				acceptanceCheck.setPowerStationAreaStatus(null);
				acceptanceCheck.setInstanceId(null);
				acceptanceCheck.setAcceptanceCheckStatus(GridStatusEnum.DTJYS.getCode());
				acceptanceCheckService.saveOrUpdate(acceptanceCheck);
				//生成验收待办
				PeasantHousehold peasantHousehold = peasantHouseholdMapper.selectById(basicGridRecord.getPeasantHouseholdId());
				RouthPathVO routhPathVO = new RouthPathVO();
				routhPathVO.setRouthPathId(String.valueOf(basicGridRecord.getPeasantHouseholdId()));
				String routhPath = toDoTasksService.getRouthPath(TaskTypeStationEnum.验收.getCode(), HygfRouthTypeEnum.HYGF_XZYSTJ.getCode(), routhPathVO);
				String wxRouthPath = toDoTasksService.getWxRouthPath(TaskTypeStationEnum.验收.getCode(), HygfRouthTypeEnum.HYGF_XZYSTJ.getCode(), routhPathVO);
				ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.验收.getCode(),  basicGridRecord.getPeasantHouseholdId(),   peasantHousehold.getOwnersName()+"待新增验收提交",peasantHousehold.getRegionalCompaniesCode(),routhPath,wxRouthPath);
				String roleId = toDoTasksService.getRoleIdByName("户用光伏-经销商-工程");
				List<String> todoUserIds = toDoTasksService.getTodoUserIds(peasantHousehold.getRegionalCompaniesCode(), roleId);
				List<String> filterUsers = toDoTasksService.filterUsers(TaskTypeStationEnum.验收.getCode(), HygfRouthTypeEnum.HYGF_XZYSTJ.getCode(), todoUserIds, peasantHousehold.getRegionalCompaniesCode(), peasantHousehold.getDeveloperCode());
				toDoTasksService.addToDoTasksByUserIds(filterUsers,toDoTasks1);

			} else if (null == basicGridRecord.getPowerStationDesignStatus() && approvalStatus.equals("0")
					&& (Objects.isNull(basicGridRecord.getRectificationStatus())
							|| (!basicGridRecord.getRectificationStatus().contains("bw-design")))) {
				up.set(BasicGridRecord::getBasicGridNode, "bw-design");
				up.set(BasicGridRecord::getGridStatus, GridStatusEnum.SJDSH.getCode());
				//完成工程
				ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.并网.getCode(),  HygfRouthTypeEnum.HYGF_BWGCSH.getBusiness());
				toDoTasksService.completeToDoTasks(toDoTasks1,"");
			} else if (null == basicGridRecord.getPowerStationDesignStatus() && approvalStatus.equals("0")
					&& !Objects.isNull(basicGridRecord.getRectificationStatus())
					&& basicGridRecord.getRectificationStatus().contains("bw-design")) {
				up.set(BasicGridRecord::getBasicGridNode, "bw-design");
				LambdaQueryWrapper<HygfRectificationOrder> query1 = new LambdaQueryWrapper<>();
				query1.eq(HygfRectificationOrder::getPeasantHouseholeId, basicGridRecord.getPeasantHouseholdId());
				query1.in(HygfRectificationOrder::getRectificationStatus, Arrays.asList("待整改", "待审核", "待提交"));
				query1.eq(HygfRectificationOrder::getRectificationSource, "bw-design");
				HygfRectificationOrder hygfRectificationOrder = rectificationOrderService.getBaseMapper()
						.selectOne(query1);
				if (hygfRectificationOrder.getRectificationStatus().equals("待提交")) {
					up.set(BasicGridRecord::getGridStatus, GridStatusEnum.SJDSH.getCode());
				} else if (hygfRectificationOrder.getRectificationStatus().equals("待整改")) {
					up.set(BasicGridRecord::getGridStatus, GridStatusEnum.DZG.getCode());
				} else {
					up.set(BasicGridRecord::getGridStatus, GridStatusEnum.ZGDSH.getCode());
				}
			} else if (null != basicGridRecord.getPowerStationDesignStatus()
					&& basicGridRecord.getPowerStationDesignStatus().equals("驳回")) {
				return CommonResponseNewUtil.failureMessage("该流程已被设计人员审核驳回，请刷新列表");
			} else {
				this.wofkflowExcute(instanceId, approvalStatus, comment, BusinessWorkflowKey.工程审核.getCode());
			}
			break;
		}
		if (approvalStatus.equals("1")) {
			up.eq(BaseEntity::getSequenceNbr, sequenceNbr);
			up.set(BasicGridRecord::getBasicGridNode, null);
			up.set(BasicGridRecord::getGridStatus, GridStatusEnum.WTG.getCode());
		}
		// 修改并网数据状态
		if (StringUtils.isNotEmpty(sequenceNbr)) {
			up.eq(BaseEntity::getSequenceNbr, sequenceNbr);
			basicGridRecordService.getBaseMapper().update(null, up);
		}
		Date date = new Date();
		da.setOperationTime(date);
		da.setOperator(kv.get("operator"));
		da.setOperationResults(approvalStatus.equals("0") ? "通过" : "驳回");
		da.setGridId(basicGridRecord.getSequenceNbr());
		da.setWorkOrderPowerStationId(basicGridRecord.getWorkOrderPowerStationId());
		da.setPeasantHouseholdId(basicGridRecord.getPeasantHouseholdId());
		da.setNotes(kv.get("comment"));
		constructionGirdRecords.save(da);
		//更新并网结束时间
		if (StringUtils.isNotEmpty(sequenceNbr)) {
			BasicGridRecord gridRecord = basicGridRecordService.getBaseMapper().selectById(sequenceNbr);
			if(Objects.nonNull(gridRecord) && GridStatusEnum.YWC.getCode().equals(gridRecord.getGridStatus())){
				LambdaUpdateWrapper<BasicGridRecord> wrapper = new LambdaUpdateWrapper<>();
				wrapper.set(BasicGridRecord::getBwEndTime, date);
				wrapper.eq(BasicGridRecord::getSequenceNbr, sequenceNbr);
				basicGridRecordService.getBaseMapper().update(null, wrapper);
			}
		}
		return CommonResponseNewUtil.success();
	}

	public ResponseModel addRectification(HygfRectificationOrder hygfRectificationOrder) {
		if (Objects.isNull(hygfRectificationOrder.getRectificationSource())) {
			return CommonResponseNewUtil.failureMessage("多角色用户发起整改单，发起人角色不可为空");
		}
		if (hygfRectificationOrder.getAddorSubmit().equals("0")
				&& Objects.isNull(hygfRectificationOrder.getRectificationIdea())) {
			return CommonResponseNewUtil.failureMessage("整改类型及整改项不可为空");
		}
		if (hygfRectificationOrder.getAddorSubmit().equals("0")
				&& !Objects.isNull(hygfRectificationOrder.getRectificationIdea())) {
			List<Object> rectificationIdea = hygfRectificationOrder.getRectificationIdea();
			for (Object item : rectificationIdea) {
				JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(item));
				Collection<Object> values = jsonObject.values();
				if (values.size() < 2) {
					return CommonResponseNewUtil.failureMessage("整改类型及整改项不可为空");
				}
				if (jsonObject.containsKey("type")) {
					if (null == jsonObject.get("type")) {
						return CommonResponseNewUtil.failureMessage("整改类型及整改项不可为空");
					}
				}
				if (jsonObject.containsKey("items")) {
					JSONArray item1 = jsonObject.getJSONArray("items");
					for (Object o : item1) {
						if (!JSON.parseObject(JSON.toJSONString(o)).containsKey("value")) {
							return CommonResponseNewUtil.failureMessage("整改类型及整改项不可为空");
						}
					}
				}
			}
		}

		if (hygfRectificationOrder.getSequenceNbr() != null) {
			LambdaQueryWrapper<HygfRectificationOrder> wr = new LambdaQueryWrapper<>();
			wr.eq(HygfRectificationOrder::getPeasantHouseholeId, hygfRectificationOrder.getPeasantHouseholeId());
			wr.notIn(HygfRectificationOrder::getRectificationStatus, Arrays.asList("已作废", "已完成"));
			wr.eq(HygfRectificationOrder::getRectificationSource, hygfRectificationOrder.getRectificationSource());
			wr.ne(BaseEntity::getSequenceNbr, hygfRectificationOrder.getSequenceNbr());
			List<HygfRectificationOrder> list = rectificationOrderService.getBaseMapper().selectList(wr);
			if (CollectionUtil.isNotEmpty(list)) {
				return CommonResponseNewUtil.failureMessage("当前农户存在其他进行中的整改单,不可重新发起");
			}
		}

		// 查询当前并网数据
		LambdaQueryWrapper<BasicGridRecord> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(BasicGridRecord::getPeasantHouseholdId, hygfRectificationOrder.getPeasantHouseholeId());
		BasicGridRecord basicGridRecord = basicGridRecordService.getBaseMapper().selectOne(wrapper);
		if (!Objects.isNull(basicGridRecord)
				&& !basicGridRecord.getBasicGridNode().contains(hygfRectificationOrder.getRectificationSource())) {
			return CommonResponseNewUtil.failureMessage("当前流程发生变化，暂时无法操作，请刷新再试");
		}

		String addorSubmit = hygfRectificationOrder.getAddorSubmit();
		LambdaUpdateWrapper<BasicGridRecord> qu = new LambdaUpdateWrapper();
		qu.eq(BasicGridRecord::getPeasantHouseholdId, hygfRectificationOrder.getPeasantHouseholeId());
		if (!Objects.isNull(basicGridRecord) && null != basicGridRecord.getRectificationStatus() && !basicGridRecord
				.getRectificationStatus().contains(hygfRectificationOrder.getRectificationSource())) {
			qu.set(BasicGridRecord::getRectificationStatus,
					basicGridRecord.getRectificationStatus() + "," + hygfRectificationOrder.getRectificationSource());
			basicGridRecordService.update(null, qu);
		} else if (!Objects.isNull(basicGridRecord) && null == basicGridRecord.getRectificationStatus()) {
			qu.set(BasicGridRecord::getRectificationStatus, hygfRectificationOrder.getRectificationSource());
			basicGridRecordService.update(null, qu);
		}
		// 修改状态
		if (addorSubmit.equals("0")) {
			// 如果历史有未完成的整改单则片区审核完成的时候改变主流程状态为整改单的状态
			int num = 0;
			LambdaQueryWrapper<HygfRectificationOrder> query = new LambdaQueryWrapper<>();
			query.eq(HygfRectificationOrder::getPeasantHouseholeId, basicGridRecord.getPeasantHouseholdId());
			query.in(HygfRectificationOrder::getRectificationStatus, Arrays.asList("待整改", "待提交", "待审核"));
			query.in(HygfRectificationOrder::getRectificationSource, Arrays.asList("bw-design", "bw-engineering"));
			List<HygfRectificationOrder> hygfRectificationOrders = rectificationOrderService.getBaseMapper()
					.selectList(query);
			for (HygfRectificationOrder hygfRectificationOrderO : hygfRectificationOrders) {
				if (hygfRectificationOrderO.getRectificationStatus().equals("待审核")) {
					qu.set(BasicGridRecord::getGridStatus, GridStatusEnum.ZGDSH.getCode());
					num = 1;
					break;
				}
			}
			if (num == 0) {
				qu.set(BasicGridRecord::getGridStatus, GridStatusEnum.DZG.getCode());
			}
			basicGridRecordService.update(null, qu);
		}
		rectificationOrderAuditingService.addRectification(hygfRectificationOrder);

		return CommonResponseNewUtil.success();
	}

	public ResponseModel nextTaskExcute(HygfRectificationOrder hygfRectificationOrder) {
		// 查询当前并网数据
		LambdaQueryWrapper<BasicGridRecord> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(BasicGridRecord::getPeasantHouseholdId, hygfRectificationOrder.getPeasantHouseholeId());
		BasicGridRecord basicGridRecord = basicGridRecordService.getBaseMapper().selectOne(wrapper);
		if (!basicGridRecord.getBasicGridNode().contains(hygfRectificationOrder.getRectificationSource())) {
			hygfRectificationOrder.setRectificationStatus(WorkOrderEnum.整改中.getCode());
			rectificationOrderAuditingService.addRectification(hygfRectificationOrder);
			return CommonResponseNewUtil.failureMessage("当前流程发生变化，暂时无法操作，请刷新再试");
		}

		if (hygfRectificationOrder.getAddorSubmit().equals("0")) {

			LambdaUpdateWrapper<BasicGridRecord> up = new LambdaUpdateWrapper<>();
			up.set(BasicGridRecord::getGridStatus, GridStatusEnum.ZGDSH.getCode());
			up.eq(BasicGridRecord::getPeasantHouseholdId, hygfRectificationOrder.getPeasantHouseholeId());
			basicGridRecordService.update(null, up);
			hygfRectificationOrder.setRectificationStatus(WorkOrderEnum.待审核.getCode());
		} else {
			hygfRectificationOrder.setRectificationStatus(WorkOrderEnum.整改中.getCode());
		}
		rectificationOrderAuditingService.nextTaskExcute(hygfRectificationOrder);
		return CommonResponseNewUtil.success();
	}

	public ResponseModel nextTaskAduit(HygfRectificationOrder hygfRectificationOrder) {
		String auditResult = hygfRectificationOrder.getAuditResult();

		// 查询当前并网数据
		LambdaQueryWrapper<BasicGridRecord> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(BasicGridRecord::getPeasantHouseholdId, hygfRectificationOrder.getPeasantHouseholeId());
		BasicGridRecord basicGridRecord = basicGridRecordService.getBaseMapper().selectOne(wrapper);

		if (!basicGridRecord.getBasicGridNode().contains(hygfRectificationOrder.getRectificationSource())) {
			return CommonResponseNewUtil.failureMessage("当前流程发生变化，暂时无法操作，请刷新再试");
		}

		// 修改整改单状态
		hygfRectificationOrder.setRectificationStatus(
				auditResult.equals("通过") ? WorkOrderEnum.已完成.getCode() : WorkOrderEnum.待整改.getCode());
		rectificationOrderAuditingService.nextTaskAduit(hygfRectificationOrder);
		// 查询是否还有其它类型待整改的整改单存在 若存在后置节点为当前并网状态
		LambdaQueryWrapper<HygfRectificationOrder> wr = new LambdaQueryWrapper<>();
		wr.eq(HygfRectificationOrder::getPeasantHouseholeId, hygfRectificationOrder.getPeasantHouseholeId());
		wr.notIn(HygfRectificationOrder::getRectificationStatus, Arrays.asList("待提交", "已作废", "已完成"));
		wr.ne(BaseEntity::getSequenceNbr, hygfRectificationOrder.getSequenceNbr());
		List<HygfRectificationOrder> list = rectificationOrderService.getBaseMapper().selectList(wr);

		// 修改并网状态
		// 片区不存在并行 无需复杂判断 工程与设计并行 需要做额外逻辑判断
		if (auditResult.equals("通过")) {
			if (hygfRectificationOrder.getRectificationSource().equals("bw-area")) {
				LambdaUpdateWrapper<BasicGridRecord> qu = new LambdaUpdateWrapper();
				qu.eq(BasicGridRecord::getPeasantHouseholdId, hygfRectificationOrder.getPeasantHouseholeId());
				qu.set(BasicGridRecord::getGridStatus, GridStatusEnum.PQYYDSH.getCode());
				qu.set(BasicGridRecord::getRectificationStatus, null);
				basicGridRecordService.update(null, qu);
			} else {
				LambdaUpdateWrapper<BasicGridRecord> qu = new LambdaUpdateWrapper();
				qu.eq(BasicGridRecord::getPeasantHouseholdId, hygfRectificationOrder.getPeasantHouseholeId());
				List<String> status = new ArrayList<>(
						Arrays.asList(basicGridRecord.getRectificationStatus().split(",")));
				status.remove(hygfRectificationOrder.getRectificationSource());
				if (status.size() < 1) {
					qu.set(BasicGridRecord::getRectificationStatus, null);
				} else {
					qu.set(BasicGridRecord::getRectificationStatus, String.join(",", status));
				}
				if (CollectionUtil.isEmpty(list)) {
					// 若两者状态都为空 说明均为审核 若某一审核状态为空 则审核状态修改为为空审核节点
					if (Objects.isNull(basicGridRecord.getPowerStationDesignStatus())
							&& Objects.isNull(basicGridRecord.getPowerStationEngineeringStatus())) {
						qu.set(BasicGridRecord::getGridStatus, GridStatusEnum.ROLESDSH.getCode());

					} else if (Objects.isNull(basicGridRecord.getPowerStationDesignStatus())) {
						qu.set(BasicGridRecord::getGridStatus, GridStatusEnum.SJDSH.getCode());
					} else {
						qu.set(BasicGridRecord::getGridStatus, GridStatusEnum.GCDSH.getCode());
					}
				} else {
					List<String> collect = list.stream().map(HygfRectificationOrder::getRectificationStatus)
							.collect(Collectors.toList());
					qu.set(BasicGridRecord::getGridStatus,
							collect.contains(WorkOrderEnum.待审核.getCode()) ? GridStatusEnum.ZGDSH.getCode()
									: GridStatusEnum.DZG.getCode());
				}
				basicGridRecordService.update(null, qu);
			}
		} else {
			// 驳回的时候 也需根据 工程或者设计 整改单状态修改并网状态
			LambdaUpdateWrapper<BasicGridRecord> qu = new LambdaUpdateWrapper();
			qu.eq(BasicGridRecord::getPeasantHouseholdId, hygfRectificationOrder.getPeasantHouseholeId());
			if (!CollectionUtil.isEmpty(list)) {
				List<String> collect = list.stream().map(HygfRectificationOrder::getRectificationStatus)
						.collect(Collectors.toList());
				qu.set(BasicGridRecord::getGridStatus,
						collect.contains(WorkOrderEnum.待审核.getCode()) ? GridStatusEnum.ZGDSH.getCode()
								: GridStatusEnum.DZG.getCode());
			} else {
				qu.set(BasicGridRecord::getGridStatus, GridStatusEnum.DZG.getCode());
			}
			basicGridRecordService.update(null, qu);
		}
		return CommonResponseNewUtil.success();
	}

	public ResponseModel rollback(Long sequenceNbr) {
		HygfRectificationOrder hygfRectificationOrder = rectificationOrderService.getBaseMapper()
				.selectById(sequenceNbr);
		// 查询当前并网数据
		LambdaQueryWrapper<BasicGridRecord> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(BasicGridRecord::getPeasantHouseholdId, hygfRectificationOrder.getPeasantHouseholeId());
		BasicGridRecord basicGridRecord = basicGridRecordService.getBaseMapper().selectOne(wrapper);
		if (!basicGridRecord.getBasicGridNode().contains(hygfRectificationOrder.getRectificationSource())) {
			return CommonResponseNewUtil.failureMessage("当前流程发生变化，暂时无法操作，请刷新再试");
		}
		LambdaUpdateWrapper<BasicGridRecord> qu = new LambdaUpdateWrapper();
		qu.eq(BasicGridRecord::getPeasantHouseholdId, hygfRectificationOrder.getPeasantHouseholeId());
		if (hygfRectificationOrder.getRectificationStatus().equals(WorkOrderEnum.待提交.getCode())
				|| hygfRectificationOrder.getRectificationStatus().equals(WorkOrderEnum.待整改.getCode())) {
			rectificationOrderAuditingService.rollback(sequenceNbr);
			List<String> status = new ArrayList<>(Arrays.asList(basicGridRecord.getRectificationStatus().split(",")));
			status.remove(hygfRectificationOrder.getRectificationSource());
			if (status.size() < 1) {
				qu.set(BasicGridRecord::getRectificationStatus, null);
			} else {
				qu.set(BasicGridRecord::getRectificationStatus, String.join(",", status));
				basicGridRecordService.getBaseMapper().update(null, qu);
			}
		} else {
			return CommonResponseNewUtil.failureMessage("仅单据状态为待提交或待整改时方可作废");
		}

		if (hygfRectificationOrder.getRectificationSource().equals("bw-area")) {
			qu.set(BasicGridRecord::getGridStatus, GridStatusEnum.PQYYDSH.getCode());
		} else {

			// 查询是否还有其它类型待整改的整改单存在 若存在后置节点为当前并网状态
			LambdaQueryWrapper<HygfRectificationOrder> wr = new LambdaQueryWrapper<>();
			wr.eq(HygfRectificationOrder::getPeasantHouseholeId, hygfRectificationOrder.getPeasantHouseholeId());
			wr.notIn(HygfRectificationOrder::getRectificationStatus, Arrays.asList("待提交", "已作废", "已完成"));
			wr.ne(BaseEntity::getSequenceNbr, hygfRectificationOrder.getSequenceNbr());
			List<HygfRectificationOrder> list = rectificationOrderService.getBaseMapper().selectList(wr);

			if (CollectionUtil.isEmpty(list)) {
				// 若两者状态都为空 说明均为审核 若某一审核状态为空 则审核状态修改为为空审核节点
				if (Objects.isNull(basicGridRecord.getPowerStationDesignStatus())
						&& Objects.isNull(basicGridRecord.getPowerStationEngineeringStatus())) {
					qu.set(BasicGridRecord::getGridStatus, GridStatusEnum.ROLESDSH.getCode());
				} else if (Objects.isNull(basicGridRecord.getPowerStationDesignStatus())) {
					qu.set(BasicGridRecord::getGridStatus, GridStatusEnum.SJDSH.getCode());
				} else {
					qu.set(BasicGridRecord::getGridStatus, GridStatusEnum.GCDSH.getCode());
				}
			} else {
				List<String> collect = list.stream().map(HygfRectificationOrder::getRectificationStatus)
						.collect(Collectors.toList());
				qu.set(BasicGridRecord::getGridStatus,
						collect.contains(WorkOrderEnum.待审核.getCode()) ? GridStatusEnum.ZGDSH.getCode()
								: GridStatusEnum.DZG.getCode());

			}
		}
		basicGridRecordService.update(null, qu);
		return CommonResponseNewUtil.success();
	}

}
