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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapBuilder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.module.hygf.api.Enum.*;
import com.yeejoin.amos.boot.module.hygf.api.dto.*;
import com.yeejoin.amos.boot.module.hygf.api.entity.*;
import com.yeejoin.amos.boot.module.hygf.api.mapper.AcceptanceCheckMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.HouseholdContractMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.PeasantHouseholdMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.PowerStationEngineeringInfoMapper;
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
    AcceptanceCheckMapper acceptanceCheckMapper;
    @Autowired
    PowerStationEngineeringInfoMapper powerStationEngineeringInfoMapper;
    @Autowired
    PeasantHouseholdMapper peasantHouseholdMapper;
    @Autowired
    HouseholdContractMapper householdContractMapper;
    @Autowired
    ConstructionAcceptanceRecordsServiceImpl acceptanceRecordsService;
    @Autowired
    FinancingInfoServiceImpl financingInfoService;
    @Autowired
    FinancingAuditingServiceImpl financingAuditingService;


    public Page<AcceptanceCheckDto> selectPage(Long regionCompanyId, Long amosDealerId, int current, int size,
                                               String projectAddress, String powerStationCode, String ownersName, String acceptanceCheckStatus,
                                               String gridConnectionTime, String formType, List<String> basicGridNodes, String type,String province, String developerName, String regionalCompaniesName) 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("acceptanceCheckStatus", acceptanceCheckStatus);
        map.put("gridConnectionTime", gridConnectionTime);
        map.put("formType", formType);
        map.put("regionCompanyId", regionCompanyId);
        map.put("amosDealerId", amosDealerId);
        map.put("basicGridNodes",basicGridNodes);
        map.put("type",type);
        map.put("province",province);
        map.put("developerName", developerName);
        map.put("regionalCompaniesName", regionalCompaniesName);
        List<AcceptanceCheckDto> list = acceptanceCheckMapper.selectPageList(map);

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


        PageInfo<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  AcceptanceCheck saveAndCommit(  Map<String,Object> model) {

        AcceptanceCheck basicGridRecord = this.getBaseMapper().selectById(model.get("sequenceNbr").toString());


        LambdaUpdateWrapper<AcceptanceCheck> update = new LambdaUpdateWrapper<>();
        update.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.JXSGLYDSH.getCode());
        update.set(AcceptanceCheck::getBasicGridNode,"jxsAdmin");
        if (model.get("type") != null && "1".equals(model.get("type").toString())) {
            // 执行工作流
            this.wofkflowExcute(basicGridRecord.getInstanceId(),"0","重新验收",BusinessWorkflowKey.验收提交.getCode());
            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(basicGridRecord.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);
            //发起待办
//            workflowResultDto.setInstanceId(basicGridRecord.getInstanceId());
//            commonService.buildTaskModel(commonService.buildTaskModelDto(basicGridRecord, workflowResultDto, BusinessTypeEnum.HYGF_YSLC));
        }

        //防止重复提交
//		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);
        Date date = new Date();
        ConstructionAcceptanceRecords da = new ConstructionAcceptanceRecords(model.get("realName").toString(), "提交验收审核",
                date , "", basicGridRecord.getSequenceNbr(), basicGridRecord.getWorkOrderPowerStationId(),
                basicGridRecord.getPeasantHouseholdId(), "");
        acceptanceRecordsService.save(da);
        AcceptanceCheck acceptanceCheck = this.getById(basicGridRecord.getSequenceNbr());
        //添加验收时间
        if(Objects.nonNull(acceptanceCheck) && Objects.isNull(acceptanceCheck.getYsCreateTime())){
            LambdaUpdateWrapper<AcceptanceCheck> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(AcceptanceCheck::getYsCreateTime,date);
            wrapper.eq(BaseEntity::getSequenceNbr,basicGridRecord.getSequenceNbr());
            this.update(null,wrapper);
        }
        return basicGridRecord;
    }



    //	工作流执行一步
    public void wofkflowExcute(String instanceId, String approvalStatus,String comment,String taskKey) {
        LambdaQueryWrapper<AcceptanceCheckAuditing> query = new LambdaQueryWrapper<>();
        query.eq(AcceptanceCheckAuditing::getInstanceId, instanceId);
        query.orderByDesc(BaseEntity::getRecDate);
        query.last("limit 1");
        AcceptanceCheckAuditing basicGridAuditing = acceptanceCheckAuditingService.getBaseMapper().selectOne(query);
        if (!taskKey.contains(basicGridAuditing.getNextNodeKey())){
            throw new BadRequest("无可执行任务");
        }

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

        task.setTaskId(basicGridAuditing.getNextTaskId());
        HashMap<String, Object> map = new HashMap<>();
        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);
        //更新待办
