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.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.IWorkOrderService;
import com.yeejoin.amos.boot.module.hygf.api.util.BeanDtoUtils;
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.feign.WorkflowFeignClient;
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 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.Isolation;
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.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

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

/**
 * 施工派工工单服务实现类
 *
 * @author system_generator
 * @date 2024-01-02
 */
@Service
public class WorkOrderServiceImpl extends BaseService<WorkOrderDto, WorkOrder, WorkOrderMapper>
		implements IWorkOrderService {

	@Autowired
	RegionalCompaniesMapper regionalCompaniesMapper;

	@Autowired
	WorkOrderMapper workOrderMapper;
	@Autowired
	WorkOrderPowerStationServiceImpl workOrderPowerStationServiceImpl;
	@Autowired
	private WorkFlowService workFlowService;
	@Autowired
	WorkOrderPowerStationMapper workOrderPowerStationMapper;
	@Autowired
	HygfWorkOrderStationAuditingServiceImpl hygfWorkOrderStationAuditingService;
	@Autowired
	RectificationOrderAuditingServiceImpl rectificationOrderAuditingService;
	@Autowired
	DesignInformationMapper designInformationMapper;
	@Autowired
	PowerStationConstructionDataServiceImpl powerStationConstructionDataService;

	@Autowired
	SurveyDetailsServiceImpl surveyDetailsService;

	@Autowired
	HygfRectificationOrderServiceImpl rectificationOrderService;

	@Autowired
	InformationServiceImpl informationService;

	@Autowired
	ExtendedInformationServiceImpl extendedInformationService;

	@Autowired
	CommercialServiceImpl commercialService;

	@Autowired
	PeasantHouseholdServiceImpl peasantHouseholdServiceImpl;

	@Autowired
	DesignInformationServiceImpl designInformationService;

	@Autowired
	PersonnelBusinessMapper personnelBusinessMapper;
	@Autowired
	SurveyInformationMapper surveyInformationMapper;
	@Autowired
	PowerStationConstructionDataMapper powerStationConstructionDataMapper;
	@Autowired
	PowerStationEngineeringInfoMapper powerStationEngineeringInfoMapper;
	@Autowired
	PowerStationEngineeringInfoServiceImpl powerStationEngineeringInfoService;
	@Autowired
	HouseholdContractMapper householdContractMapper;
	@Autowired
	HygfOnGridMapper hygfOnGridMapper;
	@Autowired
	ConstructionRecordsServiceImpl constructionRecordsServiceImpl;
	@Autowired
	ConstructionRecordsMapper constructionRecordsMapper;
	@Autowired
	ConstructionGirdRecordsMapper constructionGirdRecordsMapper;
	@Autowired
	ConstructionAcceptanceRecordsMapper constructionAcceptanceRecordsMapper;
	@Autowired
	BasicGridRecordMapper basicGridRecordMapper;
	@Autowired
	AcceptanceCheckMapper acceptanceCheckMapper;
    @Autowired
	BasicGridRecordServiceImpl basicGridRecordService;
	@Autowired
	WorkflowFeignClient workflowFeignClient;
	@Autowired
	UnitInfoServiceImpl unitInfoService;
	@Autowired
	PeasantHouseholdMapper peasantHouseholdMapper;
	@Autowired
	BasicGridAcceptanceServiceImpl basicGridAcceptanceService;
	@Autowired
	AcceptanceCheckServiceImpl acceptanceCheckService;
	@Autowired
	ToDoTasksServiceImpl toDoTasksService;
	private static final String PROCESSKEY = "ProcessEngineering";

	/**
	 * 分页查询
	 */
	public Page<WorkOrderDto> queryForWorkOrderPage(Page<WorkOrderDto> page) {
		return this.queryForPage(page, null, false);
	}

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

	@Transactional
	public WorkOrder saveWorkOrder(WorkOrder model, UserUnitInformationDto userUnitInformationDto) throws Exception {

		// 校验电站已被选
		List<PeasantHousehold> peasantHouseholdId = model.getPeasantHouseholdId();
		List<PeasantHousehold> workorderPeasant = new ArrayList<>();
		for (PeasantHousehold peasantHouse : peasantHouseholdId) {
			int count = workOrderPowerStationServiceImpl.count(new LambdaQueryWrapper<WorkOrderPowerStation>()
					.eq(WorkOrderPowerStation::getPeasantHouseholdId, peasantHouse.getSequenceNbr()));
			if (count > 0) {
				PeasantHousehold peasantHouseOne = peasantHouseholdMapper.selectById(peasantHouse.getSequenceNbr());
				workorderPeasant.add(peasantHouseOne);
			}
		}
		if (!workorderPeasant.isEmpty()) {
			String names = workorderPeasant.stream().map(i -> i.getOwnersName()).collect(Collectors.joining(","));
			throw new Exception("电站" + names + ",已被工单关联,请重新选择电站");
		}


		// 保存派工单
		RegionalCompanies regionalCompanies = regionalCompaniesMapper.selectRegionName(model.getRegionCompanyId());
		String code = NumberUtil.getCode(CodeEnum.派工单.getCode(), regionalCompanies.getCompanyCode(),
				regionalCompanies.getRegionalAddress());
		model.setWorkOrderNum(code);
		model.setRegionCompanyName(regionalCompanies.getRegionalCompaniesName());
		model.setRegionCode(regionalCompanies.getRegionalCompaniesCode());
		model.setWorkOrderStatus(WorkOrderEnum.待施工.getCode());
		model.setRegionAddress(regionalCompanies.getRegionalAddress());
		// 获取经销商单位信息
		model.setAmosDealerId(userUnitInformationDto.getAmosDealerId());
		model.setAmosDealerName(userUnitInformationDto.getAmosDealerName());
		model.setAmosDealerOrgCode(userUnitInformationDto.getAmosDealerOrgCode());

		//        根据工程用户id, 查询用户姓名
		String projectRegionManager = workOrderMapper.getRealNameByUserId(model.getProjectRegionManagerUserId());
		String constructionRegionManager = workOrderMapper.getRealNameByUserId(model.getConstructionRegionManagerUserId());

		model.setProjectRegionManager(projectRegionManager);
		model.setConstructionRegionManager(constructionRegionManager);



		workOrderMapper.insert(model);

		// 保存派工单 电站信息
		List<ConstructionRecords> constructionRecordlist = new ArrayList<>();
		List<WorkOrderPowerStation> li = new ArrayList<>();
		for (PeasantHousehold peasantHousehold : peasantHouseholdId) {
			WorkOrderPowerStation workOrderPowerStation = new WorkOrderPowerStation();
			workOrderPowerStation.setPeasantHouseholdId(peasantHousehold.getSequenceNbr());
			workOrderPowerStation.setWorkOrderId(model.getSequenceNbr());
			workOrderPowerStation.setPowerStationConstructionStatus(WorkOrderEnum.待施工.getCode());
			li.add(workOrderPowerStation);

		}
		workOrderPowerStationServiceImpl.saveBatch(li);

		for (WorkOrderPowerStation workOrderPowerStation : li) {
			// 增加操作日志
			ConstructionRecords da = new ConstructionRecords(workOrderPowerStation.getRecUserName(), "新建派工单",
					new Date(), "", workOrderPowerStation.getWorkOrderId(), workOrderPowerStation.getSequenceNbr(),
					workOrderPowerStation.getPeasantHouseholdId(), "");
			constructionRecordlist.add(da);

		}
		constructionRecordsServiceImpl.saveBatch(constructionRecordlist);

		//完成新增派工单待办
		ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.施工.getCode(), HygfRouthTypeEnum.HYGF_XZPGD.getBusiness());
		toDoTasksService.completeToDoTasks(toDoTasks1,"");
		//新增待办此处是多个施工单
		LambdaQueryWrapper<WorkOrderPowerStation> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(WorkOrderPowerStation::getWorkOrderId,model.getSequenceNbr());
		List<WorkOrderPowerStation> workOrderPowerStations = workOrderPowerStationServiceImpl.list(wrapper);
		if (CollectionUtil.isNotEmpty(workOrderPowerStations)){
			for (WorkOrderPowerStation workOrderPowerStation : workOrderPowerStations) {
				PeasantHousehold peasantHousehold = peasantHouseholdMapper.selectById(workOrderPowerStation.getPeasantHouseholdId());
				RouthPathVO routhPathVO = new RouthPathVO();
				routhPathVO.setRouthPathId(String.valueOf(workOrderPowerStation.getSequenceNbr()));
				String routhPath = toDoTasksService.getRouthPath(TaskTypeStationEnum.施工.getCode(), HygfRouthTypeEnum.HYGF_DSG.getCode(), routhPathVO);
				String wxRouthPath = toDoTasksService.getWxRouthPath(TaskTypeStationEnum.施工.getCode(), HygfRouthTypeEnum.HYGF_DSG.getCode(), routhPathVO);
				ToDoTasks toDoTasks=  new ToDoTasks (TaskTypeStationEnum.施工.getCode(),  workOrderPowerStation.getSequenceNbr(),   peasantHousehold.getOwnersName() +"待施工",model.getRegionCode(),routhPath,wxRouthPath);
				String roleId = toDoTasksService.getRoleIdByName("户用光伏-经销商-施工");
				List<String> todoUserIds = toDoTasksService.getTodoUserIds(model.getRegionCode(), roleId, String.valueOf(model.getAmosDealerOrgCode()));
				toDoTasksService.addToDoTasksByUserIds(todoUserIds,toDoTasks);
			}
		}
		return model;
	}

	@Transactional
	public WorkOrder updateWorkOrder(WorkOrder model, UserUnitInformationDto userUnitInformationDto) {
		// 保存派工单
		RegionalCompanies regionalCompanies = regionalCompaniesMapper.selectRegionName(model.getRegionCompanyId());
		model.setRegionCompanyName(regionalCompanies.getRegionalCompaniesName());
		model.setRegionCode(regionalCompanies.getRegionalCompaniesCode());
		model.setWorkOrderStatus(WorkOrderEnum.待施工.getCode());
		model.setRegionAddress(regionalCompanies.getRegionalAddress());
		// 根据工程用户id, 查询用户姓名
		String projectRegionManager = workOrderMapper.getRealNameByUserId(model.getProjectRegionManagerUserId());
		String constructionRegionManager = workOrderMapper.getRealNameByUserId(model.getConstructionRegionManagerUserId());

		model.setProjectRegionManager(projectRegionManager);
		model.setConstructionRegionManager(constructionRegionManager);

		// 获取经销商单位信息
		model.setAmosDealerId(userUnitInformationDto.getAmosDealerId());
		model.setAmosDealerName(userUnitInformationDto.getAmosDealerName());
		model.setAmosDealerOrgCode(userUnitInformationDto.getAmosDealerOrgCode());
		workOrderMapper.updateById(model);
		LambdaQueryWrapper<WorkOrderPowerStation> up = new LambdaQueryWrapper();
		up.eq(WorkOrderPowerStation::getWorkOrderId, model.getSequenceNbr());
		workOrderPowerStationMapper.delete(up);
		// 保存派工单 电站信息
		List<PeasantHousehold> peasantHouseholdId = model.getPeasantHouseholdId();
		List<WorkOrderPowerStation> li = new ArrayList<>();
		for (PeasantHousehold peasantHousehold : peasantHouseholdId) {
			WorkOrderPowerStation workOrderPowerStation = new WorkOrderPowerStation();
			workOrderPowerStation.setPeasantHouseholdId(peasantHousehold.getSequenceNbr());
			workOrderPowerStation.setWorkOrderId(model.getSequenceNbr());
			workOrderPowerStation.setPowerStationConstructionStatus(WorkOrderEnum.待施工.getCode());
			li.add(workOrderPowerStation);
		}
		workOrderPowerStationServiceImpl.saveBatch(li);

		List<ConstructionRecords> constructionRecordlist = new ArrayList<>();
		for (WorkOrderPowerStation workOrderPowerStation : li) {
			// 增加操作日志
			ConstructionRecords da = new ConstructionRecords(workOrderPowerStation.getRecUserName(), "编辑派工单",
					new Date(), "", workOrderPowerStation.getWorkOrderId(), workOrderPowerStation.getSequenceNbr(),
					workOrderPowerStation.getPeasantHouseholdId(), "");
			constructionRecordlist.add(da);

		}
		constructionRecordsServiceImpl.saveBatch(constructionRecordlist);

		return model;
	}

	public WorkOrder selectOne(Long sequenceNbr) {
		WorkOrder model = workOrderMapper.selectById(sequenceNbr);
		List<PeasantHousehold> li = workOrderPowerStationMapper.selectPeasantHousehold(sequenceNbr, null);
		model.setPeasantHouseholdId(li);
		return model;
	}

	public Map<String, Object> selectOneall(Long sequenceNbr) {
		WorkOrder model = workOrderMapper.selectById(sequenceNbr);
		List<PeasantHousehold> lih = workOrderPowerStationMapper.selectPeasantHousehold(sequenceNbr, null);

		// 获取所有电站Bom，分组合并，暂时不相加
		List<Long> ids = new ArrayList<>();
		for (PeasantHousehold documentStation : lih) {
			ids.add(documentStation.getSequenceNbr());
		}



		QueryWrapper<DesignInformation> designInformationQueryWrapper = new QueryWrapper<>();
		designInformationQueryWrapper.in("peasant_household_id", ids);
		List<DesignInformation> li = designInformationMapper.selectList(designInformationQueryWrapper);
		DesignInformation designInformation = new DesignInformation();
		// 组件
		List<Object> assembly = new ArrayList<>();
		// 逆变器
		List<Object> inverter = new ArrayList<>();
		// 电表箱
		List<Object> electricityMeter = new ArrayList<>();
		// 电缆
		List<Object> cable = new ArrayList<>();
		for (DesignInformation des : li) {
			if (des.getAssembly() != null && !des.getAssembly().isEmpty()) {
				assembly.addAll(des.getAssembly());
			}
			if (des.getInverter() != null && !des.getInverter().isEmpty()) {
				inverter.addAll(des.getInverter());
			}
			if (des.getElectricityMeter() != null && !des.getElectricityMeter().isEmpty()) {
				electricityMeter.addAll(des.getElectricityMeter());
			}
			if (des.getCable() != null && !des.getCable().isEmpty()) {
				cable.addAll(des.getCable());
			}
		}
		List<PeasantHousehold> list = workOrderPowerStationMapper.selectPeasantHousehold(sequenceNbr, null);
		if(list != null && list.size() > 0) {
			list.forEach(e -> {
				if(e.getPeasantHouseholdNo() != null) {
					e.setScale(householdContractMapper.getHygfCommercialScale(e.getPeasantHouseholdNo()));
					e.setRealScale(powerStationEngineeringInfoMapper.getRealScaleByPeasantHouseholdNo(e.getPeasantHouseholdNo()));
				}
			});
		}
		Map<String, Object> map = new HashMap<>();
		designInformation.setAssembly(assembly);
		designInformation.setInverter(inverter);
		designInformation.setElectricityMeter(electricityMeter);
		designInformation.setCable(cable);
		map.put("workOrder", model);
		map.put("designInformation", designInformation);
		map.put("peasantHousehold", list);

		return map;

	}

	@Transactional
	public synchronized PowerStationConstructionData addOrUpdate(PowerStationConstructionData powerStationConstructionData) {
		// 如果不是提交进行单独保存
		if (powerStationConstructionData.isCommitFlow()) {
//        if(powerStationConstructionData.getSequenceNbr()!=null){


			// 修改施工电站状态
			LambdaUpdateWrapper<WorkOrderPowerStation> up = new LambdaUpdateWrapper();
			up.eq(WorkOrderPowerStation::getSequenceNbr, powerStationConstructionData.getWorkOrderPowerStationId());
			if (powerStationConstructionData.getConstructionStatus().equals("未完成")) {
				up.set(WorkOrderPowerStation::getPowerStationConstructionStatus, WorkOrderEnum.施工中.getCode());
			} else {
				up.set(WorkOrderPowerStation::getPowerStationConstructionStatus, WorkOrderEnum.待登记.getCode());

//				WorkOrderPowerStation basicGridAcceptanc = workOrderPowerStationMapper
//						.selectById(powerStationConstructionData.getWorkOrderPowerStationId());


				LambdaQueryWrapper<HygfWorkOrderStationAuditing> audit = new LambdaQueryWrapper();
				audit.eq(HygfWorkOrderStationAuditing::getWorkOrderPowerStationId, powerStationConstructionData.getWorkOrderPowerStationId());
				audit.last("limit 1");
				HygfWorkOrderStationAuditing workOrderStationAuditing = hygfWorkOrderStationAuditingService.getBaseMapper().selectOne(audit);

				if (Objects.isNull(workOrderStationAuditing)){
					//开启工作流 并执行一步
					ActWorkflowBatchDTO actWorkflowBatchDTO = new ActWorkflowBatchDTO();
					List<ActWorkflowStartDTO> params = new ArrayList<>();
					ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
					dto.setProcessDefinitionKey(PROCESSKEY);
					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);
					HygfWorkOrderStationAuditingDto hygfWorkOrderStationAuditingDto = new HygfWorkOrderStationAuditingDto();
					BeanUtils.copyProperties(workflowResultDto, hygfWorkOrderStationAuditingDto);
					hygfWorkOrderStationAuditingDto.setWorkOrderPowerStationId(powerStationConstructionData.getWorkOrderPowerStationId());
					hygfWorkOrderStationAuditingDto.setPromoter(RequestContext.getExeUserId());
					hygfWorkOrderStationAuditingService.createWithModel(hygfWorkOrderStationAuditingDto);
					//发起待办
					WorkOrder workOrder = this.selectOne(powerStationConstructionData.getWorkOrderId());
					String regionalCompaniesCode="";
					String amosDealerOrgCode="";
					if(Objects.nonNull(workOrder)){
						regionalCompaniesCode=workOrder.getRegionCode();
						amosDealerOrgCode=workOrder.getAmosDealerOrgCode();
					}
					String taskName = workOrderPowerStationMapper.getStationName(powerStationConstructionData.getWorkOrderPowerStationId())+WorkOrderEnum.待登记.getCode();
					RouthPathVO routhPathVO = new RouthPathVO();
					routhPathVO.setRouthPathId(String.valueOf(powerStationConstructionData.getWorkOrderPowerStationId()));
					String routhPath = toDoTasksService.getRouthPath(TaskTypeStationEnum.施工.getCode(),workflowResultDto.getNextNodeKey(), routhPathVO);
					String wxRouthPath = toDoTasksService.getWxRouthPath(TaskTypeStationEnum.施工.getCode(),workflowResultDto.getNextNodeKey(), routhPathVO);
					ToDoTasks toDoTasks=  new ToDoTasks (TaskTypeStationEnum.施工.getCode(),  powerStationConstructionData.getWorkOrderPowerStationId(),  taskName, regionalCompaniesCode,routhPath,wxRouthPath);
					List<String> userIds = Arrays.asList(Optional.ofNullable(workflowResultDto.getNextExecuteUserIds()).orElse("").split(","));
					List<String> filterUsers = toDoTasksService.filterUsers(TaskTypeStationEnum.施工.getCode(),workflowResultDto.getNextNodeKey(),userIds, regionalCompaniesCode, amosDealerOrgCode);
					toDoTasksService.completeAndAddToDoTask(filterUsers,toDoTasks,"");
				}else {
					this.wofkflowExcute(workOrderStationAuditing.getInstanceId(),"0","通过",BusinessWorkflowKey.施工完成提交.getCode());
				}


//				// 施工完成
//				LambdaUpdateWrapper<PeasantHousehold> up1 = new LambdaUpdateWrapper<>();
//				up1.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.并网完成.getCode());
//				long idsk = basicGridAcceptanc.getPeasantHouseholdId();
//				up1.eq(PeasantHousehold::getSequenceNbr, idsk);
//				peasantHouseholdMapper.update(null, up1);
			}
			up.set(WorkOrderPowerStation::getPowerStationAreaStatus,null);
			up.set(WorkOrderPowerStation::getPowerStationDesignStatus,null);
			up.set(WorkOrderPowerStation::getPowerStationEngineeringStatus,null);
			workOrderPowerStationMapper.update(null, up);
			// 修改派工单状态
			LambdaQueryWrapper<WorkOrderPowerStation> qu = new LambdaQueryWrapper();
			qu.eq(WorkOrderPowerStation::getWorkOrderId, powerStationConstructionData.getWorkOrderId());
			List<String> d = new ArrayList<>();
			d.add(WorkOrderEnum.施工中.getCode());
			d.add(WorkOrderEnum.待施工.getCode());
			qu.in(WorkOrderPowerStation::getPowerStationConstructionStatus, d);
			List<WorkOrderPowerStation> list = workOrderPowerStationMapper.selectList(qu);

			LambdaUpdateWrapper<WorkOrder> upq = new LambdaUpdateWrapper();
			upq.eq(WorkOrder::getSequenceNbr, powerStationConstructionData.getWorkOrderId());
			if (list != null && !list.isEmpty()) {
				upq.set(WorkOrder::getWorkOrderStatus, WorkOrderEnum.施工中.getCode());
			} else {
				upq.set(WorkOrder::getWorkOrderStatus, WorkOrderEnum.登记中.getCode());
			}
			workOrderMapper.update(null, upq);

		}

		// 增加操作日志
		if (powerStationConstructionData.getSequenceNbr() != null) {
			Date date = new Date();
			// 第一次点击“施工资料上传”按钮会生成一条数据
			ConstructionRecords da = new ConstructionRecords(powerStationConstructionData.getRecUserName(), "编辑施工资料",
					date, "", powerStationConstructionData.getWorkOrderId(),
					powerStationConstructionData.getWorkOrderPowerStationId(), null, "");
			LambdaUpdateWrapper<ConstructionRecords> pcr = new LambdaUpdateWrapper<>();
			pcr.eq(ConstructionRecords::getWorkOrderId, powerStationConstructionData.getWorkOrderId());
			pcr.eq(ConstructionRecords::getWorkOrderPowerStationId, powerStationConstructionData.getWorkOrderPowerStationId());
			pcr.eq(ConstructionRecords::getOperationContent, "新增施工资料");// 自审不通过，重新上传的时候不要覆盖之前的数据
			constructionRecordsServiceImpl.saveOrUpdate(da,pcr);
			//添加施工开始时间
			WorkOrderPowerStation workOrderPowerStation = workOrderPowerStationMapper.selectById(powerStationConstructionData.getWorkOrderPowerStationId());
			if(Objects.nonNull(workOrderPowerStation) && Objects.isNull(workOrderPowerStation.getSgCreateTime())){
				LambdaUpdateWrapper<WorkOrderPowerStation> wrapper = new LambdaUpdateWrapper<>();
				wrapper.set(WorkOrderPowerStation::getSgCreateTime, date);
				wrapper.eq(WorkOrderPowerStation::getSequenceNbr, powerStationConstructionData.getWorkOrderPowerStationId());
				workOrderPowerStationMapper.update(null,wrapper);
			}

		} else {
			ConstructionRecords da = new ConstructionRecords(powerStationConstructionData.getRecUserName(), "新增施工资料",
					new Date(), "", powerStationConstructionData.getWorkOrderId(),
					powerStationConstructionData.getWorkOrderPowerStationId(), null, "");
			LambdaUpdateWrapper<ConstructionRecords> pcr = new LambdaUpdateWrapper<>();
			pcr.eq(ConstructionRecords::getWorkOrderId, powerStationConstructionData.getWorkOrderId());
			pcr.eq(ConstructionRecords::getWorkOrderPowerStationId, powerStationConstructionData.getWorkOrderPowerStationId());
			constructionRecordsServiceImpl.saveOrUpdate(da,pcr);
		}

		// 新增施工信息
		// 防止重复添加
		LambdaUpdateWrapper<PowerStationConstructionData> psc = new LambdaUpdateWrapper<>();
		psc.eq(PowerStationConstructionData::getWorkOrderPowerStationId,
				powerStationConstructionData.getWorkOrderPowerStationId());
		psc.eq(PowerStationConstructionData::getWorkOrderId, powerStationConstructionData.getWorkOrderId());
		powerStationConstructionDataService.saveOrUpdate(powerStationConstructionData, psc);
		// powerStationConstructionDataService.saveOrUpdate(powerStationConstructionData);



