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

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.ArrivalStateeEnum;
import com.yeejoin.amos.boot.module.hygf.api.Enum.GridStatusEnum;
import com.yeejoin.amos.boot.module.hygf.api.Enum.WorkOrderEnum;
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.AcceptanceCheckMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.PeasantHouseholdMapper;
import com.yeejoin.amos.boot.module.hygf.api.service.IAcceptanceCheckService;
import com.yeejoin.amos.boot.module.hygf.api.util.CommonResponseNewUtil;
import com.yeejoin.amos.component.robot.BadRequest;
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.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

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

/**
 * 并网验收节点服务实现类
 *
 * @author system_generator
 * @date 2024-08-21
 */
@Service
public class AcceptanceCheckServiceImpl extends BaseService<AcceptanceCheckDto,AcceptanceCheck,AcceptanceCheckMapper> implements IAcceptanceCheckService {
    @Autowired
    AcceptanceCheckAuditingServiceImpl acceptanceCheckAuditingService;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    RectificationOrderAuditingServiceImpl rectificationOrderAuditingService;
    @Autowired
    HygfRectificationOrderServiceImpl rectificationOrderService;
    @Autowired
    PeasantHouseholdMapper peasantHouseholdMapper;



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

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

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



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

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


        LambdaUpdateWrapper<AcceptanceCheck> update = new LambdaUpdateWrapper<>();
        update.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.JXSGLYDSH.getCode());
        update.set(AcceptanceCheck::getBasicGridNode,"jxsAdmin");
        if (grid.getType() != null && "1".equals(grid.getType())) {
            // 执行工作流
            this.wofkflowExcute(basicGridRecord.getInstanceId(),"0","重新验收");
            update.set(AcceptanceCheck::getPowerStationAreaStatus,null);
            update.set(AcceptanceCheck::getPowerStationLegalStatus,null);
            update.set(AcceptanceCheck::getPowerStationFinancingStatus,null);
            update.set(AcceptanceCheck::getPowerStationAssetsStatus,null);
        } else {
            //开启工作流 并执行一步
            ActWorkflowBatchDTO actWorkflowBatchDTO = new ActWorkflowBatchDTO();
            List<ActWorkflowStartDTO> params = new ArrayList<>();
            ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
            dto.setProcessDefinitionKey("AcceptanceCheck");
            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);
            AcceptanceCheckAuditingDto basicGridAuditingDto = new AcceptanceCheckAuditingDto();
            BeanUtils.copyProperties(workflowResultDto, basicGridAuditingDto);
            basicGridAuditingDto.setPeasantHouseholdId(grid.getPeasantHouseholdId());
            basicGridAuditingDto.setPromoter(RequestContext.getExeUserId());
            acceptanceCheckAuditingService.createWithModel(basicGridAuditingDto);
            update.set(AcceptanceCheck::getInstanceId,basicGridAuditingDto.getInstanceId());

            // 线上验收
            LambdaUpdateWrapper<PeasantHousehold> up = new LambdaUpdateWrapper<>();
            up.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.验收中.getCode());
            long idsk = basicGridRecord.getPeasantHouseholdId();
            up.eq(PeasantHousehold::getSequenceNbr, idsk);
            peasantHouseholdMapper.update(null, up);
        }

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

        update.eq(BaseEntity::getSequenceNbr,basicGridRecord.getSequenceNbr());
        this.update(null,update);
        //发起待办
