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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
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.config.UserLimits;
import com.yeejoin.amos.boot.module.hygf.api.dto.FinancingAuditingDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.FinancingInfoDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.PeasantHouseholdDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.WorkflowResultDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.*;
import com.yeejoin.amos.boot.module.hygf.api.mapper.FinancingInfoMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.HouseholdContractMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.PowerStationEngineeringInfoMapper;
import com.yeejoin.amos.boot.module.hygf.api.service.IFinancingInfoService;
import com.yeejoin.amos.boot.module.hygf.api.util.RedisLockUtil;
import com.yeejoin.amos.boot.module.hygf.biz.vo.RouthPathVO;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowBatchDTO;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowStartDTO;
import com.yeejoin.amos.feign.workflow.model.ProcessTaskDTO;
import com.yeejoin.amos.feign.workflow.model.TaskResultDTO;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

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

/**
 * 服务实现类
 *
 * @author system_generator
 * @date 2024-04-01
 */
@Service
public class FinancingInfoServiceImpl extends BaseService<FinancingInfoDto, FinancingInfo, FinancingInfoMapper> implements IFinancingInfoService {
    private static String PROCESSKEY = "StationFinancing";
    @Autowired
    RedisUtils redisUtils;
    /**
     * 分页查询
     */
    @Autowired
    private FinancingInfoMapper financingInfoMapper;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private PeasantHouseholdServiceImpl peasantHouseholdService;
//    @Autowired
//    private WorkflowImpl workflow;
    @Autowired
    private FinancingAuditingServiceImpl financingAuditingService;
    @Autowired
    private FinancingRectificationOrderServiceImpl financingRectificationOrderService;
    @Autowired
    private HouseholdContractMapper householdContractMapper;
    @Autowired
    private PowerStationEngineeringInfoMapper powerStationEngineeringInfoMapper;
    @Autowired
    private AcceptanceCheckServiceImpl acceptanceCheckService;
    @Autowired
    private AcceptanceCheckAuditingServiceImpl acceptanceCheckAuditingService;
    @Autowired
    private FinancingRegionalServiceImpl financingRegionalService;
    @Autowired
    private ToDoTasksServiceImpl toDoTasksService;

    @Resource(type = RedisLockUtil.class)
    private RedisLockUtil redisLockUtil;