//        }else{
//           //修改施工电站状态
//            LambdaUpdateWrapper<WorkOrderPowerStation> up=new LambdaUpdateWrapper();
//            up.eq(WorkOrderPowerStation::getSequenceNbr,powerStationConstructionData.getWorkOrderPowerStationId());
//            if(powerStationConstructionData.getConstructionStatus().equals("未完成")){
//                up.set(WorkOrderPowerStation::getPowerStationConstructionStatus,WorkOrderEnum.施工中.getCode());
//            }else{
//                up.set(WorkOrderPowerStation::getPowerStationConstructionStatus,WorkOrderEnum.待登记.getCode());
//            }
//            workOrderPowerStationMapper.update(null,up);
//           //修改派工单状态
//            LambdaQueryWrapper<WorkOrderPowerStation> qu=new LambdaQueryWrapper();
//            qu.eq(WorkOrderPowerStation::getWorkOrderId,powerStationConstructionData.getWorkOrderId());
//            qu.eq(WorkOrderPowerStation::getPowerStationConstructionStatus,WorkOrderEnum.待施工.getCode());
//            List<WorkOrderPowerStation> list=workOrderPowerStationMapper.selectList(qu);
//
//
//            LambdaUpdateWrapper<WorkOrder> upq=new LambdaUpdateWrapper();
//            upq.eq(WorkOrder::getSequenceNbr,powerStationConstructionData.getWorkOrderId());
//            if(list!=null&&!list.isEmpty()){
//                upq.set(WorkOrder::getWorkOrderStatus,WorkOrderEnum.施工中.getCode());
//            }else{
//                upq.set(WorkOrder::getWorkOrderStatus,WorkOrderEnum.登记中.getCode());
//            }
//            workOrderMapper.update(null,upq);
//            //修改施工信息
//
//
//        }

		return powerStationConstructionData;
	}

 		//	工作流执行一步
	public void wofkflowExcute(String instanceId, String approvalStatus,String comment,String taskKey) {
		LambdaQueryWrapper<HygfWorkOrderStationAuditing> query = new LambdaQueryWrapper<>();
		query.eq(HygfWorkOrderStationAuditing::getInstanceId, instanceId);
		query.orderByDesc(BaseEntity::getRecDate);
		query.last("limit 1");
		HygfWorkOrderStationAuditing hygfWorkOrderStationAuditing = hygfWorkOrderStationAuditingService.getBaseMapper().selectOne(query);
		if (!taskKey.contains(hygfWorkOrderStationAuditing.getNextNodeKey())){
//			throw new BadRequest("无可执行任务");
			return;
		}
		//组装信息
		TaskResultDTO task = new TaskResultDTO();

		task.setTaskId(hygfWorkOrderStationAuditing.getNextTaskId());
		HashMap<String, Object> map = new HashMap<>();
		HygfWorkOrderStationAuditingDto workOrderStationAuditingDto = new HygfWorkOrderStationAuditingDto();
		task.setResultCode("approvalStatus");
		map.put("approvalStatus", approvalStatus);
		task.setComment(comment == null?"":comment);
		task.setVariable(map);
		//执行流程
		ProcessTaskDTO processTaskDTO = workFlowService.complete(hygfWorkOrderStationAuditing.getNextTaskId(), task);
		List<WorkflowResultDto> workflowResultDtos = workFlowService.buildWorkFlowInfo(CollectionUtil.newArrayList(processTaskDTO));
		WorkflowResultDto workflowResultDto = workflowResultDtos.get(0);
		BeanUtils.copyProperties(workflowResultDto, workOrderStationAuditingDto);
		workOrderStationAuditingDto.setWorkOrderPowerStationId(hygfWorkOrderStationAuditing.getWorkOrderPowerStationId());
		workOrderStationAuditingDto.setPromoter(hygfWorkOrderStationAuditing.getPromoter());
		workOrderStationAuditingDto.setStatus(approvalStatus);
		if (null == workOrderStationAuditingDto.getInstanceId()) {
			workOrderStationAuditingDto.setInstanceId(hygfWorkOrderStationAuditing.getInstanceId());
		}
		hygfWorkOrderStationAuditingService.createWithModel(workOrderStationAuditingDto);
		//更新待办
		WorkOrderPowerStation workOrderPowerStation = workOrderPowerStationMapper.selectById(hygfWorkOrderStationAuditing.getWorkOrderPowerStationId());
		WorkOrder workOrder = this.selectOne(workOrderPowerStation.getWorkOrderId());
		String regionalCompaniesCode="";
		String amosDealerOrgCode="";
		if(Objects.nonNull(workOrder)){
			regionalCompaniesCode=workOrder.getRegionCode();
			amosDealerOrgCode = workOrder.getAmosDealerOrgCode();
		}
		String taskName ="";
		if ("Activity_1bldcno".equals(workflowResultDto.getNextNodeKey())){
			taskName = workOrderPowerStationMapper.getStationName(workOrderPowerStation.getSequenceNbr())+"待施工验收-片区运营审核";
		}else {
			taskName = workOrderPowerStationMapper.getStationName(workOrderPowerStation.getSequenceNbr())+"待"+workflowResultDto.getNextNodeName();
		}
		RouthPathVO routhPathVO = new RouthPathVO();
		routhPathVO.setRouthPathId(String.valueOf(hygfWorkOrderStationAuditing.getWorkOrderPowerStationId()));
		String routhPath = toDoTasksService.getRouthPath(TaskTypeStationEnum.施工.getCode(),workflowResultDto.getNextNodeKey(), routhPathVO);
		String wxRouthPath = toDoTasksService.getWxRouthPath(TaskTypeStationEnum.施工.getCode(),workflowResultDto.getNextNodeKey(), routhPathVO);
		ToDoTasks toDoTasks=  new ToDoTasks (TaskTypeStationEnum.施工.getCode(),  hygfWorkOrderStationAuditing.getWorkOrderPowerStationId(),   taskName,regionalCompaniesCode,routhPath,wxRouthPath);
		List<String> filterUsers;
		if("Activity_0bs6t4g".equals(workflowResultDto.getNextNodeKey())){
			String roleId = toDoTasksService.getRoleIdByName("户用光伏-经销商-施工");
			filterUsers = toDoTasksService.getTodoUserIds(regionalCompaniesCode, roleId, amosDealerOrgCode);
		}else {
			List<String> userIds = Arrays.asList(Optional.ofNullable(workflowResultDto.getNextExecuteUserIds()).orElse("").split(","));
			filterUsers = toDoTasksService.filterUsers(TaskTypeStationEnum.施工.getCode(), workflowResultDto.getNextNodeKey(),userIds, regionalCompaniesCode, amosDealerOrgCode);
		}
		toDoTasksService.completeAndAddToDoTask(filterUsers,toDoTasks,"");
	}

	public Page<WorkOrder> selectPage(int pageNum, int pageSize, WorkOrder workOrder) {
		PageHelper.startPage(pageNum, pageSize);
		List<WorkOrder> list = workOrderMapper.selectWorkOrderList(workOrder);

		list.stream().forEach(e->{
			if (!StringUtils.isEmpty(e.getOwnersName())) {
				if (e.getOwnersName().split(",").length > 3){
					e.setOwnersName(String.join(",", Arrays.copyOfRange(e.getOwnersName().split(","), 0, 3)));
				}
			}
		});

		PageInfo<WorkOrder> page = new PageInfo(list);
		Page<WorkOrder> pagenew = new Page<WorkOrder>();
		pagenew.setCurrent(pageNum);
		pagenew.setTotal(page.getTotal());
		pagenew.setSize(pageSize);
		pagenew.setRecords(page.getList());
		return pagenew;
	}

	public Page<WorkOrderPage> queryForwgpage(int pageNum, int pageSize, WorkOrderPage workOrder) {
		PageHelper.startPage(pageNum, pageSize);
		List<WorkOrderPage> list = workOrderMapper.queryForwgpage(workOrder);

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

		}


		PageInfo<WorkOrderPage> page = new PageInfo(list);
		Page<WorkOrderPage> pagenew = new Page<WorkOrderPage>();
		pagenew.setCurrent(pageNum);
		pagenew.setTotal(page.getTotal());
		pagenew.setSize(pageSize);
		pagenew.setRecords(page.getList());
		return pagenew;
	}

	public SurveyInfoAllDto getsurveyQueryxq(Long peasantHouseholdId, Long workOrderId, Long workOrderPowerStationId) {

		SurveyInfoAllDto surveyInfoAllDto = new SurveyInfoAllDto();
		PeasantHousehold peasantHousehold = new PeasantHousehold();

		LambdaQueryWrapper<PeasantHousehold> peasantHouseholdWrapper = new LambdaQueryWrapper<>();
		peasantHouseholdWrapper.eq(PeasantHousehold::getSequenceNbr, peasantHouseholdId);
		peasantHousehold = peasantHouseholdServiceImpl.getBaseMapper().selectOne(peasantHouseholdWrapper);
		String surveyInformationId = String.valueOf(peasantHousehold.getSurveyInformationId());

		// 勘察基本信息
		LambdaQueryWrapper<SurveyInformation> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(SurveyInformation::getSequenceNbr, surveyInformationId);
		SurveyInformation surveyInformation = surveyInformationMapper.selectOne(queryWrapper);
		surveyInfoAllDto.setSurveyInformation(BeanDtoUtils.convert(surveyInformation, SurveyInformationDto.class));
		// 农户信息

		// 获取用户所在经销商单位
		UserUnitInformationDto userUnitInformationDto = personnelBusinessMapper
				.getUserUnitInformationDto(peasantHousehold.getDeveloperUserId());
		BeanUtils.copyProperties(peasantHousehold, surveyInfoAllDto.getSurveyInformation());
		surveyInfoAllDto.getSurveyInformation().setDeveloperName(userUnitInformationDto.getAmosDealerName());
		surveyInfoAllDto.getSurveyInformation().setDeveloperCode(userUnitInformationDto.getAmosDealerOrgCode());
		surveyInfoAllDto.getSurveyInformation().setDeveloperId(userUnitInformationDto.getAmosDealerId());

		if (!StringUtils.isEmpty(peasantHousehold.getProjectAddressName())) {
			surveyInfoAllDto.getSurveyInformation()
					.setProjectAddressText(Arrays.asList(peasantHousehold.getProjectAddressName().split("/")));
		}
		if (!StringUtils.isEmpty(peasantHousehold.getPermanentAddressName())) {
			surveyInfoAllDto.getSurveyInformation()
					.setPermanentAddressText(Arrays.asList(peasantHousehold.getPermanentAddressName().split("/")));
		}
		if (peasantHousehold.getPermanentAddress() == null) {
			surveyInfoAllDto.getSurveyInformation().setPermanentAddress(peasantHousehold.getProjectAddress());
			surveyInfoAllDto.getSurveyInformation().setIsPermanent("1");
		}
		surveyInfoAllDto.getSurveyInformation().setSequenceNbr(surveyInformation.getSequenceNbr());
		QueryWrapper<SurveyDetails> surveyDetailsQueryWrapper = new QueryWrapper<>();
		surveyDetailsQueryWrapper.eq("survey_information_id", surveyInformationId);
		SurveyDetails surveyDetails = surveyDetailsService.getBaseMapper().selectOne(surveyDetailsQueryWrapper);

		if (surveyDetails == null) {
			surveyInfoAllDto.setSurveyDetails(new SurveyDetailsDto());
		} else {
			surveyInfoAllDto.setSurveyDetails(BeanDtoUtils.convert(surveyDetails, SurveyDetailsDto.class));
		}
		QueryWrapper<Information> informationQueryWrapper = new QueryWrapper<>();
		informationQueryWrapper.eq("survey_information_id", surveyInformationId);
		Information information = informationService.getBaseMapper().selectOne(informationQueryWrapper);
		if (information == null) {
			surveyInfoAllDto.setInformation(new InformationDto());
		} else {
			surveyInfoAllDto.setInformation(BeanDtoUtils.convert(information, InformationDto.class));
		}
		QueryWrapper<Commercial> commercialQueryWrapper = new QueryWrapper<>();
		commercialQueryWrapper.eq("survey_information_id", surveyInformationId);
		Commercial commercial = commercialService.getBaseMapper().selectOne(commercialQueryWrapper);
		if (commercial == null) {
			commercial = new Commercial();
		}
		commercial.setApplicant(peasantHousehold.getOwnersName());
		commercial.setIdCard(peasantHousehold.getIdCard());
		commercial.setTelephone(peasantHousehold.getTelephone());
		commercial.setProjectAddress(peasantHousehold.getProjectAddress());
		commercial.setProjectAddressName(peasantHousehold.getProjectAddressName());
		commercial.setProjectAddressDetail(peasantHousehold.getProjectAddressDetail());
		commercial.setLegalContactTelephone(peasantHousehold.getTelephone());
		if (information == null) {
			CommercialDto commercialDto = BeanDtoUtils.convert(commercial, CommercialDto.class);
			commercialDto.setType("zrr");
			commercialDto.setLegalType("zjdnhw");
			surveyInfoAllDto.setCommercial(commercialDto);
		} else {
			surveyInfoAllDto.setCommercial(BeanDtoUtils.convert(commercial, CommercialDto.class));
			if (commercial != null && !StringUtils.isEmpty(commercial.getProjectAddressName())) {
				surveyInfoAllDto.getCommercial()
						.setProjectAddressText(Arrays.asList(commercial.getProjectAddressName().split("/")));
			}
		}
		QueryWrapper<ExtendedInformation> extendedInformationQueryWrapper = new QueryWrapper<>();
		extendedInformationQueryWrapper.eq("survey_information_id", surveyInformationId);
		ExtendedInformation extendedInformation = extendedInformationService.getBaseMapper()
				.selectOne(extendedInformationQueryWrapper);
		if (information == null) {
			surveyInfoAllDto.setExtendedInformation(new ExtendedInformationDto());
		} else {
			surveyInfoAllDto
					.setExtendedInformation(BeanDtoUtils.convert(extendedInformation, ExtendedInformationDto.class));
		}
		QueryWrapper<DesignInformation> designInformationQueryWrapper = new QueryWrapper<>();
		designInformationQueryWrapper.eq("peasant_household_id", peasantHousehold.getSequenceNbr());
		DesignInformation designInformation = designInformationService.getBaseMapper()
				.selectOne(designInformationQueryWrapper);
		if (designInformation == null) {
			surveyInfoAllDto.setDesignInformation(new DesignInformationDto());
		} else {
			surveyInfoAllDto.setDesignInformation(BeanDtoUtils.convert(designInformation, DesignInformationDto.class));
		}

		// 派工单信息
		LambdaQueryWrapper<WorkOrder> upl = new LambdaQueryWrapper();
		upl.eq(WorkOrder::getSequenceNbr, workOrderId);
		WorkOrder workOrder = workOrderMapper.selectOne(upl);

		// 施工信息
		LambdaQueryWrapper<PowerStationConstructionData> up2 = new LambdaQueryWrapper();
		up2.eq(PowerStationConstructionData::getWorkOrderId, workOrderId);
		up2.eq(PowerStationConstructionData::getWorkOrderPowerStationId, workOrderPowerStationId);
		PowerStationConstructionData powerStationConstructionData = powerStationConstructionDataMapper.selectOne(up2);

		//增加整改单数据
		List<HygfRectificationOrder> hygfRectificationOrders = rectificationOrderService.selectForListBySource(String.valueOf(peasantHousehold.getSequenceNbr()), PROCESSKEY);
		if (CollectionUtil.isNotEmpty(hygfRectificationOrders)){
			List<HygfRectificationOrder>  areaOrders = hygfRectificationOrders.stream().filter(e -> e.getRectificationSource().equals("area")).collect(Collectors.toList());
			List<HygfRectificationOrder>  engineeringOrders = hygfRectificationOrders.stream().filter(e -> e.getRectificationSource().equals("engineering")).collect(Collectors.toList());
			List<HygfRectificationOrder>  designOrders = hygfRectificationOrders.stream().filter(e -> e.getRectificationSource().equals("design")).collect(Collectors.toList());
			powerStationConstructionData.setAreaOrders(areaOrders.size()>0?areaOrders:null);
			powerStationConstructionData.setEngineeringOrders(engineeringOrders.size()>0?engineeringOrders:null);
			powerStationConstructionData.setDesignOrders(designOrders.size()>0?designOrders:null);
		}


		// 工程信息

		LambdaQueryWrapper<PowerStationEngineeringInfo> up3 = new LambdaQueryWrapper();
		up3.eq(PowerStationEngineeringInfo::getWorkOrderId, workOrderId);
		up3.eq(PowerStationEngineeringInfo::getWorkOrderPowerStationId, workOrderPowerStationId);
		PowerStationEngineeringInfo powerStationEngineeringInfo = powerStationEngineeringInfoMapper.selectOne(up3);
		if (powerStationConstructionData != null) {
			powerStationEngineeringInfo = powerStationEngineeringInfo != null ? powerStationEngineeringInfo
					: new PowerStationEngineeringInfo();
			powerStationEngineeringInfo
					.setConstructionComponentInfo(powerStationConstructionData.getConstructionComponentInfo());
			powerStationEngineeringInfo
					.setConstructionInverterInfo(powerStationConstructionData.getConstructionInverterInfo());
			powerStationEngineeringInfo
					.setConstructionCollectorBoxInfo(powerStationConstructionData.getConstructionCollectorBoxInfo());
			powerStationEngineeringInfo
					.setConstructionGridBoxInfo(powerStationConstructionData.getConstructionGridBoxInfo());
			powerStationEngineeringInfo.setProjectRegionManager(workOrder.getProjectRegionManager());
			powerStationEngineeringInfo.setProjectRegionManagerPhone(workOrder.getProjectRegionManagerPhone());
			powerStationEngineeringInfo.setConstructionRegionManager(workOrder.getConstructionRegionManager());
			powerStationEngineeringInfo
					.setConstructionRegionManagerPhone(workOrder.getConstructionRegionManagerPhone());
		}

		// 施工自审
		LambdaQueryWrapper<ConstructionRecords> up5 = new LambdaQueryWrapper();
		up5.eq(ConstructionRecords::getWorkOrderId, workOrderId);
		up5.eq(ConstructionRecords::getWorkOrderPowerStationId, workOrderPowerStationId);
		up5.orderByAsc(ConstructionRecords::getRecDate);
		List<ConstructionRecords> li = constructionRecordsMapper.selectList(up5);
		ConstructionRecords data = new ConstructionRecords();
		data.setConstructionRecordsList(li);



		surveyInfoAllDto.setConstructionRecords(data);

		// 并网信息
		LambdaQueryWrapper<HygfOnGrid> up4 = new LambdaQueryWrapper();
		up4.eq(HygfOnGrid::getWorkOrderId, workOrderId);
		up4.eq(HygfOnGrid::getWorkOrderPowerStationId, workOrderPowerStationId);
		HygfOnGrid hygfOnGrid = hygfOnGridMapper.selectOne(up4);
		surveyInfoAllDto.setHygfOnGrid(hygfOnGrid != null ? hygfOnGrid : new HygfOnGrid());
		surveyInfoAllDto.setPowerStationConstructionData(powerStationConstructionData);
		surveyInfoAllDto.setPowerStationEngineeringInfo(powerStationEngineeringInfo);
		surveyInfoAllDto.setWorkOrder(workOrder);

		return surveyInfoAllDto;
	}

	public PowerStationEngineeringInfoAllDto getPowerStationEngineeringInfo(Long workOrderPowerStationId) {

		LambdaQueryWrapper<WorkOrderPowerStation> qu = new LambdaQueryWrapper();
		qu.eq(WorkOrderPowerStation::getSequenceNbr, workOrderPowerStationId);
		WorkOrderPowerStation workOrderPowerStation = workOrderPowerStationMapper.selectOne(qu);
		Long peasantHouseholdId = workOrderPowerStation.getPeasantHouseholdId();
		Long workOrderId = workOrderPowerStation.getWorkOrderId();

		PowerStationEngineeringInfoAllDto surveyInfoAllDto = new PowerStationEngineeringInfoAllDto();
		PeasantHousehold peasantHousehold = new PeasantHousehold();

		LambdaQueryWrapper<PeasantHousehold> peasantHouseholdWrapper = new LambdaQueryWrapper<>();
		peasantHouseholdWrapper.eq(PeasantHousehold::getSequenceNbr, peasantHouseholdId);
		peasantHousehold = peasantHouseholdServiceImpl.getBaseMapper().selectOne(peasantHouseholdWrapper);
		String surveyInformationId = String.valueOf(peasantHousehold.getSurveyInformationId());

		// 勘察基本信息
		LambdaQueryWrapper<SurveyInformation> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(SurveyInformation::getSequenceNbr, surveyInformationId);
		SurveyInformation surveyInformation = surveyInformationMapper.selectOne(queryWrapper);
		surveyInfoAllDto.setSurveyInformation(BeanDtoUtils.convert(surveyInformation, SurveyInformationDto.class));
		// 农户信息

		// 获取用户所在经销商单位
		UserUnitInformationDto userUnitInformationDto = personnelBusinessMapper
				.getUserUnitInformationDto(peasantHousehold.getDeveloperUserId());
		BeanUtils.copyProperties(peasantHousehold, surveyInfoAllDto.getSurveyInformation());
		surveyInfoAllDto.getSurveyInformation().setDeveloperName(userUnitInformationDto.getAmosDealerName());
		surveyInfoAllDto.getSurveyInformation().setDeveloperCode(userUnitInformationDto.getAmosDealerOrgCode());
		surveyInfoAllDto.getSurveyInformation().setDeveloperId(userUnitInformationDto.getAmosDealerId());

		if (!StringUtils.isEmpty(peasantHousehold.getProjectAddressName())) {
			surveyInfoAllDto.getSurveyInformation()
					.setProjectAddressText(Arrays.asList(peasantHousehold.getProjectAddressName().split("/")));
		}
		if (!StringUtils.isEmpty(peasantHousehold.getPermanentAddressName())) {
			surveyInfoAllDto.getSurveyInformation()
					.setPermanentAddressText(Arrays.asList(peasantHousehold.getPermanentAddressName().split("/")));
		}
		if (peasantHousehold.getPermanentAddress() == null) {
			surveyInfoAllDto.getSurveyInformation().setPermanentAddress(peasantHousehold.getProjectAddress());
			surveyInfoAllDto.getSurveyInformation().setIsPermanent("1");
		}
		surveyInfoAllDto.getSurveyInformation().setSequenceNbr(surveyInformation.getSequenceNbr());
		QueryWrapper<SurveyDetails> surveyDetailsQueryWrapper = new QueryWrapper<>();
		surveyDetailsQueryWrapper.eq("survey_information_id", surveyInformationId);
		SurveyDetails surveyDetails = surveyDetailsService.getBaseMapper().selectOne(surveyDetailsQueryWrapper);

		if (surveyDetails == null) {
			surveyInfoAllDto.setSurveyDetails(new SurveyDetailsDto());
		} else {
			surveyInfoAllDto.setSurveyDetails(BeanDtoUtils.convert(surveyDetails, SurveyDetailsDto.class));
		}

//        商务信息
		QueryWrapper<Commercial> commercialQueryWrapper = new QueryWrapper<>();
		commercialQueryWrapper.eq("survey_information_id", surveyInformationId);
		Commercial commercial = commercialService.getBaseMapper().selectOne(commercialQueryWrapper);
		if (commercial == null) {
			commercial = new Commercial();
		}

		commercial.setApplicant(peasantHousehold.getOwnersName());
		commercial.setIdCard(peasantHousehold.getIdCard());
		commercial.setTelephone(peasantHousehold.getTelephone());
		commercial.setProjectAddress(peasantHousehold.getProjectAddress());
		commercial.setProjectAddressName(peasantHousehold.getProjectAddressName());
		commercial.setProjectAddressDetail(peasantHousehold.getProjectAddressDetail());
		commercial.setLegalContactTelephone(peasantHousehold.getTelephone());

//        资料归档
		QueryWrapper<Information> informationQueryWrapper = new QueryWrapper<>();
		informationQueryWrapper.eq("survey_information_id", surveyInformationId);
		Information information = informationService.getBaseMapper().selectOne(informationQueryWrapper);
		if (information == null) {
			surveyInfoAllDto.setInformation(new InformationDto());
		} else {
			// 将商务信息的房产证明文件数据赋值给资料归档的房产证明文件
			information.setCardFile(commercial.getIdCardCredit());
			surveyInfoAllDto.setInformation(BeanDtoUtils.convert(information, InformationDto.class));
		}

		if (information == null) {
			CommercialDto commercialDto = BeanDtoUtils.convert(commercial, CommercialDto.class);
			commercialDto.setType("zrr");
			commercialDto.setLegalType("zjdnhw");
			surveyInfoAllDto.setCommercial(commercialDto);
		} else {
			surveyInfoAllDto.setCommercial(BeanDtoUtils.convert(commercial, CommercialDto.class));
			if (commercial != null && !StringUtils.isEmpty(commercial.getProjectAddressName())) {
				surveyInfoAllDto.getCommercial()
						.setProjectAddressText(Arrays.asList(commercial.getProjectAddressName().split("/")));
			}
		}
		QueryWrapper<ExtendedInformation> extendedInformationQueryWrapper = new QueryWrapper<>();
		extendedInformationQueryWrapper.eq("survey_information_id", surveyInformationId);
		ExtendedInformation extendedInformation = extendedInformationService.getBaseMapper()
				.selectOne(extendedInformationQueryWrapper);
		if (information == null) {
			surveyInfoAllDto.setExtendedInformation(new ExtendedInformationDto());
		} else {
			surveyInfoAllDto
					.setExtendedInformation(BeanDtoUtils.convert(extendedInformation, ExtendedInformationDto.class));
		}
		QueryWrapper<DesignInformation> designInformationQueryWrapper = new QueryWrapper<>();
		designInformationQueryWrapper.eq("peasant_household_id", peasantHousehold.getSequenceNbr());
		DesignInformation designInformation = designInformationService.getBaseMapper()
				.selectOne(designInformationQueryWrapper);
		if (designInformation == null) {
			surveyInfoAllDto.setDesignInformation(new DesignInformationDto());
		} else {
			surveyInfoAllDto.setDesignInformation(BeanDtoUtils.convert(designInformation, DesignInformationDto.class));
		}

		// 派工单信息
		LambdaQueryWrapper<WorkOrder> upl = new LambdaQueryWrapper();
		upl.eq(WorkOrder::getSequenceNbr, workOrderId);
		WorkOrder workOrder = workOrderMapper.selectOne(upl);

		// 施工信息
		LambdaQueryWrapper<PowerStationConstructionData> up2 = new LambdaQueryWrapper();
		up2.eq(PowerStationConstructionData::getWorkOrderId, workOrderId);
		up2.eq(PowerStationConstructionData::getWorkOrderPowerStationId, workOrderPowerStationId);
		PowerStationConstructionData powerStationConstructionData = powerStationConstructionDataMapper.selectOne(up2);

		//增加整改单数据
		List<HygfRectificationOrder> hygfRectificationOrders = rectificationOrderService.selectForListBySource(String.valueOf(peasantHousehold.getSequenceNbr()), PROCESSKEY);
		if (CollectionUtil.isNotEmpty(hygfRectificationOrders)){
			List<HygfRectificationOrder>  areaOrders = hygfRectificationOrders.stream().filter(e -> e.getRectificationSource().equals("area")).collect(Collectors.toList());
			List<HygfRectificationOrder>  engineeringOrders = hygfRectificationOrders.stream().filter(e -> e.getRectificationSource().equals("engineering")).collect(Collectors.toList());
			List<HygfRectificationOrder>  designOrders = hygfRectificationOrders.stream().filter(e -> e.getRectificationSource().equals("design")).collect(Collectors.toList());
			powerStationConstructionData.setAreaOrders(areaOrders.size()>0?areaOrders:null);
			powerStationConstructionData.setEngineeringOrders(engineeringOrders.size()>0?engineeringOrders:null);
			powerStationConstructionData.setDesignOrders(designOrders.size()>0?designOrders:null);
		}


		// 工程信息

		LambdaQueryWrapper<PowerStationEngineeringInfo> up3 = new LambdaQueryWrapper();
		up3.eq(PowerStationEngineeringInfo::getWorkOrderId, workOrderId);
		up3.eq(PowerStationEngineeringInfo::getWorkOrderPowerStationId, workOrderPowerStationId);
		PowerStationEngineeringInfo powerStationEngineeringInfo = powerStationEngineeringInfoMapper.selectOne(up3);
		if (powerStationConstructionData != null) {
			powerStationEngineeringInfo = powerStationEngineeringInfo != null ? powerStationEngineeringInfo
					: new PowerStationEngineeringInfo();
			powerStationEngineeringInfo
					.setConstructionComponentInfo(powerStationConstructionData.getConstructionComponentInfo());
			powerStationEngineeringInfo
					.setConstructionInverterInfo(powerStationConstructionData.getConstructionInverterInfo());
			powerStationEngineeringInfo
					.setConstructionCollectorBoxInfo(powerStationConstructionData.getConstructionCollectorBoxInfo());
			powerStationEngineeringInfo
					.setConstructionGridBoxInfo(powerStationConstructionData.getConstructionGridBoxInfo());
			powerStationEngineeringInfo.setProjectRegionManager(workOrder.getProjectRegionManager());
			powerStationEngineeringInfo.setProjectRegionManagerPhone(workOrder.getProjectRegionManagerPhone());
			powerStationEngineeringInfo.setConstructionRegionManager(workOrder.getConstructionRegionManager());
			powerStationEngineeringInfo
					.setConstructionRegionManagerPhone(workOrder.getConstructionRegionManagerPhone());
		}
		// 并网信息
		LambdaQueryWrapper<HygfOnGrid> up4 = new LambdaQueryWrapper<HygfOnGrid>();
		up4.eq(HygfOnGrid::getWorkOrderId, workOrderId);
		up4.eq(HygfOnGrid::getWorkOrderPowerStationId, workOrderPowerStationId);
		HygfOnGrid hygfOnGrid = hygfOnGridMapper.selectOne(up4);

		//增加整改单数据
		List<HygfRectificationOrder> hygfRectificationOrderList= rectificationOrderService.selectForListBySource(String.valueOf(peasantHousehold.getSequenceNbr()), RectificationOrderEnum.并网.getName());
		if (CollectionUtil.isNotEmpty(hygfRectificationOrderList)){
			List<HygfRectificationOrder>  areaOrders = hygfRectificationOrderList.stream().filter(e -> e.getRectificationSource().equals("bw-area")).collect(Collectors.toList());
			List<HygfRectificationOrder>  engineeringOrders = hygfRectificationOrderList.stream().filter(e -> e.getRectificationSource().equals("bw-engineering")).collect(Collectors.toList());
			List<HygfRectificationOrder>  designOrders = hygfRectificationOrderList.stream().filter(e -> e.getRectificationSource().equals("bw-design")).collect(Collectors.toList());
			hygfOnGrid.setAreaOrders(areaOrders.size()>0?areaOrders:null);
			hygfOnGrid.setEngineeringOrders(engineeringOrders.size()>0?engineeringOrders:null);
			hygfOnGrid.setDesignOrders(designOrders.size()>0?designOrders:null);
		}

		surveyInfoAllDto.setHygfOnGrid(hygfOnGrid != null ? hygfOnGrid : new HygfOnGrid());
		surveyInfoAllDto.setPowerStationConstructionData(powerStationConstructionData);
		surveyInfoAllDto.setPowerStationEngineeringInfo(powerStationEngineeringInfo);
		surveyInfoAllDto.setWorkOrder(workOrder);

		// 施工自审操作记录
		LambdaQueryWrapper<ConstructionRecords> up5 = new LambdaQueryWrapper<ConstructionRecords>();
		up5.eq(ConstructionRecords::getWorkOrderId, workOrderId);
		up5.eq(ConstructionRecords::getWorkOrderPowerStationId, workOrderPowerStationId);
		up5.orderByAsc(ConstructionRecords::getRecDate);
		List<ConstructionRecords> li = constructionRecordsMapper.selectList(up5);
		ConstructionRecords data = new ConstructionRecords();
		data.setConstructionRecordsList(li);
		surveyInfoAllDto.setConstructionRecords(data);

		LambdaQueryWrapper<BasicGridRecord> quv = new LambdaQueryWrapper<BasicGridRecord>();
		quv.eq(BasicGridRecord::getPeasantHouseholdId, peasantHouseholdId);
		BasicGridRecord basicGridAcceptance = basicGridRecordMapper.selectOne(quv);
		if (Objects.nonNull(basicGridAcceptance)){
			LambdaQueryWrapper<ConstructionGirdRecords> up8 = new LambdaQueryWrapper<ConstructionGirdRecords>();
			up8.eq(ConstructionGirdRecords::getGridId, basicGridAcceptance.getSequenceNbr());
			up8.eq(ConstructionGirdRecords::getWorkOrderPowerStationId, workOrderPowerStationId);
			up8.orderByAsc(ConstructionGirdRecords::getRecDate);
			List<ConstructionGirdRecords> li2 = constructionGirdRecordsMapper.selectList(up8);
			ConstructionGirdRecords constructionGirdRecords = new ConstructionGirdRecords();
			constructionGirdRecords.setConstructionRecordsList(li2);
			surveyInfoAllDto.setConstructionGirdRecords(constructionGirdRecords);
		}

		// 审核意见
		if (Objects.nonNull(basicGridAcceptance) && !StringUtils.isEmpty(basicGridAcceptance.getInstanceId())) {
			try {
				Map<String, Object> flowLoggerMap = workflowFeignClient
						.getFlowLogger(basicGridAcceptance.getInstanceId()).getResult();
				List<LinkedHashMap> flowLogger = (List<LinkedHashMap>) flowLoggerMap.get("flowLogger");
				if (flowLogger.size() > 0) {
					Collections.reverse(flowLogger);
				}
				List<LinkedHashMap> flowLoggernew = new ArrayList<>();
				for (LinkedHashMap linkedHashMap : flowLogger) {
					if (linkedHashMap.get("operateDate") != null
							&& !linkedHashMap.get("operateDate").toString().isEmpty()) {
						LinkedHashMap linke = new LinkedHashMap();
						linke.put("approvalStatue", linkedHashMap.get("approvalStatue").toString());
						// 审核意见
						List<LinkedHashMap> approvalSuggestion = (List<LinkedHashMap>) linkedHashMap
								.get("approvalSuggestion");
						if (approvalSuggestion != null && !approvalSuggestion.isEmpty()) {
							linke.put("approvalSuggestion", approvalSuggestion.get(0).get("message"));
						}
						linke.put("taskName", linkedHashMap.get("taskName").toString());
						linke.put("operator", linkedHashMap.get("operator").toString());
						linke.put("operateDate", linkedHashMap.get("operateDate").toString());
						flowLoggernew.add(linke);
					}
				}
				LoggerDto loggerDto = new LoggerDto();
				loggerDto.setLogger(flowLoggernew);
				surveyInfoAllDto.setLoggerDto(loggerDto);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		LambdaQueryWrapper<AcceptanceCheck> quv1 = new LambdaQueryWrapper();
		quv1.eq(AcceptanceCheck::getPeasantHouseholdId, peasantHouseholdId);
		AcceptanceCheck acceptanceCheck = acceptanceCheckMapper.selectOne(quv1);

		//增加整改单数据
		List<HygfRectificationOrder> hygfRectificationOrderListYs= rectificationOrderService.selectForListBySource(String.valueOf(peasantHousehold.getSequenceNbr()), RectificationOrderEnum.验收.getName());
		if (CollectionUtil.isNotEmpty(hygfRectificationOrderListYs)){
			List<HygfRectificationOrder>  areaOrders = hygfRectificationOrderListYs.stream().filter(e -> e.getRectificationSource().equals("ys-area")).collect(Collectors.toList());
			List<HygfRectificationOrder>  financeOrders = hygfRectificationOrderListYs.stream().filter(e -> e.getRectificationSource().equals("ys-tourong")).collect(Collectors.toList());
			List<HygfRectificationOrder>  legalOrders = hygfRectificationOrderListYs.stream().filter(e -> e.getRectificationSource().equals("ys-fawu")).collect(Collectors.toList());
			List<HygfRectificationOrder>  propertyOrders = hygfRectificationOrderListYs.stream().filter(e -> e.getRectificationSource().equals("ys-zichan")).collect(Collectors.toList());
			acceptanceCheck.setAreaOrders(areaOrders.size()>0?areaOrders:null);
			acceptanceCheck.setFinanceOrders(financeOrders.size()>0?financeOrders:null);
			acceptanceCheck.setLegalOrders(legalOrders.size()>0?legalOrders:null);
			acceptanceCheck.setPropertyOrders(propertyOrders.size()>0?propertyOrders:null);
		}
		if (Objects.nonNull(acceptanceCheck)){
			LambdaQueryWrapper<ConstructionAcceptanceRecords> up7 = new LambdaQueryWrapper<ConstructionAcceptanceRecords>();
			up7.eq(ConstructionAcceptanceRecords::getAcceptanceId, acceptanceCheck.getSequenceNbr());
			up7.eq(ConstructionAcceptanceRecords::getWorkOrderPowerStationId, workOrderPowerStationId);
			up7.orderByAsc(ConstructionAcceptanceRecords::getRecDate);
			List<ConstructionAcceptanceRecords> li1 = constructionAcceptanceRecordsMapper.selectList(up7);
			ConstructionAcceptanceRecords constructionAcceptanceRecords = new ConstructionAcceptanceRecords();
			constructionAcceptanceRecords.setConstructionRecordsList(li1);
			surveyInfoAllDto.setAcceptanceRecords(constructionAcceptanceRecords);
		}
		surveyInfoAllDto.setAcceptanceCheck(acceptanceCheck);
		// 审核意见
		if (Objects.nonNull(acceptanceCheck) && !StringUtils.isEmpty(acceptanceCheck.getInstanceId())) {
			try {
				Map<String, Object> flowLogMap = workflowFeignClient
						.getFlowLogger(acceptanceCheck.getInstanceId()).getResult();
				List<LinkedHashMap> flowLogger1 = (List<LinkedHashMap>) flowLogMap.get("flowLogger");
				if (flowLogger1.size() > 0) {
					Collections.reverse(flowLogger1);
				}
				List<LinkedHashMap> flowLoggernew1 = new ArrayList<>();
				for (LinkedHashMap linkedHashMap : flowLogger1) {
					if (linkedHashMap.get("operateDate") != null
							&& !linkedHashMap.get("operateDate").toString().isEmpty()) {
						LinkedHashMap linke = new LinkedHashMap();
						linke.put("approvalStatue", linkedHashMap.get("approvalStatue").toString());
						// 审核意见
						List<LinkedHashMap> approvalSuggestion = (List<LinkedHashMap>) linkedHashMap
								.get("approvalSuggestion");
						if (approvalSuggestion != null && !approvalSuggestion.isEmpty()) {
							linke.put("approvalSuggestion", approvalSuggestion.get(0).get("message"));
						}
						linke.put("taskName", linkedHashMap.get("taskName").toString());
						linke.put("operator", linkedHashMap.get("operator").toString());
						linke.put("operateDate", linkedHashMap.get("operateDate").toString());
						flowLoggernew1.add(linke);
					}
				}
				LoggerDto loggerDto1 = new LoggerDto();
				loggerDto1.setLogger(flowLoggernew1);
				surveyInfoAllDto.setLoggerYsDto(loggerDto1);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return surveyInfoAllDto;
//        LambdaQueryWrapper<PeasantHousehold> peasantHouseholdWrapper = new LambdaQueryWrapper<>();
//        peasantHouseholdWrapper.eq(PeasantHousehold::getSequenceNbr, peasantHouseholdId);
//        peasantHousehold = peasantHouseholdServiceImpl.getBaseMapper().selectOne(peasantHouseholdWrapper);
//        String  surveyInformationId = String.valueOf(peasantHousehold.getSurveyInformationId());
//
//        //勘察基本信息
//        LambdaQueryWrapper<SurveyInformation> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(SurveyInformation::getSequenceNbr, surveyInformationId);
//        SurveyInformation surveyInformation = surveyInformationMapper.selectOne(queryWrapper);
//        surveyInfoAllDto.setSurveyInformation(BeanDtoUtils.convert(surveyInformation, SurveyInformationDto.class));
//
//
//        //获取用户所在经销商单位
//        UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto(peasantHousehold.getDeveloperUserId());
//        BeanUtils.copyProperties(peasantHousehold, surveyInfoAllDto.getSurveyInformation());
//        surveyInfoAllDto.getSurveyInformation().setDeveloperName(userUnitInformationDto.getAmosDealerName());
//        surveyInfoAllDto.getSurveyInformation().setDeveloperCode(userUnitInformationDto.getAmosDealerOrgCode());
//        surveyInfoAllDto.getSurveyInformation().setDeveloperId(userUnitInformationDto.getAmosDealerId());
//
//        if (!StringUtils.isEmpty(peasantHousehold.getProjectAddressName())) {
//            surveyInfoAllDto.getSurveyInformation().setProjectAddressText(Arrays.asList(peasantHousehold.getProjectAddressName().split("/")));
//        }
//        if(!StringUtils.isEmpty(peasantHousehold.getPermanentAddressName())){
//            surveyInfoAllDto.getSurveyInformation().setPermanentAddressText(Arrays.asList(peasantHousehold.getPermanentAddressName().split("/")));
//        }
//        if(peasantHousehold.getPermanentAddress() ==null){
//            surveyInfoAllDto.getSurveyInformation().setPermanentAddress(peasantHousehold.getProjectAddress());
//            surveyInfoAllDto.getSurveyInformation().setIsPermanent("1");
//        }
//        surveyInfoAllDto.getSurveyInformation().setSequenceNbr(surveyInformation.getSequenceNbr());
//        surveyInfoAllDto.getSurveyInformation().setCreatorTime(new Date());
//
//        //派工单信息
//        LambdaQueryWrapper<WorkOrder> upl=new LambdaQueryWrapper();
//        upl.eq(WorkOrder::getSequenceNbr,workOrderId);
//        WorkOrder workOrder= workOrderMapper.selectOne(upl);
//
//        //施工信息
//        LambdaQueryWrapper<PowerStationConstructionData> up2=new LambdaQueryWrapper();
//        up2.eq(PowerStationConstructionData::getWorkOrderId,workOrderId);
//        up2.eq(PowerStationConstructionData::getWorkOrderPowerStationId,workOrderPowerStationId);
//        PowerStationConstructionData powerStationConstructionData=powerStationConstructionDataMapper.selectOne(up2);
//
//        //工程信息
//
//        LambdaQueryWrapper<PowerStationEngineeringInfo> up3=new LambdaQueryWrapper();
//        up3.eq(PowerStationEngineeringInfo::getWorkOrderId,workOrderId);
//        up3.eq(PowerStationEngineeringInfo::getWorkOrderPowerStationId,workOrderPowerStationId);
//        PowerStationEngineeringInfo powerStationEngineeringInfo=powerStationEngineeringInfoMapper.selectOne(up3);
//        if(powerStationConstructionData!=null){
//            powerStationEngineeringInfo=powerStationEngineeringInfo!=null?powerStationEngineeringInfo:new PowerStationEngineeringInfo();
//            powerStationEngineeringInfo.setConstructionComponentInfo(powerStationConstructionData.getConstructionComponentInfo());
//            powerStationEngineeringInfo.setConstructionInverterInfo(powerStationConstructionData.getConstructionInverterInfo());
//            powerStationEngineeringInfo.setConstructionCollectorBoxInfo(powerStationConstructionData.getConstructionCollectorBoxInfo());
//            powerStationEngineeringInfo.setConstructionGridBoxInfo(powerStationConstructionData.getConstructionGridBoxInfo());
//            powerStationEngineeringInfo.setProjectRegionManager(workOrder.getProjectRegionManager());
//            powerStationEngineeringInfo.setProjectRegionManagerPhone(workOrder.getProjectRegionManagerPhone());
//            powerStationEngineeringInfo.setConstructionRegionManager(workOrder.getConstructionRegionManager());
//            powerStationEngineeringInfo.setConstructionRegionManagerPhone(workOrder.getConstructionRegionManagerPhone());
//        }
//        powerStationEngineeringInfo.setCompletionDate(new Date());
//        surveyInfoAllDto.setPowerStationConstructionData(powerStationConstructionData);
//        surveyInfoAllDto.setPowerStationEngineeringInfo(powerStationEngineeringInfo);

//        return surveyInfoAllDto;
	}

	@Transactional(isolation = Isolation.REPEATABLE_READ)
	public PowerStationEngineeringInfoAllDto addPowerStationEngineeringInfo(
			PowerStationEngineeringInfoAllDto powerStationEngineeringInfoAllDto) {

		LambdaQueryWrapper<WorkOrderPowerStation> qu = new LambdaQueryWrapper();
		qu.eq(WorkOrderPowerStation::getSequenceNbr, powerStationEngineeringInfoAllDto.getWorkOrderPowerStationId());
		WorkOrderPowerStation workOrderPowerStation = workOrderPowerStationMapper.selectOne(qu);

		LambdaQueryWrapper<HygfWorkOrderStationAuditing> audit = new LambdaQueryWrapper();
		audit.eq(HygfWorkOrderStationAuditing::getWorkOrderPowerStationId, powerStationEngineeringInfoAllDto.getWorkOrderPowerStationId());
		audit.last("limit 1");
		HygfWorkOrderStationAuditing workOrderStationAuditing = hygfWorkOrderStationAuditingService.getBaseMapper().selectOne(audit);
		//兼容历史数据
		if(!Objects.isNull(workOrderStationAuditing )){
			this.wofkflowExcute(workOrderStationAuditing.getInstanceId(), "0", "通过",BusinessWorkflowKey.完工登记.getCode());

		}

		// 修改电站状态
		workOrderPowerStation.setPowerStationConstructionStatus(WorkOrderEnum.经销商工程待审核.getCode());
		workOrderPowerStationMapper.updateById(workOrderPowerStation);
		// 修改派工单状态PowerStationEngineeringInfo
		LambdaQueryWrapper<WorkOrderPowerStation> qu1 = new LambdaQueryWrapper();
		qu1.eq(WorkOrderPowerStation::getWorkOrderId, workOrderPowerStation.getWorkOrderId());
		List<String> d = new ArrayList<>();
		d.add(WorkOrderEnum.施工中.getCode());
		d.add(WorkOrderEnum.待施工.getCode());
		d.add(WorkOrderEnum.待登记.getCode());
		qu1.in(WorkOrderPowerStation::getPowerStationConstructionStatus, d);
		List<WorkOrderPowerStation> list = workOrderPowerStationMapper.selectList(qu1);
		LambdaUpdateWrapper<WorkOrder> upq = new LambdaUpdateWrapper();
		upq.eq(WorkOrder::getSequenceNbr, workOrderPowerStation.getWorkOrderId());
		if (list == null || list.isEmpty()) {
			upq.set(WorkOrder::getWorkOrderStatus, WorkOrderEnum.审核中.getCode());
			workOrderMapper.update(null, upq);
		}
		// 新增完工登记
		PowerStationEngineeringInfo powerStationEngineeringInfo = powerStationEngineeringInfoAllDto
				.getPowerStationEngineeringInfo();
		powerStationEngineeringInfo.setWorkOrderId(workOrderPowerStation.getWorkOrderId());
		powerStationEngineeringInfo
				.setWorkOrderPowerStationId(powerStationEngineeringInfoAllDto.getWorkOrderPowerStationId());
		// 防止重复提交
		LambdaQueryWrapper<PowerStationEngineeringInfo> pse = new LambdaQueryWrapper<>();
		pse.eq(PowerStationEngineeringInfo::getWorkOrderId, powerStationEngineeringInfo.getWorkOrderId());
		pse.eq(PowerStationEngineeringInfo::getWorkOrderPowerStationId,powerStationEngineeringInfo.getWorkOrderPowerStationId());
		// powerStationEngineeringInfoService.saveOrUpdate(powerStationEngineeringInfo);
		powerStationEngineeringInfoService.saveOrUpdate(powerStationEngineeringInfo, pse);
		// 增加操作日志
		ConstructionRecords da = new ConstructionRecords(powerStationEngineeringInfo.getRecUserName(), "完工登记",
				new Date(), "", workOrderPowerStation.getWorkOrderId(), workOrderPowerStation.getSequenceNbr(),
				workOrderPowerStation.getPeasantHouseholdId(), "");
		constructionRecordsServiceImpl.save(da);
		return powerStationEngineeringInfoAllDto;
	}

	public PowerStationEngineeringInfoAllDto getConstructionRecords(Long workOrderPowerStationId, String rename) {

		LambdaQueryWrapper<WorkOrderPowerStation> qu = new LambdaQueryWrapper();
		qu.eq(WorkOrderPowerStation::getSequenceNbr, workOrderPowerStationId);
		WorkOrderPowerStation workOrderPowerStation = workOrderPowerStationMapper.selectOne(qu);
		Long peasantHouseholdId = workOrderPowerStation.getPeasantHouseholdId();
		Long workOrderId = workOrderPowerStation.getWorkOrderId();
		PowerStationEngineeringInfoAllDto surveyInfoAllDto = new PowerStationEngineeringInfoAllDto();
		// 施工自审
		LambdaQueryWrapper<ConstructionRecords> up5 = new LambdaQueryWrapper();
		up5.eq(ConstructionRecords::getWorkOrderId, workOrderId);
		up5.eq(ConstructionRecords::getWorkOrderPowerStationId, workOrderPowerStationId);
		up5.orderByDesc(ConstructionRecords::getRecDate);
		List<ConstructionRecords> li = constructionRecordsMapper.selectList(up5);
		ConstructionRecords data = new ConstructionRecords();
		data.setConstructionRecordsList(li);
		data.setOperationTime(new Date());
		data.setOperator(rename);
		surveyInfoAllDto.setConstructionRecords(data);
		return surveyInfoAllDto;

	}

	@Transactional(rollbackFor = Exception.class)
	public synchronized ConstructionRecords addConstructionRecords(ConstructionRecords constructionRecords) {
        LambdaQueryWrapper<WorkOrderPowerStation> qu = new LambdaQueryWrapper();
        qu.eq(WorkOrderPowerStation::getSequenceNbr, constructionRecords.getWorkOrderPowerStationId());
        WorkOrderPowerStation workOrderPowerStation = workOrderPowerStationMapper.selectOne(qu);

		LambdaQueryWrapper<HygfWorkOrderStationAuditing> audit = new LambdaQueryWrapper();
		audit.eq(HygfWorkOrderStationAuditing::getWorkOrderPowerStationId, constructionRecords.getWorkOrderPowerStationId());
		audit.last("limit 1");
		HygfWorkOrderStationAuditing workOrderStationAuditing = hygfWorkOrderStationAuditingService.getBaseMapper().selectOne(audit);


        if (constructionRecords.getOperationResults().equals("通过")) {
            // 修改电站状态
            workOrderPowerStation.setPowerStationConstructionStatus(WorkOrderEnum.片区运营待审核.getName());
            workOrderPowerStation.setWorkOrderPowerStationNode(WorkOrderEnum.片区运营待审核.getCode());
			workOrderPowerStation.setPowerStationAreaStatus(null);
			workOrderPowerStation.setPowerStationDesignStatus(null);
			workOrderPowerStation.setPowerStationEngineeringStatus(null);
//            // 修改完工时间
//            LambdaUpdateWrapper<PowerStationEngineeringInfo> upq1 = new LambdaUpdateWrapper();
//            upq1.eq(PowerStationEngineeringInfo::getWorkOrderPowerStationId,
//                    workOrderPowerStation.getSequenceNbr());
//            upq1.set(PowerStationEngineeringInfo::getCompletionDate, new Date());
//            powerStationEngineeringInfoMapper.update(null, upq1);

//            BasicGridAcceptance dat = new BasicGridAcceptance();
//            dat.setWorkOrderId(workOrderPowerStation.getWorkOrderId());
//            dat.setWorkOrderPowerStationId(workOrderPowerStation.getSequenceNbr());
//            dat.setPeasantHouseholdId(workOrderPowerStation.getPeasantHouseholdId());
//            dat.setGridStatus("1");
//
////				// 新增并网记录
////				LambdaQueryWrapper<BasicGridAcceptance> bga = new LambdaQueryWrapper<>();
////				bga.eq(BasicGridAcceptance::getPeasantHouseholdId, workOrderPowerStation.getPeasantHouseholdId());
////				BasicGridAcceptance b = basicGridAcceptanceMapper.selectOne(bga);
////				// 防止重复增加
////				if (b == null) {
////					basicGridAcceptanceMapper.insert(dat);
////				}
//            basicGridAcceptanceService.saveOrUpdate(dat,new LambdaQueryWrapper<BasicGridAcceptance>().eq(BasicGridAcceptance::getPeasantHouseholdId,workOrderPowerStation.getPeasantHouseholdId()));

            workOrderPowerStationMapper.updateById(workOrderPowerStation);
//            // 修改派工单状态
//            LambdaQueryWrapper<WorkOrderPowerStation> qu1 = new LambdaQueryWrapper();
//            qu1.eq(WorkOrderPowerStation::getWorkOrderId, workOrderPowerStation.getWorkOrderId());
//            List<String> d = new ArrayList<>();
//            d.add(WorkOrderEnum.施工中.getCode());
//            d.add(WorkOrderEnum.待施工.getCode());
//            d.add(WorkOrderEnum.待登记.getCode());
//            d.add(WorkOrderEnum.待审核.getCode());
//            d.add(WorkOrderEnum.未通过.getCode());
//            qu1.in(WorkOrderPowerStation::getPowerStationConstructionStatus, d);
//            List<WorkOrderPowerStation> list = workOrderPowerStationMapper.selectList(qu1);
//            LambdaUpdateWrapper<WorkOrder> upq = new LambdaUpdateWrapper();
//            upq.eq(WorkOrder::getSequenceNbr, workOrderPowerStation.getWorkOrderId());
//            if (list == null || list.isEmpty()) {
//                upq.set(WorkOrder::getWorkOrderStatus, WorkOrderEnum.已完工.getCode());
//                workOrderMapper.update(null, upq);
//            }

        } else {
            // 修改电站状态
            workOrderPowerStation.setPowerStationConstructionStatus(WorkOrderEnum.未通过.getCode());
            workOrderPowerStationMapper.updateById(workOrderPowerStation);
            LambdaUpdateWrapper<WorkOrder> upq = new LambdaUpdateWrapper();
            upq.eq(WorkOrder::getSequenceNbr, workOrderPowerStation.getWorkOrderId());
            upq.set(WorkOrder::getWorkOrderStatus, WorkOrderEnum.未通过.getCode());
            workOrderMapper.update(null, upq);

			// 修改完工时间
			LambdaUpdateWrapper<PowerStationEngineeringInfo> upq1 = new LambdaUpdateWrapper();
			upq1.eq(PowerStationEngineeringInfo::getWorkOrderPowerStationId,
					workOrderPowerStation.getSequenceNbr());
			upq1.set(PowerStationEngineeringInfo::getCompletionDate, null);
			powerStationEngineeringInfoMapper.update(null, upq1);
        }
        //线上历史数据有部分因当时没流程 所以已跳过流程开启节点 允许没有流程的业务驳回
        if(!Objects.isNull(workOrderStationAuditing)){
			this.wofkflowExcute(workOrderStationAuditing.getInstanceId(),
					constructionRecords.getOperationResults().equals("通过")?"0":"1",
					constructionRecords.getOperationResults(),BusinessWorkflowKey.完工自审.getCode());
		}


        // 增加操作日志
        constructionRecords.setWorkOrderId(workOrderPowerStation.getWorkOrderId());
        constructionRecords.setOperationContent("完工自审-" + constructionRecords.getOperationResults());
        constructionRecords.setWorkOrderPowerStationId(workOrderPowerStation.getSequenceNbr());
        constructionRecords.setPeasantHouseholdId(workOrderPowerStation.getPeasantHouseholdId());
        constructionRecordsServiceImpl.save(constructionRecords);
		return constructionRecords;
	}


	public void completeAudit(Map<String,String> kv) {
		String powerStationId = kv.get("powerStationId");
		String comment = kv.get("comment");
		String status = kv.get("status");
		String approvalStatus = kv.get("approvalStatus");
		LambdaQueryWrapper<HygfWorkOrderStationAuditing> audit = new LambdaQueryWrapper();
		audit.eq(HygfWorkOrderStationAuditing::getWorkOrderPowerStationId, powerStationId);
		audit.last("limit 1");
		HygfWorkOrderStationAuditing workOrderStationAuditing = hygfWorkOrderStationAuditingService.getBaseMapper().selectOne(audit);

		String taskKey = "";

		LambdaQueryWrapper<WorkOrderPowerStation> qu = new LambdaQueryWrapper();
		qu.eq(WorkOrderPowerStation::getSequenceNbr, powerStationId);
		WorkOrderPowerStation workOrderPowerStation = workOrderPowerStationMapper.selectOne(qu);
		ConstructionRecords constructionRecords = new ConstructionRecords();
		switch (status){
			case "area":
				workOrderPowerStation.setPowerStationAreaStatus(approvalStatus.equals("0")?"通过":"驳回");
				constructionRecords.setOperationContent("施工验收-片区运营审核-" +workOrderPowerStation.getPowerStationAreaStatus());
				workOrderPowerStation.setWorkOrderPowerStationNode(WorkOrderEnum.工程待审核.getCode());
				workOrderPowerStation.setPowerStationConstructionStatus(WorkOrderEnum.工程待审核.getName());
				taskKey = BusinessWorkflowKey.片区运营审核.getCode();
				break;
			case "design":
				workOrderPowerStation.setPowerStationDesignStatus(approvalStatus.equals("0")?"通过":"驳回");
				constructionRecords.setOperationContent("施工验收-设计审核-" + workOrderPowerStation.getPowerStationDesignStatus());
				workOrderPowerStation.setPowerStationConstructionStatus(WorkOrderEnum.已完工.getCode());
				workOrderPowerStation.setSgEndTime(new Date());
				workOrderPowerStation.setWorkOrderPowerStationNode(WorkOrderEnum.全部节点.getCode());
				taskKey = BusinessWorkflowKey.设计审核.getCode();
				break;
			default:
				workOrderPowerStation.setPowerStationEngineeringStatus(approvalStatus.equals("0")?"通过":"驳回");
				constructionRecords.setOperationContent("施工验收-工程审核-" + workOrderPowerStation.getPowerStationEngineeringStatus());
				workOrderPowerStation.setPowerStationConstructionStatus(WorkOrderEnum.设计待审核.getName());
				workOrderPowerStation.setWorkOrderPowerStationNode(WorkOrderEnum.设计待审核.getCode());
				taskKey = BusinessWorkflowKey.工程审核.getCode();
				break;
		}
		this.wofkflowExcute(workOrderStationAuditing.getInstanceId(), approvalStatus , comment ,taskKey );
		//若驳回则修改施工场站状态为未通过 上述switch作通过状态的统一处理 且节点恢复为null
		if (approvalStatus.equals("1")){
			workOrderPowerStation.setPowerStationConstructionStatus(WorkOrderEnum.未通过.getCode());
			workOrderPowerStation.setWorkOrderPowerStationNode(null);
			//此处sql可以和updateById合并优化 后续处理
			LambdaUpdateWrapper<WorkOrderPowerStation> qqq = new LambdaUpdateWrapper();
			qqq.eq(BaseEntity::getSequenceNbr,workOrderPowerStation.getSequenceNbr());
			qqq.set(WorkOrderPowerStation::getWorkOrderPowerStationNode,null);
			workOrderPowerStationMapper.update(null,qqq);

			LambdaUpdateWrapper<WorkOrder> upq = new LambdaUpdateWrapper();
			upq.eq(WorkOrder::getSequenceNbr, workOrderPowerStation.getWorkOrderId());
			upq.set(WorkOrder::getWorkOrderStatus, WorkOrderEnum.未通过.getCode());
			workOrderMapper.update(null, upq);

		}

		// 增加操作日志
		constructionRecords.setOperationTime(new Date());
		constructionRecords.setOperator(kv.get("operator"));
		constructionRecords.setOperationResults(approvalStatus.equals("0")?"通过":"驳回");
		constructionRecords.setWorkOrderId(workOrderPowerStation.getWorkOrderId());
		constructionRecords.setWorkOrderPowerStationId(workOrderPowerStation.getSequenceNbr());
		constructionRecords.setPeasantHouseholdId(workOrderPowerStation.getPeasantHouseholdId());
		constructionRecords.setNotes(kv.get("comment"));
		constructionRecordsServiceImpl.save(constructionRecords);

		workOrderPowerStationMapper.updateById(workOrderPowerStation);

		if (status.equals("design") && approvalStatus.equals("0")){

			// 修改完工时间
			LambdaUpdateWrapper<PowerStationEngineeringInfo> upq1 = new LambdaUpdateWrapper();
			upq1.eq(PowerStationEngineeringInfo::getWorkOrderPowerStationId,
					workOrderPowerStation.getSequenceNbr());
			upq1.set(PowerStationEngineeringInfo::getCompletionDate, new Date());
			powerStationEngineeringInfoMapper.update(null, upq1);

			BasicGridRecord dat = new BasicGridRecord();
			dat.setWorkOrderId(workOrderPowerStation.getWorkOrderId());
			dat.setWorkOrderPowerStationId(workOrderPowerStation.getSequenceNbr());
			dat.setPeasantHouseholdId(workOrderPowerStation.getPeasantHouseholdId());
			dat.setGridStatus("1");

//				// 新增并网记录
//				LambdaQueryWrapper<BasicGridAcceptance> bga = new LambdaQueryWrapper<>();
//				bga.eq(BasicGridAcceptance::getPeasantHouseholdId, workOrderPowerStation.getPeasantHouseholdId());
//				BasicGridAcceptance b = basicGridAcceptanceMapper.selectOne(bga);
//				// 防止重复增加
//				if (b == null) {
//					basicGridAcceptanceMapper.insert(dat);
//				}
			basicGridRecordService.saveOrUpdate(dat,new LambdaQueryWrapper<BasicGridRecord>().eq(BasicGridRecord::getPeasantHouseholdId,workOrderPowerStation.getPeasantHouseholdId()));
			// 修改派工单状态
			LambdaQueryWrapper<WorkOrderPowerStation> qu1 = new LambdaQueryWrapper();
			qu1.eq(WorkOrderPowerStation::getWorkOrderId, workOrderPowerStation.getWorkOrderId());
			List<String> d = new ArrayList<>();
			d.add(WorkOrderEnum.施工中.getCode());
			d.add(WorkOrderEnum.待施工.getCode());
			d.add(WorkOrderEnum.待登记.getCode());
			d.add(WorkOrderEnum.待审核.getCode());
			d.add(WorkOrderEnum.片区运营待审核.getCode());
			d.add(WorkOrderEnum.工程待审核.getCode());
			d.add(WorkOrderEnum.设计待审核.getCode());
			d.add(WorkOrderEnum.未通过.getCode());
			qu1.in(WorkOrderPowerStation::getPowerStationConstructionStatus, d);
			List<WorkOrderPowerStation> list = workOrderPowerStationMapper.selectList(qu1);
			LambdaUpdateWrapper<WorkOrder> upq = new LambdaUpdateWrapper();
			upq.eq(WorkOrder::getSequenceNbr, workOrderPowerStation.getWorkOrderId());
			if (list == null || list.isEmpty()) {
				upq.set(WorkOrder::getWorkOrderStatus, WorkOrderEnum.已完工.getCode());
				workOrderMapper.update(null, upq);
			}


			// 施工完成
			LambdaUpdateWrapper<PeasantHousehold> up1 = new LambdaUpdateWrapper<>();
			up1.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.施工完成.getCode());
			if (null != workOrderPowerStation.getPeasantHouseholdId() && workOrderPowerStation.getPeasantHouseholdId().longValue() != 0L ){
				long idsk = workOrderPowerStation.getPeasantHouseholdId();
				up1.eq(PeasantHousehold::getSequenceNbr, idsk);
				peasantHouseholdMapper.update(null, up1);
			}
			//判断施工状态是否完成，完成的话新增并网待办
			if(WorkOrderEnum.已完工.getCode().equals(workOrderPowerStation.getPowerStationConstructionStatus())){
				//生成并网待办
				PeasantHousehold peasantHousehold = peasantHouseholdMapper.selectById(workOrderPowerStation.getPeasantHouseholdId());
				WorkOrderDto workOrderDto = queryBySeq(workOrderPowerStation.getWorkOrderId());
				RouthPathVO routhPathVO = new RouthPathVO();
				routhPathVO.setRouthPathId(String.valueOf(workOrderPowerStation.getPeasantHouseholdId()));
				String routhPath = toDoTasksService.getRouthPath(TaskTypeStationEnum.并网.getCode(), HygfRouthTypeEnum.HYGF_XZBWDJ.getCode(), routhPathVO);
				String wxRouthPath = toDoTasksService.getWxRouthPath(TaskTypeStationEnum.并网.getCode(), HygfRouthTypeEnum.HYGF_XZBWDJ.getCode(), routhPathVO);
				ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.并网.getCode(),  workOrderPowerStation.getPeasantHouseholdId(),   peasantHousehold.getOwnersName()+"待新增并网登记",workOrderDto.getRegionCode(),routhPath,wxRouthPath);
				List<String> todoUserIds = new ArrayList<>();
				todoUserIds.add(peasantHousehold.getDeveloperUserId());
				toDoTasksService.addToDoTasksByUserIds(todoUserIds,toDoTasks1);
			}
		}

	}



	public ResponseModel addRectification(HygfRectificationOrder hygfRectificationOrder) {
		rectificationOrderAuditingService.addRectification(hygfRectificationOrder);
		String addorSubmit = hygfRectificationOrder.getAddorSubmit();

		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 (addorSubmit.equals("0")){
			LambdaUpdateWrapper<WorkOrderPowerStation> qu = new LambdaUpdateWrapper();
			qu.eq(WorkOrderPowerStation::getPeasantHouseholdId, hygfRectificationOrder.getPeasantHouseholeId());
			qu.set(WorkOrderPowerStation::getPowerStationConstructionStatus,WorkOrderEnum.待整改.getCode());
			workOrderPowerStationMapper.update(null,qu);
		}

		return CommonResponseNewUtil.success();

	}


	public void nextTaskExcute(HygfRectificationOrder hygfRectificationOrder) {
		//修改电站状态
		LambdaUpdateWrapper<WorkOrderPowerStation> qu = new LambdaUpdateWrapper();
		qu.eq(WorkOrderPowerStation::getPeasantHouseholdId, hygfRectificationOrder.getPeasantHouseholeId());

		if (hygfRectificationOrder.getAddorSubmit().equals("0")) {
			qu.set(WorkOrderPowerStation::getPowerStationConstructionStatus,WorkOrderEnum.整改待审核.getCode());
			workOrderPowerStationMapper.update(null,qu);
			hygfRectificationOrder.setRectificationStatus(WorkOrderEnum.待审核.getCode());
		}else {
		//	qu.set(WorkOrderPowerStation::getPowerStationConstructionStatus,WorkOrderEnum.整改中.getCode());
			hygfRectificationOrder.setRectificationStatus(WorkOrderEnum.整改中.getCode());
		}
		rectificationOrderAuditingService.nextTaskExcute(hygfRectificationOrder);
	}

		public void nextTaskAduit(HygfRectificationOrder hygfRectificationOrder) {
		//修改电站状态
		LambdaUpdateWrapper<WorkOrderPowerStation> qu = new LambdaUpdateWrapper();
		qu.eq(WorkOrderPowerStation::getPeasantHouseholdId, hygfRectificationOrder.getPeasantHouseholeId());

		if (hygfRectificationOrder.getAuditResult().equals("通过")){
			qu.set(WorkOrderPowerStation::getPowerStationConstructionStatus,WorkOrderEnum.getNodeByCode(hygfRectificationOrder.getRectificationSource()).getName());
			hygfRectificationOrder.setRectificationStatus(WorkOrderEnum.已完成.getCode());
		}else {
			qu.set(WorkOrderPowerStation::getPowerStationConstructionStatus,WorkOrderEnum.待整改.getCode());
			hygfRectificationOrder.setRectificationStatus(WorkOrderEnum.待整改.getCode());
		}
		rectificationOrderAuditingService.nextTaskAduit(hygfRectificationOrder);
		workOrderPowerStationMapper.update(null,qu);
	}

	public void rollback(Long sequenceNbr) {
		HygfRectificationOrder hygfRectificationOrder = rectificationOrderService.getBaseMapper().selectById(sequenceNbr);
		if (hygfRectificationOrder.getRectificationStatus().equals(WorkOrderEnum.待提交.getCode()) ||
				hygfRectificationOrder.getRectificationStatus().equals(WorkOrderEnum.待整改.getCode())){
			rectificationOrderAuditingService.rollback(sequenceNbr);
		}else {
			throw new BadRequest("仅单据状态为待提交或待整改时方可作废");
		}
		//修改施工电站状态
		LambdaUpdateWrapper<WorkOrderPowerStation> qu = new LambdaUpdateWrapper();
		qu.eq(WorkOrderPowerStation::getPeasantHouseholdId, hygfRectificationOrder.getPeasantHouseholeId());
		qu.set(WorkOrderPowerStation::getPowerStationConstructionStatus,WorkOrderEnum.getNodeByCode(hygfRectificationOrder.getRectificationSource()).getName());
		workOrderPowerStationMapper.update(null,qu);


	}

	@Transactional(rollbackFor = Exception.class)
	public void updateDetail(PowerStationEngineeringInfoAllDto powerStationEngineeringInfoAllDto,String realName) {
		//更新施工信息
		PowerStationConstructionData powerStationConstructionData = powerStationEngineeringInfoAllDto.getPowerStationConstructionData();
		if(Objects.nonNull(powerStationConstructionData)){
			powerStationConstructionDataMapper.updateById(powerStationConstructionData);
		}
		//更新工程
		PowerStationEngineeringInfo powerStationEngineeringInfo = powerStationEngineeringInfoAllDto.getPowerStationEngineeringInfo();
		if(Objects.nonNull(powerStationEngineeringInfo)){
			powerStationEngineeringInfoMapper.updateById(powerStationEngineeringInfo);
			//更新施工组件信息
			LambdaUpdateWrapper<PowerStationConstructionData> powerStationConstructionDataWrapper = new LambdaUpdateWrapper<>();
			powerStationConstructionDataWrapper.set(PowerStationConstructionData::getConstructionComponentInfo, JSONArray.toJSONString(powerStationEngineeringInfo.getConstructionComponentInfo()));
			powerStationConstructionDataWrapper.set(PowerStationConstructionData::getConstructionInverterInfo,JSONArray.toJSONString(powerStationEngineeringInfo.getConstructionInverterInfo()));
			powerStationConstructionDataWrapper.set(PowerStationConstructionData::getConstructionCollectorBoxInfo,JSONArray.toJSONString(powerStationEngineeringInfo.getConstructionCollectorBoxInfo()));
			powerStationConstructionDataWrapper.set(PowerStationConstructionData::getConstructionGridBoxInfo,JSONArray.toJSONString(powerStationEngineeringInfo.getConstructionGridBoxInfo()));
			powerStationConstructionDataWrapper.eq(PowerStationConstructionData::getWorkOrderId, powerStationEngineeringInfo.getWorkOrderId());
			powerStationConstructionDataWrapper.eq(PowerStationConstructionData::getWorkOrderPowerStationId, powerStationEngineeringInfo.getWorkOrderPowerStationId());
			powerStationConstructionDataMapper.update(null,powerStationConstructionDataWrapper);
            //更新工程负责人
			LambdaUpdateWrapper<WorkOrder> upl = new LambdaUpdateWrapper();
			upl.set(WorkOrder::getProjectRegionManager, powerStationEngineeringInfo.getProjectRegionManager());
			upl.set(WorkOrder::getProjectRegionManagerPhone, powerStationEngineeringInfo.getProjectRegionManagerPhone());
			upl.set(WorkOrder::getConstructionRegionManager, powerStationEngineeringInfo.getConstructionRegionManager());
			upl.set(WorkOrder::getConstructionRegionManagerPhone, powerStationEngineeringInfo.getConstructionRegionManagerPhone());
			upl.eq(WorkOrder::getSequenceNbr, powerStationEngineeringInfo.getWorkOrderId());
			workOrderMapper.update(null,upl);
		}
		//更新并网信息
		HygfOnGrid hygfOnGrid = powerStationEngineeringInfoAllDto.getHygfOnGrid();
		if(Objects.nonNull(hygfOnGrid)){
			hygfOnGridMapper.updateById(hygfOnGrid);
		}
		//更新设计信息
		DesignInformationDto designInformation = powerStationEngineeringInfoAllDto.getDesignInformation();
		if(Objects.nonNull(designInformation)){
			designInformationService.updateWithModel(designInformation);
		}
		//更新商务信息
		CommercialDto commercial = powerStationEngineeringInfoAllDto.getCommercial();
		if(Objects.nonNull(commercial)){
			commercialService.updateWithModel(commercial);
		}

		if(Objects.isNull(powerStationEngineeringInfoAllDto.getCommitFlag())){
			throw new BadRequest("保存标识为空");
		}

		if(Objects.isNull(powerStationEngineeringInfoAllDto.getFlowType())){
			throw new BadRequest("流程标识为空");
		}

		//提交
		if(powerStationEngineeringInfoAllDto.getCommitFlag() == 1){
			//提交并网
			if(Objects.nonNull(hygfOnGrid) && powerStationEngineeringInfoAllDto.getFlowType() == 0) {
				hygfOnGrid.setType("1");
				basicGridAcceptanceService.saveAndCommit(hygfOnGrid,realName);
			}
			//提交验收
			AcceptanceCheck acceptanceCheck = powerStationEngineeringInfoAllDto.getAcceptanceCheck();
			if(powerStationEngineeringInfoAllDto.getFlowType() == 1 && Objects.nonNull(acceptanceCheck)) {
				Map<String,Object> model =new HashMap<>();
				if(acceptanceCheck.getInstanceId() == null) {
					model.put("type", "0");
				}else {
					model.put("type","1");
				}

				model.put("sequenceNbr",acceptanceCheck.getSequenceNbr());
				model.put("realName",realName);
				acceptanceCheckService.saveAndCommit(model);
			}
		}
	}



	public PowerStationEngineeringInfoAllDto getPowerStationEngineeringInfoHistory(Long peasantHouseholdId ,
																				   String processInstanceId) {


		PowerStationEngineeringInfoAllDto surveyInfoAllDto = new PowerStationEngineeringInfoAllDto();
		PeasantHousehold peasantHousehold = new PeasantHousehold();

		LambdaQueryWrapper<PeasantHousehold> peasantHouseholdWrapper = new LambdaQueryWrapper<>();
		peasantHouseholdWrapper.eq(PeasantHousehold::getSequenceNbr, peasantHouseholdId);
		peasantHousehold = peasantHouseholdServiceImpl.getBaseMapper().selectOne(peasantHouseholdWrapper);
		String surveyInformationId = String.valueOf(peasantHousehold.getSurveyInformationId());

		// 勘察基本信息
		LambdaQueryWrapper<SurveyInformation> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(SurveyInformation::getSequenceNbr, surveyInformationId);
		SurveyInformation surveyInformation = surveyInformationMapper.selectOne(queryWrapper);
		SurveyInformationDto surveyInformationDto = BeanDtoUtils.convert(surveyInformation, SurveyInformationDto.class);
		surveyInformationDto.setPeasantHouseholdId(peasantHousehold.getSequenceNbr());
		surveyInfoAllDto.setSurveyInformation(surveyInformationDto);
		// 农户信息

		// 获取用户所在经销商单位

		LambdaQueryWrapper<UnitInfo> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(UnitInfo::getAmosCompanySeq,peasantHousehold.getDeveloperId());
		UnitInfo unitInfo = unitInfoService.getBaseMapper().selectOne(wrapper);


		BeanUtils.copyProperties(peasantHousehold, surveyInfoAllDto.getSurveyInformation());
		surveyInfoAllDto.getSurveyInformation().setDeveloperName(peasantHousehold.getDeveloperName());
		surveyInfoAllDto.getSurveyInformation().setDeveloperCode(peasantHousehold.getDeveloperCode());
		surveyInfoAllDto.getSurveyInformation().setDeveloperId(unitInfo.getSequenceNbr());

		if (!StringUtils.isEmpty(peasantHousehold.getProjectAddressName())) {
			surveyInfoAllDto.getSurveyInformation()
					.setProjectAddressText(Arrays.asList(peasantHousehold.getProjectAddressName().split("/")));
		}
		if (!StringUtils.isEmpty(peasantHousehold.getPermanentAddressName())) {
			surveyInfoAllDto.getSurveyInformation()
					.setPermanentAddressText(Arrays.asList(peasantHousehold.getPermanentAddressName().split("/")));
		}
		if (peasantHousehold.getPermanentAddress() == null) {
			surveyInfoAllDto.getSurveyInformation().setPermanentAddress(peasantHousehold.getProjectAddress());
			surveyInfoAllDto.getSurveyInformation().setIsPermanent("1");
		}
		surveyInfoAllDto.getSurveyInformation().setSequenceNbr(surveyInformation.getSequenceNbr());
		QueryWrapper<SurveyDetails> surveyDetailsQueryWrapper = new QueryWrapper<>();
		surveyDetailsQueryWrapper.eq("survey_information_id", surveyInformationId);
		SurveyDetails surveyDetails = surveyDetailsService.getBaseMapper().selectOne(surveyDetailsQueryWrapper);

		if (surveyDetails == null) {
			surveyInfoAllDto.setSurveyDetails(new SurveyDetailsDto());
		} else {
			surveyInfoAllDto.setSurveyDetails(BeanDtoUtils.convert(surveyDetails, SurveyDetailsDto.class));
		}

//        商务信息
		QueryWrapper<Commercial> commercialQueryWrapper = new QueryWrapper<>();
		commercialQueryWrapper.eq("survey_information_id", surveyInformationId);
		Commercial commercial = commercialService.getBaseMapper().selectOne(commercialQueryWrapper);
		if (commercial == null) {
			commercial = new Commercial();
		}

		commercial.setApplicant(peasantHousehold.getOwnersName());
		commercial.setIdCard(peasantHousehold.getIdCard());
		commercial.setTelephone(peasantHousehold.getTelephone());
		commercial.setProjectAddress(peasantHousehold.getProjectAddress());
		commercial.setProjectAddressName(peasantHousehold.getProjectAddressName());
		commercial.setProjectAddressDetail(peasantHousehold.getProjectAddressDetail());
		commercial.setLegalContactTelephone(peasantHousehold.getTelephone());


		List<Object> list = new ArrayList<>();
		if (null != surveyDetails) {
			if (CollectionUtil.isNotEmpty(surveyDetails.getSurroundingHouseSurvey())) {
				list.addAll(surveyDetails.getSurroundingHouseSurvey());
			}
			if (CollectionUtil.isNotEmpty(surveyDetails.getOverallHousingSurvey())) {
				list.addAll(surveyDetails.getOverallHousingSurvey());
			}
			if (CollectionUtil.isNotEmpty(surveyDetails.getPanoramaSurvey())) {
				list.addAll(surveyDetails.getPanoramaSurvey());
			}
			if (CollectionUtil.isNotEmpty(surveyDetails.getPlanSketchSurvey())) {
				list.addAll(surveyDetails.getPlanSketchSurvey());
			}
			if (CollectionUtil.isNotEmpty(surveyDetails.getAzimuthSurvey())) {
				list.addAll(surveyDetails.getAzimuthSurvey());
			}
		}
		commercial.setSurveyPhotosWeb(list);
//        资料归档
		QueryWrapper<Information> informationQueryWrapper = new QueryWrapper<>();
		informationQueryWrapper.eq("survey_information_id", surveyInformationId);
		Information information = informationService.getBaseMapper().selectOne(informationQueryWrapper);
		if (information == null) {
			surveyInfoAllDto.setInformation(new InformationDto());
		} else {
			// 将商务信息的房产证明文件数据赋值给资料归档的房产证明文件
			information.setCardFile(commercial.getIdCardCredit());
			surveyInfoAllDto.setInformation(BeanDtoUtils.convert(information, InformationDto.class));
		}

		if (information == null) {
			CommercialDto commercialDto = BeanDtoUtils.convert(commercial, CommercialDto.class);
			commercialDto.setType("zrr");
			commercialDto.setLegalType("zjdnhw");
			surveyInfoAllDto.setCommercial(commercialDto);
		} else {
			surveyInfoAllDto.setCommercial(BeanDtoUtils.convert(commercial, CommercialDto.class));
			if (commercial != null && !StringUtils.isEmpty(commercial.getProjectAddressName())) {
				surveyInfoAllDto.getCommercial()
						.setProjectAddressText(Arrays.asList(commercial.getProjectAddressName().split("/")));
			}
		}
		QueryWrapper<ExtendedInformation> extendedInformationQueryWrapper = new QueryWrapper<>();
		extendedInformationQueryWrapper.eq("survey_information_id", surveyInformationId);
		ExtendedInformation extendedInformation = extendedInformationService.getBaseMapper()
				.selectOne(extendedInformationQueryWrapper);
		if (information == null) {
			surveyInfoAllDto.setExtendedInformation(new ExtendedInformationDto());
		} else {
			surveyInfoAllDto
					.setExtendedInformation(BeanDtoUtils.convert(extendedInformation, ExtendedInformationDto.class));
		}
		QueryWrapper<DesignInformation> designInformationQueryWrapper = new QueryWrapper<>();
		designInformationQueryWrapper.eq("peasant_household_id", peasantHousehold.getSequenceNbr());
		DesignInformation designInformation = designInformationService.getBaseMapper()
				.selectOne(designInformationQueryWrapper);
		if (designInformation == null) {
			surveyInfoAllDto.setDesignInformation(new DesignInformationDto());
		} else {
			surveyInfoAllDto.setDesignInformation(BeanDtoUtils.convert(designInformation, DesignInformationDto.class));
		}


		// 施工信息
		LambdaQueryWrapper<PowerStationConstructionData> up2 = new LambdaQueryWrapper();
		up2.eq(PowerStationConstructionData::getWorkOrderPowerStationId, peasantHouseholdId);
		PowerStationConstructionData powerStationConstructionData = powerStationConstructionDataMapper.selectOne(up2);



		// 工程信息

		LambdaQueryWrapper<PowerStationEngineeringInfo> up3 = new LambdaQueryWrapper();
		up3.eq(PowerStationEngineeringInfo::getWorkOrderPowerStationId, peasantHouseholdId);
		PowerStationEngineeringInfo powerStationEngineeringInfo = powerStationEngineeringInfoMapper.selectOne(up3);
		if (powerStationConstructionData != null) {
			powerStationEngineeringInfo = powerStationEngineeringInfo != null ? powerStationEngineeringInfo
					: new PowerStationEngineeringInfo();
			powerStationEngineeringInfo
					.setConstructionComponentInfo(powerStationConstructionData.getConstructionComponentInfo());
			powerStationEngineeringInfo
					.setConstructionInverterInfo(powerStationConstructionData.getConstructionInverterInfo());
			powerStationEngineeringInfo
					.setConstructionCollectorBoxInfo(powerStationConstructionData.getConstructionCollectorBoxInfo());
			powerStationEngineeringInfo
					.setConstructionGridBoxInfo(powerStationConstructionData.getConstructionGridBoxInfo());
		}
		// 并网信息
		LambdaQueryWrapper<HygfOnGrid> up4 = new LambdaQueryWrapper<HygfOnGrid>();
		up4.eq(HygfOnGrid::getPeasantHouseholdId, peasantHouseholdId);
		HygfOnGrid hygfOnGrid = hygfOnGridMapper.selectOne(up4);

		surveyInfoAllDto.setHygfOnGrid(hygfOnGrid != null ? hygfOnGrid : new HygfOnGrid());
		surveyInfoAllDto.setPowerStationConstructionData(powerStationConstructionData);
		surveyInfoAllDto.setPowerStationEngineeringInfo(powerStationEngineeringInfo);

		if (!StringUtils.isEmpty(processInstanceId)) {
			try {
				Map<String, Object> flowLoggerMap = workflowFeignClient.getFlowLogger(processInstanceId).getResult();
				List<LinkedHashMap> flowLogger = (List<LinkedHashMap>) flowLoggerMap.get("flowLogger");
				if (flowLogger.size() > 0) {
					Collections.reverse(flowLogger);
				}
				List<LinkedHashMap> flowLoggernew = new ArrayList<>();
				for (LinkedHashMap linkedHashMap : flowLogger) {
					if (linkedHashMap.get("operateDate") != null
							&& !linkedHashMap.get("operateDate").toString().isEmpty()) {
						LinkedHashMap linke = new LinkedHashMap();
						linke.put("approvalStatue", linkedHashMap.get("approvalStatue").toString());
						// 审核意见
						List<LinkedHashMap> approvalSuggestion = (List<LinkedHashMap>) linkedHashMap
								.get("approvalSuggestion");
						if (approvalSuggestion != null && !approvalSuggestion.isEmpty()) {
							linke.put("approvalSuggestion", approvalSuggestion.get(0).get("message"));
						}
						linke.put("taskName", linkedHashMap.get("taskName").toString());
						linke.put("operator", linkedHashMap.get("operator").toString());
						linke.put("operateDate", linkedHashMap.get("operateDate").toString());
						flowLoggernew.add(linke);
					}
				}
				LoggerDto loggerDto = new LoggerDto();
				loggerDto.setLogger(flowLoggernew);
				surveyInfoAllDto.setOrderTracking(loggerDto);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}


		return surveyInfoAllDto;
	}
}