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

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
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.yeejoin.amos.boot.biz.common.utils.RedisUtils;
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.fegin.IdxFeginService;
import com.yeejoin.amos.boot.module.hygf.api.mapper.*;
import com.yeejoin.amos.boot.module.hygf.api.service.IPowerStationService;
import com.yeejoin.amos.boot.module.hygf.api.service.ISurveyInformationService;
import com.yeejoin.amos.boot.module.hygf.api.util.BeanDtoUtils;
import com.yeejoin.amos.boot.module.hygf.api.util.NumberUtil;
import com.yeejoin.amos.boot.module.hygf.api.util.RedisLockUtil;
import com.yeejoin.amos.boot.module.hygf.biz.feign.WorkflowFeignClient;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

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

/**
 * 勘察信息服务实现类
 *
 * @author system_generator
 * @date 2023-07-07
 */
@Service
@Slf4j
public class SurveyInformationServiceImpl
		extends BaseService<SurveyInformationDto, SurveyInformation, SurveyInformationMapper>
		implements ISurveyInformationService {

	@Autowired
	SurveyDetailsServiceImpl surveyDetailsService;

	@Autowired
	InformationServiceImpl informationService;

	@Autowired
	ExtendedInformationServiceImpl extendedInformationService;

	@Autowired
	CommercialServiceImpl commercialService;

	@Autowired
	PeasantHouseholdServiceImpl peasantHouseholdServiceImpl;

	@Autowired
	DesignInformationServiceImpl designInformationService;

	@Autowired
	WorkflowFeignClient workflowFeignClient;

	@Autowired
	RedisUtils redisUtils;

	@Autowired
	IdxFeginService idxFeginService;
	@Autowired
	RegionalCompaniesMapper regionalCompaniesMapper;
	@Autowired
	IPowerStationService powerStationService;
	@Autowired
	PowerStationMapper powerStationMapper;
	@Autowired
	ToDoTasksServiceImpl toDoTasksService;
	@Autowired
	UserMessageMapper userMessageMapper;
	@Value("${power.station.examine.pageId}")
	private long pageId;
	@Autowired
	protected EmqKeeper emqKeeper;
	@Value("${power.station.examine.planId}")
	private String planId;

	private static final String regionRedis = "app_region_redis";
	private static final String OPERATION_TYPE_SUBMIT = "submit";
	private static final String OPERATION_TYPE_APPLY = "apply";
	private static final String IDX_REQUEST_STATE = "200";
	@Autowired
	PersonnelBusinessMapper personnelBusinessMapper;
	@Autowired
	PeasantHouseholdMapper peasantHouseholdMapper;

	@Autowired
	WorkOrderMapper workOrderMapper;
	@Autowired
	HygfOnGridMapper hygfOnGridMapper;
	@Autowired
	ConstructionRecordsServiceImpl constructionRecordsServiceImpl;
	@Autowired
	ConstructionRecordsMapper constructionRecordsMapper;
	@Autowired
	BasicGridAcceptanceMapper basicGridAcceptanceMapper;

	@Autowired
	SurveyInformationMapper surveyInformationMapper;
	@Autowired
	PowerStationConstructionDataMapper powerStationConstructionDataMapper;
	@Autowired
	PowerStationEngineeringInfoMapper powerStationEngineeringInfoMapper;
	@Autowired
	WorkOrderPowerStationMapper workOrderPowerStationMapper;
	@Autowired
	AmosRequestContext requestContext;
	@Resource(type = RedisLockUtil.class)
	private RedisLockUtil redisLockUtil;
    //    @Autowired
//    WorkflowImpl workflow;
	@Autowired
	WorkFlowService workFlowService;

	@Autowired
	HygfRectificationOrderServiceImpl rectificationOrderService;
	private static final String PROCESSKEY = "ProcessEngineering";

	@Autowired
	AcceptanceCheckMapper acceptanceCheckMapper;
	/**
	 * 分页查询
	 */
	public Page<SurveyInformationDto> queryForSurveyInformationPage(Page<SurveyInformationDto> page) {
		return this.queryForPage(page, "rec_date", false);
	}

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

	@Transactional
	public SurveyInfoAllDto saveSurveyInfo(SurveyInfoAllDto surveyInfoAllDto, String operationType) {
		String lockName = null;
		try {

			JSONArray regionName = getRegionName();
			List<RegionModel> list = JSONArray.parseArray(regionName.toJSONString(), RegionModel.class);


			// 更新勘察基本信息
			SurveyInformation surveyInformation = BeanDtoUtils.convert(surveyInfoAllDto.getSurveyInformation(),
					SurveyInformation.class);

			lockName = String.format("LockName:saveSurveyInfo:%s", surveyInformation.getSequenceNbr());
			Boolean isLocked = redisLockUtil.tryLock(lockName, lockName, 10, 1);
			if (BooleanUtils.isNotTrue(isLocked)) {
				throw new BadRequest("其他用户正在操作，请刷新后再试！");
			}

			QueryWrapper<PeasantHousehold> peasantHouseholdQueryWrapper = new QueryWrapper<>();
			peasantHouseholdQueryWrapper.eq("survey_information_id", surveyInformation.getSequenceNbr());
			PeasantHousehold peasantHousehold = peasantHouseholdServiceImpl.getBaseMapper()
					.selectOne(peasantHouseholdQueryWrapper);

			PowerStation powerStation = powerStationMapper.selectOne(new LambdaQueryWrapper<PowerStation>()
					.eq(PowerStation::getPeasantHouseholdId, peasantHousehold.getSequenceNbr()));
			if (ArrivalStateeEnum.勘察中.getCode().equals(peasantHousehold.getConstructionState())) {
				// 驳回后重新提交是勘察中->勘察中导致此逻辑有问题,所以去掉这种情况
				if (powerStation != null
						&& PowerStationProcessStateEnum.不通过.getName().equals(powerStation.getProcessStatus())) {

				} else {
					throw new BadRequest("此数据已被其他人操作，请返回重新刷新！");
				}

			}

			surveyInformation.setReview(0);
			if (OPERATION_TYPE_APPLY.equals(operationType) && null == surveyInformation.getCreatorTime()) {
				surveyInformation.setCreatorTime(new Date());
			}
			this.saveOrUpdate(surveyInformation);

			// 更新扩展信息
			ExtendedInformation extendedInformation = BeanDtoUtils.convert(surveyInfoAllDto.getExtendedInformation(),
					ExtendedInformation.class);
			extendedInformation.setSurveyInformationId(surveyInformation.getSequenceNbr());
			// 避免生成多份数据
			extendedInformationService.saveOrUpdate(extendedInformation, new LambdaQueryWrapper<ExtendedInformation>()
					.eq(ExtendedInformation::getSurveyInformationId, surveyInformation.getSequenceNbr()));
			// extendedInformationService.saveOrUpdate(extendedInformation);

			// 更新勘察明细信息
			SurveyDetailsDto oldSurveyDetails = surveyInfoAllDto.getSurveyDetails();
			SurveyDetails surveyDetails = BeanDtoUtils.convert(oldSurveyDetails, SurveyDetails.class);
			surveyDetails.setSurveyInformationId(surveyInformation.getSequenceNbr());
			// 避免生成多份数据
			surveyDetailsService.saveOrUpdate(surveyDetails, new LambdaQueryWrapper<SurveyDetails>()
					.eq(SurveyDetails::getSurveyInformationId, surveyInformation.getSequenceNbr()));
			// surveyDetailsService.saveOrUpdate(surveyDetails);

			// 更新商务信息
			CommercialDto oldCommercial = surveyInfoAllDto.getCommercial();
			Commercial commercial = BeanDtoUtils.convert(oldCommercial, Commercial.class);
			// 处理省市县
			String paddressName = "";
			for (Integer reg : surveyInfoAllDto.getSurveyInformation().getProjectAddress()) {
				for (RegionModel re : list) {
					if (re.getRegionCode().equals(Integer.valueOf(reg))) {
						paddressName = paddressName + re.getRegionName() + "/";
					}
				}
			}
			commercial.setProjectAddressName(paddressName.substring(0, paddressName.length() - 1));
			commercial.setSurveyInformationId(surveyInformation.getSequenceNbr());
			// 避免生成多份数据
			commercialService.saveOrUpdate(commercial, new LambdaQueryWrapper<Commercial>()
					.eq(Commercial::getSurveyInformationId, surveyInformation.getSequenceNbr()));
			// commercialService.saveOrUpdate(commercial);
			// 勘察后，更新状态
			// QueryWrapper<PeasantHousehold> peasantHouseholdQueryWrapper = new
			// QueryWrapper<>();
			// peasantHouseholdQueryWrapper.eq("survey_information_id",
			// surveyInformation.getSequenceNbr());
			// PeasantHousehold peasantHousehold =
			// peasantHouseholdServiceImpl.getBaseMapper()
			// .selectOne(peasantHouseholdQueryWrapper);

			// 更新资料归档信息
			Information information = BeanDtoUtils.convert(surveyInfoAllDto.getInformation(), Information.class);
			information.setHouseProve(null == commercial ? null
					: (CollectionUtil.isNotEmpty(commercial.getRealEstateLegal()) ? commercial.getRealEstateLegal()
							: null));
			information.setCardFile(null == commercial ? null
					: (CollectionUtil.isNotEmpty(commercial.getIdCardCredit()) ? commercial.getIdCardCredit() : null));
			information.setCardFile(commercial.getAgentLegal());
			information
					.setArchivesNumber(this.getNo(CodeEnum.档案.getCode(), peasantHousehold.getRegionalCompaniesSeq()));
			information.setFileNumber(this.getNo(CodeEnum.文件.getCode(), peasantHousehold.getRegionalCompaniesSeq()));
			information.setSurveyInformationId(surveyInformation.getSequenceNbr());

			// 避免生成多份数据
			informationService.saveOrUpdate(information, new LambdaQueryWrapper<Information>()
					.eq(Information::getSurveyInformationId, surveyInformation.getSequenceNbr()));
			// informationService.saveOrUpdate(information);

			peasantHousehold.setOwnersName(surveyInfoAllDto.getSurveyInformation().getOwnersName());
			peasantHousehold.setTelephone(surveyInfoAllDto.getSurveyInformation().getTelephone());
			peasantHousehold.setIdCard(surveyInfoAllDto.getSurveyInformation().getIdCard());
			peasantHousehold.setMailbox(surveyInfoAllDto.getSurveyInformation().getMailbox());
			peasantHousehold.setProjectAddress(surveyInfoAllDto.getSurveyInformation().getProjectAddress());
			peasantHousehold.setProjectAddressDetail(surveyInfoAllDto.getSurveyInformation().getProjectAddressDetail() != null ? surveyInfoAllDto.getSurveyInformation().getProjectAddressDetail(): "" );
			peasantHousehold.setPermanentAddress(surveyInfoAllDto.getSurveyInformation().getPermanentAddress());
			peasantHousehold
					.setPermanentAddressDetail(surveyInfoAllDto.getSurveyInformation().getPermanentAddressDetail() != null ? surveyInfoAllDto.getSurveyInformation().getPermanentAddressDetail() : "");
//			peasantHousehold
//					.setPermanentAddressDetail(surveyInfoAllDto.getSurveyInformation().getPermanentAddressDetail() != null ? surveyInfoAllDto.getSurveyInformation().getPermanentAddressDetail(): "");

			// 处理项目地址
			String projectAddressName = "";
			for (Integer reg : surveyInfoAllDto.getSurveyInformation().getProjectAddress()) {
				for (RegionModel re : list) {
					if (re.getRegionCode().equals(Integer.valueOf(reg))) {
						projectAddressName = projectAddressName + re.getRegionName() + "/";
					}
				}
			}
			peasantHousehold.setProjectAddressName(projectAddressName.substring(0, projectAddressName.length() - 1));
			// 常住地址
			String permanentAddressName = "";
			for (Integer reg : surveyInfoAllDto.getSurveyInformation().getPermanentAddress()) {
				for (RegionModel re : list) {
					if (re.getRegionCode().equals(Integer.valueOf(reg))) {
						permanentAddressName = permanentAddressName + re.getRegionName() + "/";
					}
				}
			}
			peasantHousehold
					.setPermanentAddressName(permanentAddressName.substring(0, permanentAddressName.length() - 1));


			if (OPERATION_TYPE_SUBMIT.equals(operationType)) {
				// peasantHousehold.setSurveyOrNot(1);
			} else if (OPERATION_TYPE_APPLY.equals(operationType)) {
				// 提交审核
				ToDoTasks toDoTasks = new ToDoTasks(TaskTypeStationEnum.勘察.getCode(), peasantHousehold.getSequenceNbr());
				toDoTasksService.completeToDoTasks(toDoTasks,"");
				submitExamine(peasantHousehold);
			}
			peasantHouseholdServiceImpl.saveOrUpdate(peasantHousehold);

		} catch (BadRequest e1) {
			throw e1;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (StringUtils.isNotEmpty(lockName)) {
				redisLockUtil.releaseLock(lockName);
			}
		}

		return surveyInfoAllDto;
	}

	public String getNo(String type, Long sequenceNbr) {
		RegionalCompanies da = regionalCompaniesMapper.selectRegionName(sequenceNbr);
		if (da.getCompanyCode() == null || da.getCompanyCode().isEmpty()) {
			throw new BadRequest("区域公司编号为空, 请设置编号");
		}
		if (da.getRegionalAddress() == null || da.getRegionalAddress().isEmpty()) {
			throw new BadRequest("区域公司省市区为空, 请设置省市区");
		}
		String code = NumberUtil.getCode(type, da.getCompanyCode(), da.getRegionalAddress());
		return code;
	}

//    private void updateSurveyInformationTask(PowerStation powerStation, String instanceId) {
//        Map<String, Object> updateTaskParam = new HashMap<>();
//        updateTaskParam.put("flowStatus", FlowStatusEnum.TO_BE_FINISHED.getCode());
//        updateTaskParam.put("flowStatusLabel", FlowStatusEnum.TO_BE_FINISHED.getName());
//        updateTaskParam.put("taskStatus", FlowStatusEnum.TO_BE_FINISHED.getCode());
//        updateTaskParam.put("taskStatusLabel", FlowStatusEnum.TO_BE_FINISHED.getName());
//        updateTaskParam.put("model", powerStation);
//        updateTaskParam.put("relationId", instanceId);
//        commonService.updateTaskModel(updateTaskParam);
//    }

	private void submitExamine(PeasantHousehold peasantHousehold) {

		PowerStation powerStation = powerStationService.getObjByNhId(String.valueOf(peasantHousehold.getSequenceNbr()),
				PowerStationProcessStateEnum.作废.getCode());

		String taskId = null;
		Map<String, Object> objectMap = new HashMap<>(1);
		objectMap.put("describe", "经销商已上传信息");

		// 保存并审核
		try {

			BasicGridAcceptance basicGridAcceptance = new BasicGridAcceptance();
            List<ProcessTaskDTO> processTaskDTOS = new ArrayList();
            if (ObjectUtils.isNotEmpty(powerStation)) {
                // 工作流执行一步
                // taskId = powerStation.getTaskId();
//                StandardDto standardDto = new StandardDto();
//                standardDto.setResult("0");
//                standardDto.setTaskId(powerStation.getFlowTaskId());
//                VariableDto variable = new VariableDto();
//                variable.setApprovalStatus("0");
//                standardDto.setVariable(variable);
//                workflow.standard(basicGridAcceptance, standardDto, requestContext.getUserId());
                //执行流程
                TaskResultDTO taskResultDTO = new TaskResultDTO();
                taskResultDTO.setResult("0");
                taskResultDTO.setTaskId(powerStation.getFlowTaskId());
                HashMap<String, Object> variableMap = new HashMap<>();
                variableMap.put("approvalStatus", "0");
                taskResultDTO.setVariable(variableMap);
                ProcessTaskDTO processTaskDTO = workFlowService.standard(basicGridAcceptance, taskResultDTO, requestContext.getUserId());

                basicGridAcceptance.setInstanceId(powerStation.getProcessInstanceId());
//                updateSurveyInformationTask(powerStation, powerStation.getProcessInstanceId());
                processTaskDTOS.add(processTaskDTO);
            } else {
                // 第一步启动工作流
                // 发起工作流
                // 调用工作流执行第一个节点
//                ProcessDto processDto = new ProcessDto();
//                processDto.setBusinessKey(String.valueOf(peasantHousehold.getSequenceNbr()));
//                processDto.setProcessDefinitionKey("hygf_10001");
//                StartProcessDto startProcessDto = new StartProcessDto();
//                List<ProcessDto> process = new ArrayList<>();
//                process.add(processDto);
//                startProcessDto.setProcess(process);
//                workflow.startProcess(basicGridAcceptance, startProcessDto, requestContext.getUserId());

                //开启工作流 并执行一步
                ActWorkflowBatchDTO actWorkflowBatchDTO = new ActWorkflowBatchDTO();
                List<ActWorkflowStartDTO> list = new ArrayList<>();
                ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
                dto.setProcessDefinitionKey(BusinessTypeEnum.HYGF_DZ_SH.getCode());
                dto.setBusinessKey(String.valueOf(peasantHousehold.getSequenceNbr()));
                dto.setCompleteFirstTask(true);
                list.add(dto);
                actWorkflowBatchDTO.setProcess(list);
                processTaskDTOS = workFlowService.startBatch(actWorkflowBatchDTO);
                basicGridAcceptance = workFlowService.getBasicGridAcceptance(basicGridAcceptance, processTaskDTOS, requestContext.getUserId());
                powerStation = new PowerStation();
            }
			peasantHousehold.setSurveyOrNot(2);
			peasantHousehold.setReview(1);
			// 插入记录表
			powerStation.setPlanInstanceId(planId);
			powerStation.setPowerStationCode(peasantHousehold.getPeasantHouseholdNo());
			powerStation.setOwnersName(peasantHousehold.getOwnersName());
			powerStation.setProjectAddress(peasantHousehold.getProjectAddressName());
			powerStation.setPeasantHouseholdId(String.valueOf(peasantHousehold.getSequenceNbr()));
			powerStation.setProcessStatus(PowerStationProcessStateEnum.设计待审核.getName());
			powerStation.setServiceAgent(peasantHousehold.getDeveloperName());
			// 获取流程信息
			powerStation.setTaskId(basicGridAcceptance.getNextTaskId());
			powerStation.setProcessInstanceId(basicGridAcceptance.getInstanceId());
			powerStation.setFlowTaskId(basicGridAcceptance.getNextTaskId());
			powerStation.setNodeRole(basicGridAcceptance.getNextExecutorIds());
			powerStation.setNodeRouting(PowerStationEnum.getNodeByKey(basicGridAcceptance.getNextNodeKey()));
			powerStation.setNextProcessNode(PowerStationNodeEnum.设计审核.getCode());
			powerStation.setPromoter(basicGridAcceptance.getPromoter());
			powerStation.setNextExecuteUserIds(basicGridAcceptance.getNextExecuteUserIds());
			powerStation.setNextNodeName(basicGridAcceptance.getNextNodeName());
			powerStation.setTechnologyStatus("");
			powerStation.setDesignStatus("");
			powerStation.setBusinessStatus("");
			SurveyInformation surveyInformation = this.baseMapper.selectById(peasantHousehold.getSurveyInformationId());
			if(Objects.nonNull(surveyInformation)){
				powerStation.setKcCreateTime(surveyInformation.getCreatorTime());
			}

			powerStationService.savePowerStation(powerStation, true, powerStation.getOwnersName(), "");
			//
			peasantHousehold.setConstructionState(ArrivalStateeEnum.勘察中.getCode());
			LambdaUpdateWrapper<PeasantHousehold> up = new LambdaUpdateWrapper<>();
			up.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.勘察中.getCode());
			long idsk = peasantHousehold.getSequenceNbr();
			up.eq(PeasantHousehold::getSequenceNbr, idsk);
			peasantHouseholdMapper.update(null, up);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("submitExamine error:", e);
		}

//        PowerStation powerStation = powerStationService.getObjByNhId(String.valueOf(peasantHousehold.getSequenceNbr()), PowerStationProcessStateEnum.作废.getCode());
//
//        String taskId = null;
//        Map<String, Object> objectMap = new HashMap<>(1);
//        objectMap.put("describe", "经销商已上传信息");
//        if (ObjectUtils.isNotEmpty(powerStation)) {
//            // 工作流执行一步
//            taskId = powerStation.getTaskId();
//        } else {
//            // 第一步启动工作流
//            powerStation = new PowerStation();
//        }
//        // 保存并审核
//        try {
//            FeignClientResult<String> submit = idxFeginService.submit(pageId, taskId, planId, null, "STATION_AUDIT", null, objectMap);
//            if (IDX_REQUEST_STATE.equals(String.valueOf(submit.getStatus()))) {
//                peasantHousehold.setSurveyOrNot(2);
//                peasantHousehold.setReview(1);
//                String code = submit.getResult();
//                // 插入记录表
//                powerStation.setPlanInstanceId(planId);
//                powerStation.setPowerStationCode(peasantHousehold.getPeasantHouseholdNo());
//                powerStation.setOwnersName(peasantHousehold.getOwnersName());
//                powerStation.setProjectAddress(peasantHousehold.getProjectAddressName());
//                powerStation.setPeasantHouseholdId(String.valueOf(peasantHousehold.getSequenceNbr()));
//                powerStation.setProcessStatus(PowerStationProcessStateEnum.进行中.getName());
//                powerStation.setServiceAgent(peasantHousehold.getDeveloperName());
//                log.info("流程执行成功：{}", code);
//                // 获取流程信息
//                FeignClientResult<JSONObject> record = idxFeginService.getRecord(code);
//                if (IDX_REQUEST_STATE.equals(String.valueOf(record.getStatus()))) {
//                    JSONObject resultObj = record.getResult();
//                    String taskIdNew = String.valueOf(resultObj.get("taskId"));
//                    String processInstanceId = String.valueOf(resultObj.get("processInstanceId"));
//                    String flowTaskId = String.valueOf(resultObj.get("flowTaskId"));
//                    powerStation.setTaskId(taskIdNew);
//                    powerStation.setProcessInstanceId(processInstanceId);
//                    powerStation.setFlowTaskId(flowTaskId);
//                    powerStation.setNextProcessNode(PowerStationNodeEnum.设计审核.getCode());
//                }
//                powerStationService.savePowerStation(powerStation, true,powerStation.getOwnersName(),"");
//            }
//        } catch (Exception e){
//            e.printStackTrace();
//            throw new BaseException("获取工作流节点失败！","400","获取工作流节点失败！");
//        }
	}

	public SurveyInfoAllDto querySurveyInfo(String surveyInformationId, String peasantHouseholdId,
			String processInstanceId, AgencyUserModel userInfo) {

		SurveyInfoAllDto surveyInfoAllDto = new SurveyInfoAllDto();
		PeasantHousehold peasantHousehold = new PeasantHousehold();
		if (!StringUtils.isEmpty(peasantHouseholdId)) {
			LambdaQueryWrapper<PeasantHousehold> peasantHouseholdWrapper = new LambdaQueryWrapper<>();
			peasantHouseholdWrapper.eq(PeasantHousehold::getSequenceNbr, peasantHouseholdId);
			peasantHousehold = peasantHouseholdServiceImpl.getBaseMapper().selectOne(peasantHouseholdWrapper);
			surveyInformationId = String.valueOf(peasantHousehold.getSurveyInformationId());
		} else {
			QueryWrapper<PeasantHousehold> peasantHouseholdQueryWrapper = new QueryWrapper<>();
			peasantHouseholdQueryWrapper.eq("survey_information_id", surveyInformationId);
			peasantHousehold = peasantHouseholdServiceImpl.getBaseMapper().selectOne(peasantHouseholdQueryWrapper);
		}
		// 勘察基本信息
		LambdaQueryWrapper<SurveyInformation> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(SurveyInformation::getSequenceNbr, surveyInformationId);
		SurveyInformation surveyInformation = this.baseMapper.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 (surveyInfoAllDto.getSurveyInformation().getSalesmanId() == null) {
			surveyInfoAllDto.getSurveyInformation().setSalesmanId(peasantHousehold.getDeveloperUserId());
			surveyInfoAllDto.getSurveyInformation().setSalesman(peasantHousehold.getDeveloper());
			surveyInfoAllDto.getSurveyInformation().setCreator(peasantHousehold.getDeveloper());
		}

		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(surveyInformation.getCreatorTime());

		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);

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

		if (information == null) {
			surveyInfoAllDto.setInformation(new InformationDto());
		} else {
			information.setHouseProve(null == commercial ? new ArrayList<>()
					: (CollectionUtil.isNotEmpty(commercial.getRealEstateLegal()) ? commercial.getRealEstateLegal()
							: new ArrayList<>()));
			information.setCardFile(null == commercial ? new ArrayList<>()
					: (CollectionUtil.isNotEmpty(commercial.getIdCardCredit()) ? commercial.getIdCardCredit()
							: new ArrayList<>()));
			surveyInfoAllDto.setInformation(BeanDtoUtils.convert(information, InformationDto.class));
		}

		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);

		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<WorkOrderPowerStation> up1 = new LambdaQueryWrapper();
		up1.eq(WorkOrderPowerStation::getPeasantHouseholdId, peasantHouseholdId);
		WorkOrderPowerStation workOrderPowerStation = workOrderPowerStationMapper.selectOne(up1);
		if (workOrderPowerStation != null) {
			Long workOrderId = workOrderPowerStation.getWorkOrderId();
			Long workOrderPowerStationId = workOrderPowerStation.getSequenceNbr();

			// 派工单信息
			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();
			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 != null ? powerStationConstructionData
							: new PowerStationConstructionData());
			surveyInfoAllDto
					.setPowerStationEngineeringInfo(powerStationEngineeringInfo != null ? powerStationEngineeringInfo
							: new PowerStationEngineeringInfo());
			surveyInfoAllDto.setWorkOrder(workOrder != null ? workOrder : new WorkOrder());

		} else {
			surveyInfoAllDto.setHygfOnGrid(new HygfOnGrid());
			surveyInfoAllDto.setPowerStationConstructionData(new PowerStationConstructionData());
			surveyInfoAllDto.setPowerStationEngineeringInfo(new PowerStationEngineeringInfo());
			surveyInfoAllDto.setWorkOrder(new WorkOrder());
		}

		//验收信息
		LambdaQueryWrapper<AcceptanceCheck> quv1 = new LambdaQueryWrapper<AcceptanceCheck>();
		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);
		}
		surveyInfoAllDto.setAcceptanceCheck(acceptanceCheck);

		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;
	}

	public JSONArray getRegionName() {
		JSONArray jsonArray = new JSONArray();
		if (redisUtils.hasKey(regionRedis)) {
			jsonArray = JSONArray.parseArray(redisUtils.get(regionRedis).toString());
		} else {
			Collection<RegionModel> regionChild = new ArrayList<>();
			RegionModel regionModel1 = new RegionModel();
			regionChild.add(regionModel1);
			FeignClientResult<Collection<RegionModel>> collectionFeignClientResult = Systemctl.regionClient
					.queryForTreeParent(610000L);
			Collection<RegionModel> result = collectionFeignClientResult.getResult();
			for (RegionModel regionModel : result) {
				if (regionModel.getChildren() != null && !regionModel.getChildren().isEmpty()) {
					for (RegionModel child : regionModel.getChildren()) {
						if (child.getChildren() != null && !child.getChildren().isEmpty()) {
							for (RegionModel childChild : child.getChildren()) {
								jsonArray.add(childChild);
							}
							child.setChildren(regionChild);
							jsonArray.add(child);
						}

					}
				}

				regionModel.setChildren(regionChild);
				jsonArray.add(regionModel);
			}

			redisUtils.set(regionRedis, jsonArray);
		}
		return jsonArray;
	}
}