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

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.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.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 lombok.extern.slf4j.Slf4j;
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.foundation.exception.BaseException;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.*;

/**
 * 勘察信息服务实现类
 *
 * @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
    ToDoTasksMapper toDoTasksMapper;
    @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;

    @Autowired
    WorkflowImpl workflow;

    /**
     * 分页查询
     */
    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)   {
        try {


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

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

        //更新扩展信息
        ExtendedInformation extendedInformation = BeanDtoUtils.convert(surveyInfoAllDto.getExtendedInformation(), ExtendedInformation.class);
        extendedInformation.setSurveyInformationId(surveyInformation.getSequenceNbr());
        extendedInformationService.saveOrUpdate(extendedInformation);

        //更新勘察明细信息
        SurveyDetailsDto oldSurveyDetails = surveyInfoAllDto.getSurveyDetails();
        SurveyDetails surveyDetails = BeanDtoUtils.convert(oldSurveyDetails, SurveyDetails.class);
        surveyDetails.setSurveyInformationId(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);
        //勘察后，更新状态
        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.setArchivesNumber(this.getNo(CodeEnum.档案.getCode(),peasantHousehold.getRegionalCompaniesSeq()));
        information.setFileNumber(this.getNo(CodeEnum.文件.getCode(),peasantHousehold.getRegionalCompaniesSeq()));
        information.setSurveyInformationId(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());
        peasantHousehold.setPermanentAddress(surveyInfoAllDto.getSurveyInformation().getPermanentAddress());
        peasantHousehold.setPermanentAddressDetail(surveyInfoAllDto.getSurveyInformation().getPermanentAddressDetail());
        peasantHousehold.setPermanentAddressDetail(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)){
            // 提交审核
            submitExamine(peasantHousehold);
            LambdaQueryWrapper<ToDoTasks> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ToDoTasks::getType, TaskTypeStationEnum.电站勘察.getCode());
            wrapper.eq(ToDoTasks::getState, "待办");
            wrapper.eq(ToDoTasks::getBusinessId, peasantHousehold.getSequenceNbr());
            ToDoTasks doTasks= toDoTasksMapper.selectOne(wrapper);
            if(doTasks!=null){
                doTasks.setState("已办");
                doTasks.setCompleteTime(new Date());
                toDoTasksMapper.updateById(doTasks);
                emqKeeper.getMqttClient().publish("TASK_MESSAGE" ,JSON.toJSONString(doTasks).getBytes(), 2 ,false);

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

            }
        }
        peasantHouseholdServiceImpl.saveOrUpdate(peasantHousehold);



        }catch (Exception e){
            e.printStackTrace();
            throw new BadRequest("系统异常");
        }

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

                powerStationService.savePowerStation(powerStation, true,powerStation.getOwnersName(),"");
                //
            LambdaUpdateWrapper<PeasantHousehold> up =new LambdaUpdateWrapper<>();
            up.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.勘察中.getCode());
            long idsk= basicGridAcceptance.getPeasantHouseholdId();
            up.eq(PeasantHousehold::getSequenceNbr,idsk);
            peasantHouseholdMapper.update(null,up);



        } catch (Exception e){
            e.printStackTrace();
            throw new BaseException("获取工作流节点失败！","400","获取工作流节点失败！");
        }



//        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(userInfo.getUserId());
          surveyInfoAllDto.getSurveyInformation().setSalesman(userInfo.getRealName());
          surveyInfoAllDto.getSurveyInformation().setCreator(userInfo.getRealName());
         }

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

            //工程信息

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



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