    @UserLimits
    public Page<Map<String, Object>> queryForFinancingInfoPage(Page<Map<String, Object>> page, String type, String status, String regionalCompaniesCode, String ownersName, String region,String batchNo,String isHistory, String projectAddress, String peasantHouseholdNo, String developerName, String financingCompaniesName, String startTime, String endTime,String routhPathId) {
        StdUserEmpower orgCode = (StdUserEmpower) redisUtils.get("Emp_" + RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken()));
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        List<String> amosOrgCodes = orgCode.getAmosOrgCode();
        Map<String, Object> params = new HashMap<>();
        params.put("ownersName", ownersName);
        if (null != status ){
                params.put("status", Arrays.asList(status.split(",")));
        }
        params.put("regionalCompaniesCode", regionalCompaniesCode);
        params.put("type", type);
        params.put("batchNo", batchNo);
        params.put("isHistory", isHistory);
        params.put("region", region);
        params.put("projectAddress", projectAddress);
        params.put("peasantHouseholdNo", peasantHouseholdNo);
        params.put("developerName", developerName);
        params.put("financingCompaniesName", financingCompaniesName);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("routhPathId", routhPathId);
        // 1 投融人员  2.融资  3经销商管理员
        switch (type) {
            case "1":
                break;
            case "2":
                Long sequenceNbr = reginParams.getCompany().getSequenceNbr();
                params.put("financingCompaniesSeq", String.valueOf(sequenceNbr));
                break;
            default:
                amosOrgCodes = Arrays.asList(orgCode.getAdminRegionalCompaniesCode().split(","));
        }
        PageHelper.startPage((int) page.getCurrent(), (int) page.getSize());
        List<Map<String, Object>> list = financingInfoMapper.getStationFinancingInfoList(params, amosOrgCodes);
        list.forEach(e -> {
//            e.put("scale", householdContractMapper.getHygfCommercialScale((String) e.get("peasantHouseholdNo")));
//            if (e.containsKey("isHistory") && e.get("isHistory").toString().equals("1")){
//                e.put("realScale", powerStationEngineeringInfoMapper.getRealScaleByPeasantHouseholdNoIsHisotry((String) e.get("peasantHouseholdNo")));
//            }else {
//                e.put("realScale", powerStationEngineeringInfoMapper.getRealScaleByPeasantHouseholdNo((String) e.get("peasantHouseholdNo")));
//            }
            e.put("regionName",e.get("projectAddress").toString().split("/")[0]);
            e.put("trCreateTime", DateUtils.dateStringFormat(e.get("trCreateTime")));
            if (null != e.get("instanceId") && e.get("instanceId").toString().contains(",")) {
                String[] instanceIds = e.get("instanceId").toString().split(",");
                e.put("instanceId", instanceIds[0]);
                e.put("nodeRouting", instanceIds[1]);
            }
        });
        PageInfo<Map<String, Object>> infos = new PageInfo<>(list);
        page.setRecords(list);
        page.setTotal(infos.getTotal());
        return page;
    }


   public List<Map<String,Object>>  selectRegion(){

       return financingInfoMapper.selectRegion();
    }

    public List<Map<String,Object>>  selectRegionByParentCode(String parentCode, String level){
       return financingInfoMapper.selectRegionByParentCode(parentCode, level);
    }

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

    public FinancingInfoDto saveModel(FinancingInfoDto model) {
        String lockName = String.format("LockName:powerStationExamine");
        try{
            Boolean isLocked = redisLockUtil.tryLock(lockName, lockName, 10, 1);
            if (BooleanUtils.isNotTrue(isLocked)) {
                throw new com.yeejoin.amos.component.robot.BadRequest("其他用户正在操作，请刷新后再试！");
            }

            List<String> ids;
            long time = new Date().getTime();
            String batcvNo = String.valueOf(time);
            if (model.getPeasantHouseholdIds().contains(",")) {
                ids = Arrays.asList(model.getPeasantHouseholdIds().split(","));
            } else {
                ids = Arrays.asList(new String[]{model.getPeasantHouseholdIds()});
            }
            Map<String, Object> orgInfo = this.getBaseMapper().selectRZOrgInfo(model.getFinancingCompaniesSeq());
            model.setFinancingCompaniesCode(orgInfo.getOrDefault("ORG_CODE", "").toString());
            model.setFinancingCompaniesName(orgInfo.getOrDefault("COMPANY_NAME", "").toString());
            ids.stream().forEach(e -> {
                LambdaQueryWrapper<FinancingInfo> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(FinancingInfo::getPeasantHouseholdId, Long.valueOf(e));
                FinancingInfo financingInfos = this.getBaseMapper().selectOne(queryWrapper);
                if (ObjectUtils.isEmpty(financingInfos)) {
                    LambdaQueryWrapper<PeasantHousehold> query= new LambdaQueryWrapper<>();
                    query.eq(BaseEntity::getSequenceNbr,e);
                    PeasantHousehold peasantHousehold = peasantHouseholdService.getBaseMapper().selectOne(query);


                    model.setStatus(FinancingAuditEnum.待融资审核.getName());
                    model.setPeasantHouseholdId(Long.valueOf(e));
                    FinancingInfoDto financingInfoDto = new FinancingInfoDto();
                    BeanUtils.copyProperties(model, financingInfoDto);
                    financingInfoDto.setSequenceNbr(null);
                    financingInfoDto.setBatchNo(batcvNo);
                    financingInfoDto.setRegionalCompaniesSeq(peasantHousehold.getRegionalCompaniesSeq());
                    financingInfoDto.setTrCreateTime(new Date());
                    this.createWithModel(financingInfoDto);
                    //开启工作流 并执行一步
                    ActWorkflowBatchDTO actWorkflowBatchDTO = new ActWorkflowBatchDTO();
                    List<ActWorkflowStartDTO> list = new ArrayList<>();
                    ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
                    dto.setProcessDefinitionKey(PROCESSKEY);
                    Date date = new Date();
                    dto.setBusinessKey(String.valueOf(date.getTime()));
                    dto.setCompleteFirstTask(true);
                    //工作流程图第一步执行后存在互斥网关 isFlag为表达式 默认为1执行到融资审核
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("isFlag", "0");
                    dto.setVariables(map);
                    list.add(dto);
                    actWorkflowBatchDTO.setProcess(list);
                    List<ProcessTaskDTO> processTaskDTOS = workFlowService.startBatch(actWorkflowBatchDTO);
                    List<WorkflowResultDto> workflowResultDtos = workFlowService.buildWorkFlowInfo(processTaskDTOS);
                    WorkflowResultDto workflowResultDto = workflowResultDtos.get(0);
                    FinancingAuditingDto financingAuditingDto = new FinancingAuditingDto();
                    BeanUtils.copyProperties(workflowResultDto, financingAuditingDto);
                    financingAuditingDto.setPeasantHouseholdId(Long.valueOf(e));
                    financingAuditingDto.setPromoter(RequestContext.getExeUserId());
                    financingAuditingService.createWithModel(financingAuditingDto);
                    //完成新增投融
                    ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.投融资.getCode(),Long.valueOf(e));
                    toDoTasksService.completeToDoTasks(toDoTasks1,"");
                    //发起待办
                    String taskName="您有一条投融的待办";
                    if(Objects.nonNull(peasantHousehold)){
                        taskName= peasantHousehold.getOwnersName() +"待融资审核" ;
                    }
                    RouthPathVO routhPathVO = new RouthPathVO();
                    routhPathVO.setRouthPathId(String.valueOf(peasantHousehold.getSequenceNbr()));
                    String routhPath = toDoTasksService.getRouthPath(TaskTypeStationEnum.投融资.getCode(),workflowResultDto.getNextNodeKey(), routhPathVO);
                    String wxRouthPath = toDoTasksService.getWxRouthPath(TaskTypeStationEnum.投融资.getCode(),workflowResultDto.getNextNodeKey(), routhPathVO);
                    ToDoTasks toDoTasks=  new ToDoTasks (TaskTypeStationEnum.投融资.getCode(),  peasantHousehold.getSequenceNbr(),  taskName, model.getFinancingCompaniesCode(),routhPath,wxRouthPath);
                    String roleId = toDoTasksService.getRoleIdByName("户用光伏-融资");
                    List<String> userIds = toDoTasksService.getTodoUserIdsByRzjg(model.getFinancingCompaniesCode(),roleId);
                    toDoTasksService.addToDoTasksByUserIds(userIds,toDoTasks);
                }
                //批量 兼容审核不通过及整改待推送
                else if (financingInfos.getStatus().equals(FinancingAuditEnum.审核不通过.getName()) || financingInfos.getStatus().equals("待推送")   ){
                    financingInfos.setStatus(FinancingAuditEnum.待融资审核.getName());
                    financingInfos.setTrCreateTime(new Date());
                    Map<String, Object> orgInfo1 = this.getBaseMapper().selectRZOrgInfo(model.getFinancingCompaniesSeq());
                    //业务表中无工作流id 需要补充
                    LambdaQueryWrapper<FinancingAuditing> queryWrapper1 = new LambdaQueryWrapper<>();
                    queryWrapper1.eq(FinancingAuditing::getPeasantHouseholdId, Long.valueOf(e));
                    queryWrapper1.orderByDesc(BaseEntity::getRecDate);
                    queryWrapper1.last("limit 1");
                    FinancingAuditing financingInfos1 = financingAuditingService.getBaseMapper().selectOne(queryWrapper1);


                    financingInfos.setFinancingCompaniesCode(orgInfo1.getOrDefault("ORG_CODE", "").toString());
                    financingInfos.setFinancingCompaniesName(orgInfo1.getOrDefault("COMPANY_NAME", "").toString());
                    this.updateById(financingInfos);
                    Map<String, Object> map = BeanUtil.beanToMap(financingInfos);
                    map.put("isFlag","0");
                    map.put("instanceId",financingInfos1.getInstanceId());
                    this.execueFlow(map);
                }
            });
        }finally {
            redisLockUtil.releaseLock(lockName);
        }
        return model;
    }

    @Override
    public void rollback(String processId, String peasantHouseholdId) {
        workFlowService.stopProcess(processId);
        LambdaQueryWrapper<FinancingInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FinancingInfo::getPeasantHouseholdId, peasantHouseholdId);
        List<FinancingInfo> financingInfos = this.getBaseMapper().selectList(queryWrapper);

        if (!CollectionUtils.isEmpty(financingInfos)) {
            FinancingInfo financingInfo = financingInfos.get(0);

            LambdaQueryWrapper<FinancingAuditing> wrapper = new LambdaQueryWrapper();
            wrapper.eq(FinancingAuditing::getPeasantHouseholdId,financingInfo.getPeasantHouseholdId());
            financingAuditingService.getBaseMapper().delete(wrapper);

            LambdaQueryWrapper<FinancingRectificationOrder> wrapper1 = new LambdaQueryWrapper();
            wrapper1.eq(FinancingRectificationOrder::getPeasantHouseholdId,financingInfo.getPeasantHouseholdId());
            financingRectificationOrderService.getBaseMapper().delete(wrapper1);

            this.deleteBySeq(financingInfo.getSequenceNbr());
            //停止流程
            ToDoTasks toDoTasks = new ToDoTasks(TaskTypeStationEnum.投融资.getCode(), financingInfo.getPeasantHouseholdId());
            toDoTasksService.completeToDoTasks(toDoTasks,"");
            //生成新增投融资待办
            PeasantHouseholdDto peasantHouseholdDto = peasantHouseholdService.queryBySeq(financingInfo.getPeasantHouseholdId());
            RouthPathVO routhPathVO = new RouthPathVO();
            routhPathVO.setRouthPathId(String.valueOf(financingInfo.getPeasantHouseholdId()));
            String routhPath = toDoTasksService.getRouthPath(TaskTypeStationEnum.投融资.getCode(), HygfRouthTypeEnum.HYGF_XZTSRZ.getCode(), routhPathVO);
            String wxRouthPath = toDoTasksService.getWxRouthPath(TaskTypeStationEnum.投融资.getCode(), HygfRouthTypeEnum.HYGF_XZTSRZ.getCode(), routhPathVO);
            ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.投融资.getCode(),  financingInfo.getPeasantHouseholdId(),   peasantHouseholdDto.getOwnersName()+"待新增推送融资",peasantHouseholdDto.getRegionalCompaniesCode(),routhPath,wxRouthPath);
            String roleId = toDoTasksService.getRoleIdByName("户用光伏-投融");
            List<String> todoUserIds = toDoTasksService.getTodoUserIds(peasantHouseholdDto.getRegionalCompaniesCode(), roleId);
            toDoTasksService.addToDoTasksByUserIds(todoUserIds,toDoTasks1);
        }

    }

    @Override
    public FinancingInfoDto selectDataInfo(Long peasantHouseholdId) {
        FinancingInfoDto financingInfoDto = this.getBaseMapper().selectDataInfo(peasantHouseholdId);
        financingInfoDto.setFiles(JSONArray.parseArray(financingInfoDto.getFile()));
        return financingInfoDto;
    }

    @Override
    public void execueFlow(Map<String, Object> params) {
        LambdaQueryWrapper<FinancingAuditing> query = new LambdaQueryWrapper<>();
        query.eq(FinancingAuditing::getInstanceId, params.get("instanceId").toString());
        query.orderByDesc(BaseEntity::getRecDate);
        query.last("limit 1");
        FinancingAuditing financingAuditing = financingAuditingService.getBaseMapper().selectOne(query);

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

        task.setTaskId(financingAuditing.getNextTaskId());
        HashMap<String, Object> map = new HashMap<>();
        FinancingAuditingDto financingAuditingDto = new FinancingAuditingDto();

        //此处是工作流网关路线原因 相同参数存在工作流不知道怎么执行报错问题 暂未排除问题 先修改不同表达式
        if (params.containsKey("isFlag")) {
            task.setResultCode("isFlag");
            map.put("isFlag", params.get("isFlag"));
            if (params.get("isFlag").equals("1")) {
                params.put("comments", "退回经销商重新验收");
                params.put("approvalStatus",params.getOrDefault("problemDescription",""));
            }else {
                params.put("approvalStatus","");

            }
        } else {
            task.setResultCode("approvalStatus");
            map.put("approvalStatus", params.get("approvalStatus"));
        }
        task.setComment(params.getOrDefault("comments", "").toString());
        task.setVariable(map);
        //执行流程
        ProcessTaskDTO processTaskDTO = workFlowService.complete(financingAuditing.getNextTaskId(), task);
        List<WorkflowResultDto> workflowResultDtos = workFlowService.buildWorkFlowInfo(CollectionUtil.newArrayList(processTaskDTO));
        WorkflowResultDto workflowResultDto = workflowResultDtos.get(0);
        BeanUtils.copyProperties(workflowResultDto, financingAuditingDto);
        financingAuditingDto.setPeasantHouseholdId(financingAuditing.getPeasantHouseholdId());
        financingAuditingDto.setPromoter(financingAuditing.getPromoter());
        if (null == financingAuditingDto.getInstanceId()) {
            financingAuditingDto.setInstanceId(financingAuditing.getInstanceId());
        }
        financingAuditingDto.setStatus(params.getOrDefault("comments", "").toString());
        financingAuditingDto.setNodeRouting(FinancingAuditEnum.getNodeByCode(workflowResultDto.getNextNodeKey()));
        financingAuditingService.createWithModel(financingAuditingDto);

        String nameByCode = FinancingAuditEnum.getNameByCode(workflowResultDto.getNextNodeKey());
        String statusName = nameByCode == null || nameByCode.equals("") ? "放款完成" : nameByCode;

        LambdaQueryWrapper<FinancingInfo> info = new LambdaQueryWrapper<>();
        info.eq(FinancingInfo::getPeasantHouseholdId, financingAuditing.getPeasantHouseholdId());
        FinancingInfo financingInfo = this.getBaseMapper().selectOne(info);
        if (params.containsKey("financingCompaniesSeq") && params.get("financingCompaniesSeq")!= null) {
            financingInfo.setFinancingCompaniesSeq(Long.valueOf(params.get("financingCompaniesSeq").toString()));
            Map<String, Object> orgInfo = this.getBaseMapper().selectRZOrgInfo(Long.valueOf(params.get("financingCompaniesSeq").toString()));
            financingInfo.setFinancingCompaniesName(orgInfo.getOrDefault("COMPANY_NAME", "").toString());
        }
        if("融资审核".equals(financingAuditingDto.getNextNodeName())){
            financingInfo.setTrCreateTime(new Date());
        }
        //标识对于整改待推送状态
        if (params.containsKey("isZG")) {
            financingInfo.setStatus("待推送");
        }else {
            financingInfo.setStatus(statusName);
        }

//        if (params.containsKey("isHistory")) {
//            financingInfo.setStatus("退回建档");
//        }
        if("放款完成".equals(financingInfo.getStatus())){
            financingInfo.setTrEndTime(new Date());
        }
        this.updateById(financingInfo);
        //更新待办
        PeasantHousehold peasantHousehold = peasantHouseholdService.getBaseMapper().selectById(financingAuditing.getPeasantHouseholdId());
        String taskName="您有一条投融资的待办";
        String orgCode="";
        if(Objects.nonNull(peasantHousehold)){
            taskName=peasantHousehold.getOwnersName() + "待" +workflowResultDto.getNextNodeName() ;
            orgCode=peasantHousehold.getRegionalCompaniesCode();
        }
        RouthPathVO routhPathVO = new RouthPathVO();
        routhPathVO.setRouthPathId(String.valueOf(financingAuditing.getPeasantHouseholdId()));
        String routhPath = toDoTasksService.getRouthPath(TaskTypeStationEnum.投融资.getCode(),workflowResultDto.getNextNodeKey(), routhPathVO);
        String wxRouthPath = toDoTasksService.getWxRouthPath(TaskTypeStationEnum.投融资.getCode(),workflowResultDto.getNextNodeKey(), routhPathVO);
        ToDoTasks toDoTasks=  new ToDoTasks (TaskTypeStationEnum.投融资.getCode(),  peasantHousehold.getSequenceNbr(),   taskName,orgCode,routhPath,wxRouthPath);
        if("AbarbeitungWaitPush".equals(workflowResultDto.getNextNodeKey())){
            String roleId = toDoTasksService.getRoleIdByName("户用光伏-投融");
            List<String> todoUserIds = toDoTasksService.getTodoUserIds(peasantHousehold.getRegionalCompaniesCode(), roleId);
            toDoTasksService.completeAndAddToDoTask(todoUserIds,toDoTasks,"");
        }else if("FinancingAudit".equals(workflowResultDto.getNextNodeKey())){
            String roleId = toDoTasksService.getRoleIdByName("户用光伏-融资");
            List<String> userIds = toDoTasksService.getTodoUserIdsByRzjg(financingInfo.getFinancingCompaniesCode(),roleId);
            toDoTasksService.completeAndAddToDoTask(userIds,toDoTasks,"");
        } else if ("AuditPass".equals(workflowResultDto.getNextNodeKey())){
            String routhPath1 = toDoTasksService.getRouthPath(TaskTypeStationEnum.投融资.getCode(), HygfRouthTypeEnum.HYGF_DFK.getCode(), routhPathVO);
            String wxRouthPath1 = toDoTasksService.getWxRouthPath(TaskTypeStationEnum.投融资.getCode(), HygfRouthTypeEnum.HYGF_DFK.getCode(), routhPathVO);
            ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.投融资.getCode(),  peasantHousehold.getSequenceNbr(),   peasantHousehold.getOwnersName()+"待放款",peasantHousehold.getRegionalCompaniesCode(),routhPath1,wxRouthPath1);
            String roleId = toDoTasksService.getRoleIdByName("户用光伏-融资");
            List<String> userIds = toDoTasksService.getTodoUserIdsByRzjg(financingInfo.getFinancingCompaniesCode(),roleId);
            toDoTasksService.completeAndAddToDoTask(userIds,toDoTasks1,"");
        } else if("WaitAbarbeitung".equals(workflowResultDto.getNextNodeKey())){
            ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.投融资.getCode(),  peasantHousehold.getSequenceNbr(),   peasantHousehold.getOwnersName()+"待经销商重新提交验收",peasantHousehold.getRegionalCompaniesCode(),routhPath,wxRouthPath);
            String roleId = toDoTasksService.getRoleIdByName("户用光伏-经销商-工程");
            List<String> todoUserIds = toDoTasksService.getTodoUserIds(peasantHousehold.getRegionalCompaniesCode(), roleId,peasantHousehold.getDeveloperCode());
            toDoTasksService.completeAndAddToDoTask(todoUserIds,toDoTasks1,"");
        } else {
            List<String> userIds = Arrays.asList(Optional.ofNullable(workflowResultDto.getNextExecuteUserIds()).orElse("").split(","));
            List<String> filterUsers = toDoTasksService.filterUsers(TaskTypeStationEnum.投融资.getCode(), workflowResultDto.getNextNodeKey(),userIds, orgCode, peasantHousehold.getDeveloperCode());
            toDoTasksService.completeAndAddToDoTask(filterUsers,toDoTasks,"");
        }
        //节点为待整改时生成整改单
        if (params.containsKey("isFlag") && params.get("isFlag").equals("1") && workflowResultDto.getNextNodeKey().equals(FinancingAuditEnum.待整改.getCode())) {
             if (params.containsKey("isHistory")){

                 LambdaUpdateWrapper<PeasantHousehold> up = new LambdaUpdateWrapper<>();
                 up.set(PeasantHousehold::getPreparationMoneyState,"待提交");
                 up.eq(BaseEntity::getSequenceNbr,financingAuditing.getPeasantHouseholdId());
                 peasantHouseholdService.getBaseMapper().update(null,up);
             }else  if (!params.containsKey("isHistory")){
                 this.sendBack(financingInfo.getPeasantHouseholdId());
             }


//            LambdaQueryWrapper<FinancingRectificationOrder> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.eq(FinancingRectificationOrder::getPeasantHouseholdId, financingInfo.getPeasantHouseholdId());
//            queryWrapper.orderByDesc(BaseEntity::getRecDate);
//            queryWrapper.last("limit 1");
//            FinancingRectificationOrder oldData = financingRectificationOrderService.getBaseMapper().selectOne(queryWrapper);
//
//            FinancingRectificationOrder financingRectificationOrder = new FinancingRectificationOrder();
//            //若存在历史整改单 将历史整改单数据同步至新整改单 便于修改
//            if (ObjectUtils.isNotEmpty(oldData)) {
//                BeanUtils.copyProperties(oldData, financingRectificationOrder);
//                financingRectificationOrder.setSequenceNbr(null);
//                financingRectificationOrder.setCompleteDate(null);
//                financingRectificationOrder.setRectificationPhoto(null);
//            }
//            financingRectificationOrder.setRectificationOrderCode(String.valueOf(new Date().getTime()));
//            financingRectificationOrder.setRectificationStatus("待整改");
//            financingRectificationOrder.setProblemDescription(params.getOrDefault("problemDescription", "").toString());
//            financingRectificationOrder.setPeasantHouseholdName(params.getOrDefault("peasantHouseholdName", "").toString());
//            financingRectificationOrder.setRectificationDescription(params.getOrDefault("rectificationDescription", "").toString());
//            financingRectificationOrder.setPeasantHouseholdId(financingInfo.getPeasantHouseholdId());
//            financingRectificationOrder.setResponsibleUserName(params.getOrDefault("responsibleUserName", "").toString());
//            financingRectificationOrder.setResponsibleUserPhone(params.getOrDefault("responsibleUserPhone", "").toString());
//            financingRectificationOrderService.save(financingRectificationOrder);
        }

    }

    public List<Map<String, Object>> selectOrgList() {
        return this.getBaseMapper().selectOrgList();

    }


    public void sendBack(Long peasantHouseholdId ){
        //投融资表数据
        LambdaUpdateWrapper<FinancingInfo> financingUp = new LambdaUpdateWrapper<>();
        financingUp.eq(FinancingInfo::getPeasantHouseholdId,peasantHouseholdId);
        financingUp.set(FinancingInfo::getStatus,"重新验收");
        this.update(null,financingUp);

        //删除验收审核数据
        LambdaQueryWrapper<AcceptanceCheckAuditing> checkAuditUp = new LambdaQueryWrapper<>();
        checkAuditUp.eq(AcceptanceCheckAuditing::getPeasantHouseholdId,peasantHouseholdId);
        acceptanceCheckAuditingService.getBaseMapper().delete(checkAuditUp);

        //重置验收数据
        LambdaUpdateWrapper<AcceptanceCheck>  checkUp = new LambdaUpdateWrapper<>();
        checkUp.eq(AcceptanceCheck::getPeasantHouseholdId,peasantHouseholdId);
        checkUp.set(AcceptanceCheck::getAcceptanceCheckStatus, GridStatusEnum.WTG.getCode());
        checkUp.set(AcceptanceCheck::getBasicGridNode,null);
        checkUp.set(AcceptanceCheck::getPowerStationFinancingStatus,null);
        checkUp.set(AcceptanceCheck::getPowerStationLegalStatus,null);
        checkUp.set(AcceptanceCheck::getPowerStationAssetsStatus,null);
        checkUp.set(AcceptanceCheck::getPowerStationAreaStatus,null);
        checkUp.set(AcceptanceCheck::getInstanceId,null);
        checkUp.set(AcceptanceCheck::getAcceptanceTime,null);
        acceptanceCheckService.getBaseMapper().update(null,checkUp);

    }


     public  void updateState(List<Long> ids){
        LambdaUpdateWrapper<FinancingInfo> up = new LambdaUpdateWrapper<>();
        up.in(FinancingInfo::getPeasantHouseholdId,ids);
        up.set(FinancingInfo::getStatus,"已放款");
        this.getBaseMapper().update(null,up);

        //完成待放款待办
         if(CollectionUtil.isNotEmpty(ids)){
             for (Long id : ids) {
                 ToDoTasks toDoTasks=new ToDoTasks(TaskTypeStationEnum.投融资.getCode(), id);
                 toDoTasksService.completeToDoTasks(toDoTasks,"");
                 //产生新的放款确认待办
                 PeasantHouseholdDto peasantHouseholdDto = peasantHouseholdService.queryBySeq(id);
                 RouthPathVO routhPathVO = new RouthPathVO();
                 routhPathVO.setRouthPathId(String.valueOf(id));
                 String routhPath = toDoTasksService.getRouthPath(TaskTypeStationEnum.投融资.getCode(), "AuditPass", routhPathVO);
                 String wxRouthPath = toDoTasksService.getWxRouthPath(TaskTypeStationEnum.投融资.getCode(), "AuditPass", routhPathVO);
                 ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.投融资.getCode(), id ,peasantHouseholdDto.getOwnersName()+"待放款确认", peasantHouseholdDto.getRegionalCompaniesCode(),routhPath,wxRouthPath);
                 String roleId = toDoTasksService.getRoleIdByName("户用光伏-投融");
                 List<String> todoUserIds = toDoTasksService.getTodoUserIds(peasantHouseholdDto.getRegionalCompaniesCode(), roleId);
                 toDoTasksService.addToDoTasksByUserIds(todoUserIds,toDoTasks1);
             }

         }

    }

    public void upDateMoney(FinancingInfoDto financingInfoDto) {

        Map<Long, Double> maps = financingInfoDto.getPeasantHouseholds().stream()
                .collect(Collectors.toMap(
                        PeasantHousehold::getSequenceNbr, // key extractor
                        PeasantHousehold::getDisbursementMoney, // value mapper
                        (existingValue, newValue) -> existingValue // merge function
                ));

        LambdaQueryWrapper<FinancingInfo> up = new LambdaQueryWrapper<>();
        up.in(FinancingInfo::getPeasantHouseholdId,maps.keySet());
        List<FinancingInfo> financingInfos = this.getBaseMapper().selectList(up);

        financingInfos.forEach(e->{
            e.setDisbursementMoney(maps.get(e.getPeasantHouseholdId()));
            e.setDisbursementTime(financingInfoDto.getDisbursementTime());
            e.setUnitPrice(financingInfoDto.getUnitPrice());
            if (financingInfoDto.getFiles() != null){
                e.setFile(JSON.toJSONString(financingInfoDto.getFiles()));
            }
            this.getBaseMapper().updateById(e);

            LambdaQueryWrapper<FinancingAuditing> query = new LambdaQueryWrapper<>();
            query.eq(FinancingAuditing::getPeasantHouseholdId, e.getPeasantHouseholdId());
            query.orderByDesc(BaseEntity::getRecDate);
            query.last("limit 1");
            FinancingAuditing financingAuditing = financingAuditingService.getBaseMapper().selectOne(query);

            Map<String, Object> map = BeanUtil.beanToMap(e);
            map.put("approvalStatus","0");
            map.put("instanceId",financingAuditing.getInstanceId());
            this.execueFlow(map);


        });

    }

    public Object orgListByqyid(String peasantHouseholdId) {

        LambdaQueryWrapper<PeasantHousehold> query= new LambdaQueryWrapper<>();
        query.eq(BaseEntity::getSequenceNbr,peasantHouseholdId);
        PeasantHousehold peasantHousehold = peasantHouseholdService.getBaseMapper().selectOne(query);

        LambdaQueryWrapper<FinancingRegional> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FinancingRegional::getRegionalCompaniesSeq,peasantHousehold.getRegionalCompaniesSeq());
        FinancingRegional financingRegional = financingRegionalService.getBaseMapper().selectOne(wrapper);
        if (ObjectUtils.isEmpty(financingRegional)){
            throw new BadRequest("该区域公司尚未绑定融资机构，请绑定后操作");
        }
        List<String> ids = Arrays.asList(financingRegional.getFinancingId().split(","));
        return this.getBaseMapper().orgListByqyid(ids);

    }
}