//		commonService.buildTaskModel(buildBWYSTaskModel(grid, basicGridAcceptance));
        return grid;
    }



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

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

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

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

        AcceptanceCheck basicGridRecord = this.getBaseMapper().selectById(sequenceNbr);
        //执行工作流
        this.wofkflowExcute(instanceId, approvalStatus , comment);
        //修改并网数据状态
        basicGridRecord.setAcceptanceCheckStatus(approvalStatus.equals("0")?GridStatusEnum.PQYYDSH.getCode():GridStatusEnum.WTG.getCode());
        basicGridRecord.setBasicGridNode("ys-area");
        this.updateById(basicGridRecord);
    }



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

        AcceptanceCheck basicGridRecord = this.getBaseMapper().selectById(sequenceNbr);
        LambdaUpdateWrapper<AcceptanceCheck> up = new LambdaUpdateWrapper<>();
        switch (status){
            case "ys-area":
                up.set(AcceptanceCheck::getPowerStationAreaStatus,approvalStatus.equals("0")?"通过":"驳回");
                up.set(AcceptanceCheck::getBasicGridNode,"ys-fawu,ys-tourong");
                up.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.ROLESDSH.getCode());
                LambdaQueryWrapper<HygfRectificationOrder> query = new LambdaQueryWrapper<>();
                query.eq(HygfRectificationOrder::getPeasantHouseholeId,basicGridRecord.getPeasantHouseholdId());
                query.in(HygfRectificationOrder::getRectificationStatus,Arrays.asList("待整改","待提交","待审核"));
                query.in(HygfRectificationOrder::getRectificationSource,Arrays.asList("ys-fawu","ys-tourong","ys-zichan"));
                List<HygfRectificationOrder> hygfRectificationOrders = rectificationOrderService.getBaseMapper().selectList(query);
                for (HygfRectificationOrder hygfRectificationOrder : hygfRectificationOrders) {
                    if (hygfRectificationOrder.getRectificationStatus().equals("待审核")){
                        up.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.ZGDSH.getCode());
                        break;
                    }
                    if (hygfRectificationOrder.getRectificationStatus().equals("待整改")){
                        up.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.DZG.getCode());
                    }
                }
                this.wofkflowExcute(instanceId, approvalStatus , comment  );
                break;
            case "ys-fawu":
                up.set(AcceptanceCheck::getPowerStationLegalStatus,approvalStatus.equals("0")?"通过":"驳回");
                if (basicGridRecord.getPowerStationFinancingStatus() != null && basicGridRecord.getPowerStationFinancingStatus().equals("通过")&&approvalStatus.equals("0") ){
                    up.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.ZCDSH.getCode());
                    this.wofkflowExcute(instanceId, approvalStatus , comment  );
                    up.set(AcceptanceCheck::getBasicGridNode,"ys-zichan");
 
                }else if( null == basicGridRecord.getPowerStationFinancingStatus() && approvalStatus.equals("0") &&  (  Objects.isNull(basicGridRecord.getRectificationStatus())||(!basicGridRecord.getRectificationStatus().contains("ys-tourong")) ) ) {
                    up.set(AcceptanceCheck::getBasicGridNode,"ys-tourong");
                    up.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.GCDSH.getCode());
                }else if( null == basicGridRecord.getPowerStationFinancingStatus() && approvalStatus.equals("0") && basicGridRecord.getRectificationStatus() .contains("ys-tourong") ) {
                    up.set(AcceptanceCheck::getBasicGridNode,"ys-tourong");
                    LambdaQueryWrapper<HygfRectificationOrder> query2 = new LambdaQueryWrapper<>();
                    query2.eq(HygfRectificationOrder::getPeasantHouseholeId,basicGridRecord.getPeasantHouseholdId());
                    query2.in(HygfRectificationOrder::getRectificationStatus,Arrays.asList("待整改","待审核","待提交"));
                    query2.eq(HygfRectificationOrder::getRectificationSource,"ys-tourong");
                    HygfRectificationOrder hygfRectificationOrder = rectificationOrderService.getBaseMapper().selectOne(query2);
                    if (hygfRectificationOrder.getRectificationStatus().equals("待提交")){
                        up.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.SJDSH.getCode());
                    }else if (hygfRectificationOrder.getRectificationStatus().equals("待整改")){
                        up.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.DZG.getCode());
                    }else {
                        up.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.ZGDSH.getCode());
                    }
                }
                else if (null != basicGridRecord.getPowerStationFinancingStatus() && basicGridRecord.getPowerStationFinancingStatus().equals("驳回")){
                    return	CommonResponseNewUtil.failureMessage("该流程已被投融人员审核驳回，请刷新列表");
                }else {
                    this.wofkflowExcute(instanceId, approvalStatus , comment  );
                }
                break;
            case "ys-tourong":
                up.set(AcceptanceCheck::getPowerStationFinancingStatus,approvalStatus.equals("0")?"通过":"驳回");
                if (basicGridRecord.getPowerStationLegalStatus() != null && basicGridRecord.getPowerStationLegalStatus().equals("通过")&&approvalStatus.equals("0") ){
                    up.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.ZCDSH.getCode());
                    this.wofkflowExcute(instanceId, approvalStatus , comment  );
                    up.set(AcceptanceCheck::getBasicGridNode,"ys-zichan");
                }else if( null == basicGridRecord.getPowerStationLegalStatus() && approvalStatus.equals("0") && (  Objects.isNull(basicGridRecord.getRectificationStatus())||(!basicGridRecord.getRectificationStatus().contains("ys-fawu")) )) {
                    up.set(AcceptanceCheck::getBasicGridNode,"ys-fawu");
                    up.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.SJDSH.getCode());
                }else if( null == basicGridRecord.getPowerStationLegalStatus() &&approvalStatus.equals("0") && !Objects.isNull(basicGridRecord.getRectificationStatus()) && basicGridRecord.getRectificationStatus().contains("ys-fawu") ) {
                    up.set(AcceptanceCheck::getBasicGridNode,"ys-fawu");
                    LambdaQueryWrapper<HygfRectificationOrder> query1 = new LambdaQueryWrapper<>();
                    query1.eq(HygfRectificationOrder::getPeasantHouseholeId,basicGridRecord.getPeasantHouseholdId());
                    query1.in(HygfRectificationOrder::getRectificationStatus,Arrays.asList("待整改","待审核","待提交"));
                    query1.eq(HygfRectificationOrder::getRectificationSource,"ys-fawu");
                    HygfRectificationOrder hygfRectificationOrder = rectificationOrderService.getBaseMapper().selectOne(query1);
                    if (hygfRectificationOrder.getRectificationStatus().equals("待提交")){
                        up.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.SJDSH.getCode());
                    }else if (hygfRectificationOrder.getRectificationStatus().equals("待整改")){
                        up.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.DZG.getCode());
                    }else {
                        up.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.ZGDSH.getCode());
                    }
                } else if (null != basicGridRecord.getPowerStationLegalStatus() && basicGridRecord.getPowerStationLegalStatus().equals("驳回")){
                    return	CommonResponseNewUtil.failureMessage("该流程已被法务人员审核驳回，请刷新列表");
                }else {
                    this.wofkflowExcute(instanceId, approvalStatus , comment  );
                }
                break;
            default:
                up.set(AcceptanceCheck::getPowerStationAreaStatus,approvalStatus.equals("0")?"通过":"驳回");
                up.set(AcceptanceCheck::getBasicGridNode,"all");
                up.set(AcceptanceCheck::getAcceptanceTime,new Date());
                up.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.YWC.getCode());
                this.wofkflowExcute(instanceId, approvalStatus , comment  );
        }
        if (approvalStatus.equals("1") ){
            up.eq(BaseEntity::getSequenceNbr,sequenceNbr);
            up.set(AcceptanceCheck::getBasicGridNode,null);
            up.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.WTG.getCode());
        }
        //修改验收数据状态
        if (StringUtils.isNotEmpty(sequenceNbr)){
            up.eq(BaseEntity::getSequenceNbr,sequenceNbr);
            this.getBaseMapper().update(null,up);
        }
        return CommonResponseNewUtil.success();
    }




    public ResponseModel addRectification(HygfRectificationOrder hygfRectificationOrder) {

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

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

        String addorSubmit = hygfRectificationOrder.getAddorSubmit();;
        LambdaUpdateWrapper<AcceptanceCheck> qu = new LambdaUpdateWrapper();
        qu.eq(AcceptanceCheck::getPeasantHouseholdId, hygfRectificationOrder.getPeasantHouseholeId());
        if (!Objects.isNull(basicGridRecord) && null !=  basicGridRecord.getRectificationStatus() && !basicGridRecord.getRectificationStatus().contains(hygfRectificationOrder.getRectificationSource())){
            qu.set(AcceptanceCheck::getRectificationStatus,basicGridRecord.getRectificationStatus()+","+hygfRectificationOrder.getRectificationSource());
            this.update(null,qu);
        }else if (!Objects.isNull(basicGridRecord) && null ==  basicGridRecord.getRectificationStatus() ) {
            qu.set(AcceptanceCheck::getRectificationStatus,hygfRectificationOrder.getRectificationSource());
            this.update(null,qu);
        }
        //修改状态
        if (addorSubmit.equals("0")){
            qu.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.DZG.getCode());
            this.update(null,qu);
        }
        rectificationOrderAuditingService.addRectification(hygfRectificationOrder);

        return 	CommonResponseNewUtil.success();
    }


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

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

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

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

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

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

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

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

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

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



        if (hygfRectificationOrder.getRectificationSource().equals("ys-area")){
            qu.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.PQYYDSH.getCode());
        } else if (hygfRectificationOrder.getRectificationSource().equals("ys-fawu") || hygfRectificationOrder.getRectificationSource().equals("ys-tourong")){
            //查询是否还有其它类型待整改的整改单存在 若存在后置节点为当前并网状态
            LambdaQueryWrapper<HygfRectificationOrder> wr= new LambdaQueryWrapper<>();
            wr.eq(HygfRectificationOrder::getPeasantHouseholeId,hygfRectificationOrder.getPeasantHouseholeId());
            wr.notIn(HygfRectificationOrder::getRectificationStatus,Arrays.asList("待提交","已作废","已完成"));
            wr.ne(BaseEntity::getSequenceNbr,hygfRectificationOrder.getSequenceNbr());
            List<HygfRectificationOrder> list = rectificationOrderService.getBaseMapper().selectList(wr);

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

            }
        }else {
            qu.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.ZCDSH.getCode());
        }
        this.update(null,qu);
        return 	CommonResponseNewUtil.success();
    }
}