//        workflowResultDto.setInstanceId(basicGridAuditingDto.getInstanceId());
//        commonService.updateTaskModelAndAddTask(basicGridAuditingDto,workflowResultDto,BusinessTypeEnum.HYGF_YSLC);
    }


    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, BusinessWorkflowKey.经销商管理员审核.getCode());
        //修改并网数据状态
        basicGridRecord.setAcceptanceCheckStatus(approvalStatus.equals("0")?GridStatusEnum.PQYYDSH.getCode():GridStatusEnum.WTG.getCode());
        basicGridRecord.setBasicGridNode(approvalStatus.equals("0")?"ys-area":null);
        this.updateById(basicGridRecord);

        ConstructionAcceptanceRecords da = new ConstructionAcceptanceRecords();
        da.setOperationTime(new Date());
        da.setOperationContent("验收管理-经销商管理员审核-"+(approvalStatus.equals("0")?"通过":"驳回"));
        da.setOperator(kv.get("operator"));
        da.setOperationResults(approvalStatus.equals("0")?"通过":"驳回");
        da.setAcceptanceId(basicGridRecord.getSequenceNbr());
        da.setWorkOrderPowerStationId(basicGridRecord.getWorkOrderPowerStationId());
        da.setPeasantHouseholdId(basicGridRecord.getPeasantHouseholdId());
        da.setNotes(kv.get("comment"));
        acceptanceRecordsService.save(da);
    }



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

        AcceptanceCheck basicGridRecord = this.getBaseMapper().selectById(sequenceNbr);
        LambdaUpdateWrapper<AcceptanceCheck> up = new LambdaUpdateWrapper<>();
        ConstructionAcceptanceRecords da = new ConstructionAcceptanceRecords();
        switch (status){
            case "ys-area":
                up.set(AcceptanceCheck::getPowerStationAreaStatus,approvalStatus.equals("0")?"通过":"驳回");
                da.setOperationContent("验收审核-片区运营审核-" + (approvalStatus.equals("0")?"通过":"驳回"));
                if (approvalStatus.equals("0")){
                    up.set(AcceptanceCheck::getBasicGridNode,"ys-fawu,ys-tourong");

                    Boolean flag = true;
                    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());
                            flag = false;
                            break;
                        }
                    }
                    if (CollectionUtil.isNotEmpty(hygfRectificationOrders) && flag){
                        up.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.DZG.getCode());
                    }else {
                        up.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.YSROLESDSH.getCode());
                    }
                }
                this.wofkflowExcute(instanceId, approvalStatus , comment ,BusinessWorkflowKey.片区运营审核.getCode() );
                break;
            case "ys-fawu":
                up.set(AcceptanceCheck::getPowerStationLegalStatus,approvalStatus.equals("0")?"通过":"驳回");
                da.setOperationContent("验收审核-法务审核-" + (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,BusinessWorkflowKey.法务审核.getCode()  );
                    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.TRDSH.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.TRDSH.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,BusinessWorkflowKey.法务审核.getCode()  );
                }
                break;
            case "ys-tourong":
                up.set(AcceptanceCheck::getPowerStationFinancingStatus,approvalStatus.equals("0")?"通过":"驳回");
                da.setOperationContent("验收审核-投融审核-" + (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  ,BusinessWorkflowKey.投融审核.getCode());
                    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.FWDSH.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.FWDSH.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  ,BusinessWorkflowKey.投融审核.getCode() );
                }
                break;
            default:
                da.setOperationContent("验收审核-资产审核-" + (approvalStatus.equals("0")?"通过":"驳回"));
                up.set(AcceptanceCheck::getPowerStationAssetsStatus,approvalStatus.equals("0")?"通过":"驳回");
                if (approvalStatus.equals("0")){
                    up.set(AcceptanceCheck::getBasicGridNode,"all");
                    up.set(AcceptanceCheck::getAcceptanceTime,new Date());
                    up.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.YWC.getCode());
                    up.set(AcceptanceCheck::getYsEndTime,new Date());
                    //验收完成后需对投融数据进行处理。
                    LambdaUpdateWrapper<FinancingInfo> wrapper = new LambdaUpdateWrapper<>();
                    wrapper.eq(FinancingInfo::getPeasantHouseholdId,basicGridRecord.getPeasantHouseholdId());
                    wrapper.set(FinancingInfo::getStatus,"待推送");
                    financingInfoService.update(null,wrapper);

                    LambdaQueryWrapper<FinancingAuditing> finQuery = new LambdaQueryWrapper<>();
                    finQuery.eq(FinancingAuditing::getPeasantHouseholdId,basicGridRecord.getPeasantHouseholdId());
                    finQuery.orderByDesc(BaseEntity::getRecDate);
                    finQuery.last("limit 1");
                    FinancingAuditing financingAuditing = financingAuditingService.getBaseMapper().selectOne(finQuery);
                    if (!Objects.isNull(financingAuditing)){
                        financingInfoService.execueFlow(MapBuilder.<String,Object>create().put("instanceId",financingAuditing.getInstanceId()).put("approvalStatus","0").put("isZG","1").build());

                    }
                }
                this.wofkflowExcute(instanceId, approvalStatus , comment  ,BusinessWorkflowKey.资产审核.getCode() );


                // 线上验收
                LambdaUpdateWrapper<PeasantHousehold> up1 = new LambdaUpdateWrapper<>();
                up1.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.验收完成.getCode());
                long idsk = basicGridRecord.getPeasantHouseholdId();
                up1.eq(PeasantHousehold::getSequenceNbr, idsk);
                peasantHouseholdMapper.update(null, up1);
        }
        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);
        }

        da.setOperationTime(new Date());
        da.setOperator(kv.get("operator"));
        da.setOperationResults(approvalStatus.equals("0")?"通过":"驳回");
        da.setAcceptanceId(basicGridRecord.getSequenceNbr());
        da.setWorkOrderPowerStationId(basicGridRecord.getWorkOrderPowerStationId());
        da.setPeasantHouseholdId(basicGridRecord.getPeasantHouseholdId());
        da.setNotes(kv.get("comment"));
        acceptanceRecordsService.save(da);
        return CommonResponseNewUtil.success();
    }




    public ResponseModel addRectification(HygfRectificationOrder hygfRectificationOrder) {
        if (Objects.isNull( hygfRectificationOrder.getRectificationSource()) ){
            return	CommonResponseNewUtil.failureMessage("多角色用户发起整改单，发起人角色不可为空");
        }
        if (hygfRectificationOrder.getAddorSubmit().equals("0") && Objects.isNull(hygfRectificationOrder.getRectificationIdea())){
            return	CommonResponseNewUtil.failureMessage("整改类型及整改项不可为空");
        }
        if (hygfRectificationOrder.getAddorSubmit().equals("0") && !Objects.isNull(hygfRectificationOrder.getRectificationIdea())){
            List<Object> rectificationIdea = hygfRectificationOrder.getRectificationIdea();
            for (Object item : rectificationIdea) {
                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(item));
                Collection<Object> values = jsonObject.values();
                if (values.size() < 2){
                    return	CommonResponseNewUtil.failureMessage("整改类型及整改项不可为空");
                }
                if (jsonObject.containsKey("type")){
                        if (null == jsonObject.get("type")){
                            return	CommonResponseNewUtil.failureMessage("整改类型及整改项不可为空");
                        }
                }
                if (jsonObject.containsKey("items")){
                    JSONArray item1 = jsonObject.getJSONArray("items");
                    for (Object o : item1) {
                        if (!JSON.parseObject(JSON.toJSONString(o)).containsKey("value")){
                            return	CommonResponseNewUtil.failureMessage("整改类型及整改项不可为空");
                        }
                    }
                }
            }
        }
        if (hygfRectificationOrder.getSequenceNbr() != null ){
            LambdaQueryWrapper<HygfRectificationOrder> wr= new LambdaQueryWrapper<>();
            wr.eq(HygfRectificationOrder::getPeasantHouseholeId,hygfRectificationOrder.getPeasantHouseholeId());
            wr.notIn(HygfRectificationOrder::getRectificationStatus,Arrays.asList("已作废","已完成"));
            wr.eq(HygfRectificationOrder::getRectificationSource,hygfRectificationOrder.getRectificationSource());
            wr.ne(BaseEntity::getSequenceNbr,hygfRectificationOrder.getSequenceNbr());
            List<HygfRectificationOrder> list = rectificationOrderService.getBaseMapper().selectList(wr);
            if (CollectionUtil.isNotEmpty(list)){
                return	CommonResponseNewUtil.failureMessage("当前农户存在其他进行中的整改单,不可重新发起");
            }
        }

        //查询当前并网数据
        LambdaQueryWrapper<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")){
            int num = 0;
            //如果历史有未完成的整改单则片区审核完成的时候改变主流程状态为整改单的状态
			LambdaQueryWrapper<HygfRectificationOrder> query = new LambdaQueryWrapper<>();
			query.eq(HygfRectificationOrder::getPeasantHouseholeId,basicGridRecord.getPeasantHouseholdId());
			query.in(HygfRectificationOrder::getRectificationStatus,Arrays.asList("待整改","待提交","待审核"));
			query.in(HygfRectificationOrder::getRectificationSource,Arrays.asList("ys-tourong","ys-fawu"));
			List<HygfRectificationOrder> hygfRectificationOrders = rectificationOrderService.getBaseMapper().selectList(query);
			for (HygfRectificationOrder hygfRectificationOrderO : hygfRectificationOrders) {
				if (hygfRectificationOrderO.getRectificationStatus().equals("待审核")){
					qu.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.ZGDSH.getCode());
					break;
				}
			}
			if ( num == 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.YSROLESDSH.getCode());

                    }else if (Objects.isNull(basicGridRecord.getPowerStationLegalStatus() ) ){
                        qu.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.FWDSH.getCode());
                    }else {
                        qu.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.TRDSH.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<AcceptanceCheck>();
            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.YSROLESDSH.getCode());
                }else if (Objects.isNull(basicGridRecord.getPowerStationLegalStatus() ) ){
                    qu.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.FWDSH.getCode());
                }else {
                    qu.set(AcceptanceCheck::getAcceptanceCheckStatus,GridStatusEnum.TRDSH.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();
    }
}