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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.entity.BaseEntity;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.hygf.api.Enum.*;
import com.yeejoin.amos.boot.module.hygf.api.dto.*;
import com.yeejoin.amos.boot.module.hygf.api.entity.*;
import com.yeejoin.amos.boot.module.hygf.api.mapper.*;
import com.yeejoin.amos.boot.module.hygf.api.service.IPreparationMoneyService;
import com.yeejoin.amos.boot.module.hygf.api.util.NumberUtil;
import com.yeejoin.amos.boot.module.hygf.biz.feign.WorkflowFeignClient;
import com.yeejoin.amos.boot.module.hygf.biz.vo.RouthPathVO;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowBatchDTO;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowStartDTO;
import com.yeejoin.amos.feign.workflow.model.ProcessTaskDTO;
import com.yeejoin.amos.feign.workflow.model.TaskResultDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 发货单服务实现类
 *
 * @author system_generator
 * @date 2023-08-17
 */
@Service
public class PreparationMoneyServiceImpl extends BaseService<PreparationMoneyDto,PreparationMoney,PreparationMoneyMapper> implements IPreparationMoneyService {


    @Autowired
    private PreparationMoneyMapper preparationMoneyMapper;
    @Autowired
    private PowerStationServiceImpl powerStationService;
    @Autowired
    private PeasantHouseholdServiceImpl peasantHouseholdService;
    @Autowired
    private DocumentBomServiceImpl documentBomService;
    @Autowired
    private DocumentStationServiceImpl documentStationService;
    @Autowired
    private AmosRequestContext amosRequestContext;
    @Autowired
    private UnitInfoServiceImpl unitInfoService;
    @Autowired
    private PreparationMoneyLogServiceImpl preparationMoneyLogService;
    @Autowired
    RegionalCompaniesMapper regionalCompaniesMapper;
    @Autowired
    DocumentStationMapper documentStationMapper;
    @Autowired
    RedisUtils redisUtil;
    @Autowired
    DesignInformationMapper designInformationMapper;
    @Autowired
    HouseholdContractMapper householdContractMapper;
    @Autowired
    PowerStationEngineeringInfoMapper powerStationEngineeringInfoMapper;
    @Autowired
    PreparationMoneyLogMapper preparationMoneyLogMapper;
    @Autowired
    PeasantHouseholdMapper peasantHouseholdMapper;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private HygfPreparationMoneyAuditingServiceImpl hygfPreparationMoneyAuditingService;
    @Autowired
    private HygfReplenishmentMapper hygfReplenishmentMapper;
    @Autowired
    private WorkflowFeignClient workflowFeignClient;
    @Autowired
    ToDoTasksServiceImpl toDoTasksServiceImpl;

    private static final String regionRedis = "app_region_redis";
//    private static final String PROCESSKEY = "DeliveryManagement";

    /**
     * 分页查询
     */

    public IPage<PreparationMoney> queryForPreparationMoneyPage(PreparationPageDto dto) {

        //列表数据组装
//        LambdaQueryWrapper<PreparationMoney> qw = new LambdaQueryWrapper<>();
        DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

//      qw.like(StringUtils.isNotEmpty(dto.getConsigneeRegion()), PreparationMoney::getConsigneeRegion, dto.getConsigneeRegion());
//      qw.like(StringUtils.isNotEmpty(dto.getAmosUnitName()), PreparationMoney::getAmosUnitName, dto.getAmosUnitName());
//      qw.like(StringUtils.isNotEmpty(dto.getOddNumbers()), PreparationMoney::getOddNumbers, dto.getOddNumbers());
//      qw.eq(StringUtils.isNotEmpty(dto.getDeliveryState()), PreparationMoney::getDeliveryState, dto.getDeliveryState());
//      qw.eq(StringUtils.isNotEmpty(dto.getAmosUnitId()), PreparationMoney::getAmosUnitId, dto.getAmosUnitId());
//      qw.ne(StringUtils.isNotEmpty(dto.getFlag()),PreparationMoney::getDeliveryState,DeliveryStateeEnum.已作废.getCode());

//        qw.orderBy(Boolean.TRUE, Boolean.FALSE, PreparationMoney::getOrderTime);
        PreparationDto preparationDto = new PreparationDto();
        BeanUtils.copyProperties(dto, preparationDto);
        PageHelper.startPage((int) dto.getCurrent(), (int) dto.getSize());
        List<PreparationMoney> list = preparationMoneyMapper.selectPageList(preparationDto);
        PageInfo<PreparationMoney> page = new PageInfo(list);
        Page<PreparationMoney> pagenew = new Page<PreparationMoney>();
        pagenew.setCurrent(page.getPageNum());
        pagenew.setTotal(page.getTotal());
        pagenew.setSize(page.getSize());
        pagenew.setRecords(page.getList());
        return pagenew;
    }

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

    /**
     * 获取发货单详情 by sequenceNbr
     *
     * @return {@link  PreparationMoneyDto}
     * @throws
     * @author Provence
     */
//    public PreparationMoneyDto getObjectBySequenceNbr(Long sequenceNbr) {
//        PreparationMoneyDto preparationMoneyDto = this.queryBySeq(sequenceNbr);
//        // 加载BOM清单数据
//        preparationMoneyDto.setDocumentBoms(documentBomService.listByPreparationMoneyId(sequenceNbr));
//        // 加载发货电站数据
//        List<Long> peasantHouseholdIds = documentStationService.list(new LambdaQueryWrapper<DocumentStation>()
//                .select(DocumentStation::getStationId)
//                .eq(DocumentStation::getPreparationMoneyId, sequenceNbr))
//                .stream().map(DocumentStation::getStationId).collect(Collectors.toList());
//        List<PeasantHousehold> peasantHouseholds = (List<PeasantHousehold>) peasantHouseholdService.listByIds(peasantHouseholdIds);
//        preparationMoneyDto.setPowerStations(peasantHouseholds.stream().map(o -> entityToDto(o)).collect(Collectors.toList()));
//        // 加载单据追踪数据
//        List<PreparationMoneyLog> preparationMoneyLogDtos = preparationMoneyLogService.list(new LambdaQueryWrapper<PreparationMoneyLog>().eq(PreparationMoneyLog::getPreparationMoneyId, sequenceNbr));
//        preparationMoneyDto.setPreparationMoneyLogs(preparationMoneyLogDtos.stream().map(o -> entityToDto(o)).collect(Collectors.toList()));
//        return preparationMoneyDto;
//    }
    private PeasantHouseholdDto entityToDto(PeasantHousehold o) {
        PeasantHouseholdDto dto = new PeasantHouseholdDto();
        BeanUtils.copyProperties(o, dto);
        return dto;
    }

    private PreparationMoneyLogDto entityToDto(PreparationMoneyLog o) {
        PreparationMoneyLogDto dto = new PreparationMoneyLogDto();
        BeanUtils.copyProperties(o, dto);
        return dto;
    }


    public PreparationMoney selectOnebyId(Long sequenceNbr) {

        LambdaUpdateWrapper<PreparationMoney> qu = new LambdaUpdateWrapper<>();
        qu.eq(PreparationMoney::getSequenceNbr, sequenceNbr);
        PreparationMoney preparationMoney = preparationMoneyMapper.selectOne(qu);
        LambdaUpdateWrapper<DocumentStation> q = new LambdaUpdateWrapper<>();
        q.eq(DocumentStation::getPreparationMoneyId, sequenceNbr);
        List<DocumentStation> li = documentStationMapper.selectList(q);

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

        }

        preparationMoney.setPeasantHouseholdId(li);


        LambdaQueryWrapper<HygfReplenishment> files = new LambdaQueryWrapper<>();
        files.eq(HygfReplenishment::getPreparationMoneyId,sequenceNbr);
        files.orderByDesc(BaseEntity::getRecDate);
        List<HygfReplenishment> hygfReplenishments1 = hygfReplenishmentMapper.selectList(files);

        if (CollectionUtil.isNotEmpty(hygfReplenishments1) && !hygfReplenishments1.isEmpty() ){
            preparationMoney.setFiles(hygfReplenishments1);
        }
        return preparationMoney;

    }


    @Transactional
    public boolean zfPreparationMoney(Long sequenceNbr, AgencyUserModel agencyUserModel) {

        // 记录操作日志
        PreparationMoneyLog preparationMoneyLog = new PreparationMoneyLog();
        preparationMoneyLog.setPreparationMoneyId(sequenceNbr);
        preparationMoneyLog.setOperationContent(PreparationEnum.作废发货单.getCode());
        preparationMoneyLog.setExecutionTime(new Date());
        preparationMoneyLog.setExecutor(agencyUserModel.getRealName());
        preparationMoneyLogService.save(preparationMoneyLog);
        LambdaUpdateWrapper<PreparationMoney> qu = new LambdaUpdateWrapper();
        qu.set(PreparationMoney::getDeliveryState, DeliveryStateeEnum.已作废.getCode());
        qu.eq(PreparationMoney::getSequenceNbr, sequenceNbr);
        return this.update(qu);
    }

    public Map<String, Object> selectOnePreparationMoney(String sequenceNbr) {
        Map<String, Object> map = new HashMap<>();
        LambdaQueryWrapper<PreparationMoney> qu = new LambdaQueryWrapper<>();
        qu.eq(PreparationMoney::getSequenceNbr, sequenceNbr);
        PreparationMoney preparationMoney = preparationMoneyMapper.selectOne(qu);

        LambdaQueryWrapper<HygfPreparationMoneyAuditing> audit = new LambdaQueryWrapper<>();
        audit.eq(HygfPreparationMoneyAuditing::getPreparationMoneyId,sequenceNbr);
        List<HygfPreparationMoneyAuditing> hygfPreparationMoneyAuditings = hygfPreparationMoneyAuditingService.getBaseMapper().selectList(audit);
        if (CollectionUtil.isNotEmpty(hygfPreparationMoneyAuditings) && hygfPreparationMoneyAuditings.size()>0 ){
            if (!StringUtils.isEmpty(hygfPreparationMoneyAuditings.get(0).getInstanceId())) {
                try {
                    Map<String, Object> flowLoggerMap = workflowFeignClient.getFlowLogger(hygfPreparationMoneyAuditings.get(0).getInstanceId()).getResult();
                    List<LinkedHashMap> flowLogger = (List<LinkedHashMap>) flowLoggerMap.get("flowLogger");
                    if (flowLogger.size() > 0) {
                        Collections.reverse(flowLogger);
                    }
                    List<LinkedHashMap> flowLoggernew = new ArrayList<>();
                    for (LinkedHashMap linkedHashMap : flowLogger) {
                        if (linkedHashMap.get("operateDate") != null
                                && !linkedHashMap.get("operateDate").toString().isEmpty()) {
                            LinkedHashMap linke = new LinkedHashMap();
                            linke.put("approvalStatue", linkedHashMap.get("approvalStatue").toString());
                            // 审核意见
                            List<LinkedHashMap> approvalSuggestion = (List<LinkedHashMap>) linkedHashMap.get("approvalSuggestion");
                            if (approvalSuggestion != null && !approvalSuggestion.isEmpty()) {
                                linke.put("approvalSuggestion", approvalSuggestion.get(0).get("message"));
                            }
                            linke.put("taskName", linkedHashMap.get("taskName").toString());
                            linke.put("operator", linkedHashMap.get("operator").toString());
                            linke.put("operateDate", linkedHashMap.get("operateDate").toString());
                            flowLoggernew.add(linke);
                        }
                    }
                    LoggerDto loggerDto = new LoggerDto();
                    loggerDto.setLogger(flowLoggernew);
                    map.put("orderTracking",loggerDto);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }



        LambdaQueryWrapper<DocumentStation> q = new LambdaQueryWrapper<>();
        q.eq(DocumentStation::getPreparationMoneyId, sequenceNbr);
        List<DocumentStation> lih = documentStationMapper.selectList(q);

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

        }




        preparationMoney.setPeasantHouseholdId(lih);

        LambdaUpdateWrapper<PreparationMoneyLog> q1 = new LambdaUpdateWrapper<>();
        q1.eq(PreparationMoneyLog::getPreparationMoneyId, sequenceNbr);
        q1.orderByAsc(PreparationMoneyLog::getExecutionTime);
        List<PreparationMoneyLog> liD = preparationMoneyLogMapper.selectList(q1);
        preparationMoney.setPreparationMoneyLog(liD);


        List<Long> ids = new ArrayList<>();
        for (DocumentStation documentStation : lih) {
            ids.add(documentStation.getStationId());
        }
        //获取所有电站Bom，分组合并，暂时不相加

        QueryWrapper<DesignInformation> designInformationQueryWrapper = new QueryWrapper<>();
        designInformationQueryWrapper.in("peasant_household_id", ids);
        List<DesignInformation> li = designInformationMapper.selectList(designInformationQueryWrapper);
        DesignInformation designInformation = new DesignInformation();
        //组件
        List<Object> assembly = new ArrayList<>();
        //逆变器
        List<Object> inverter = new ArrayList<>();
        //电表箱
        List<Object> electricityMeter = new ArrayList<>();
        //电缆
        List<Object> cable = new ArrayList<>();
        for (DesignInformation des : li) {
            if (des.getAssembly() != null && !des.getAssembly().isEmpty()) {
                assembly.addAll(des.getAssembly());
            }
            if (des.getInverter() != null && !des.getInverter().isEmpty()) {
                inverter.addAll(des.getInverter());
            }
            if (des.getElectricityMeter() != null && !des.getElectricityMeter().isEmpty()) {
                electricityMeter.addAll(des.getElectricityMeter());
            }
            if (des.getCable() != null && !des.getCable().isEmpty()) {
                cable.addAll(des.getCable());
            }
        }
        designInformation.setAssembly(assembly);
        designInformation.setInverter(inverter);
        designInformation.setElectricityMeter(electricityMeter);
        designInformation.setCable(cable);
        Map<String, Object> map2 = Bean.BeantoMap(preparationMoney);

        LambdaQueryWrapper<HygfReplenishment> files = new LambdaQueryWrapper<>();
        files.eq(HygfReplenishment::getPreparationMoneyId,sequenceNbr);
        files.orderByDesc(BaseEntity::getRecDate);
        List<HygfReplenishment> hygfReplenishments = hygfReplenishmentMapper.selectList(files);

        if (CollectionUtil.isNotEmpty(hygfReplenishments) && !hygfReplenishments.isEmpty() ){
            map2.put("files",hygfReplenishments);
        }

        map.put("preparationMoney", map2);
        map.put("designInformation", designInformation);
        Map<String, Object> map1 = new HashMap<>();
        map1.put("preparationMoneyLog", liD);
        map.put("preparationMoneyLog", map1);
        return map;
    }


    /**
     * 保存或更新发货单
     *
     * @param model model
     * @return {@link  PreparationMoneyDto}
     * @throws
     * @author Provence
     */
    @Transactional
    @Override
    public PreparationMoney saveOrUpdateObject(PreparationMoney model, AgencyUserModel agencyUserModel) {

        if (model.getSequenceNbr() == null) {
            //获取经销商单位信息
            UnitInfo unitInfo = unitInfoService.getById(model.getAmosUnitId());
            model.setAmosUnitName(unitInfo != null ? unitInfo.getName() : null);
            model.setAmosUnitOrgCode(unitInfo != null ? unitInfo.getAmosCompanyCode() : null);
            RegionalCompanies regionalCompanies = regionalCompaniesMapper.selectRegionName(model.getRegionalCompaniesSeq());
            model.setRegionalCompaniesCode(regionalCompanies != null ? regionalCompanies.getRegionalCompaniesCode() : null);
            model.setRegionalCompaniesName(regionalCompanies != null ? regionalCompanies.getRegionalCompaniesName() : null);
            //收货区域信息
            JSONArray regionName = getRegionName();
            List<RegionModel> list = JSONArray.parseArray(regionName.toJSONString(), RegionModel.class);
            String ConsigneeRegion = "";
            List<Integer> da = model.getConsigneeRegionCode();
            if (da != null && !da.isEmpty()) {
                for (int i = 0; i < da.size(); i++) {
                    for (RegionModel re : list) {
                        if (re.getRegionCode().equals(Integer.valueOf(da.get(i)))) {
                            if (da.size() - 1 == i) {
                                ConsigneeRegion = ConsigneeRegion + re.getRegionName();
                            } else {
                                ConsigneeRegion = ConsigneeRegion + re.getRegionName() + "-";
                            }
                            break;
                        }
                    }
                }

                model.setConsigneeRegion(ConsigneeRegion);
            }
            //发货单号

            String code = NumberUtil.getCode(CodeEnum.货单.getCode(), regionalCompanies.getCompanyCode(), regionalCompanies.getRegionalAddress());
            model.setOddNumbers(code);

            if (model.getDeliveryFile() != null && !model.getDeliveryFile().isEmpty()) {
                model.setDeliveryState(DeliveryStateeEnum.已发货.getCode());


                model.setArrivalState(ArrivalStateeEnum.待收货.getCode());
                model.setDeliveryTime(new Date());
            } else {
                model.setDeliveryState(DeliveryStateeEnum.待发货.getCode());
                model.setArrivalState(DeliveryStateeEnum.待发货.getCode());
            }

            //更新电站施工状态
            LambdaUpdateWrapper<PeasantHousehold> up = new LambdaUpdateWrapper<>();
            up.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.备货中.getCode());
            List<DocumentStation> idsk = model.getPeasantHouseholdId();
            List<Long> idsH = new ArrayList<>();

            for (DocumentStation documentStation : idsk) {
                idsH.add(documentStation.getStationId());
            }

            up.in(PeasantHousehold::getSequenceNbr, idsH);
            peasantHouseholdMapper.update(null, up);

            preparationMoneyMapper.insert(model);
            //电站信息存储
            List<DocumentStation> ids = model.getPeasantHouseholdId();
            List<DocumentStation> listDocumentStation = new ArrayList<>();
            for (DocumentStation documentStation : ids) {
                documentStation.setPreparationMoneyId(model.getSequenceNbr());
                listDocumentStation.add(documentStation);
            }
            documentStationService.saveBatch(listDocumentStation);

            // 记录操作日志
            PreparationMoneyLog preparationMoneyLog = new PreparationMoneyLog();
            preparationMoneyLog.setPreparationMoneyId(model.getSequenceNbr());
            preparationMoneyLog.setOperationContent(PreparationEnum.创建发货单.getCode());
            preparationMoneyLog.setExecutionTime(new Date());
            preparationMoneyLog.setExecutor(agencyUserModel.getRealName());
            preparationMoneyLogService.save(preparationMoneyLog);
            if (model.getArrivalFile() != null && !model.getArrivalFile().isEmpty()) {
                PreparationMoneyLog preparationMoneyLog1 = new PreparationMoneyLog();
                preparationMoneyLog1.setPreparationMoneyId(model.getSequenceNbr());
                preparationMoneyLog1.setOperationContent(PreparationEnum.确认发货.getCode());
                preparationMoneyLog1.setExecutionTime(new Date());
                preparationMoneyLog1.setExecutor(agencyUserModel.getRealName());
                preparationMoneyLogService.save(preparationMoneyLog1);

            }
        } else {

            //获取经销商单位信息
            UnitInfo unitInfo = unitInfoService.getById(model.getAmosUnitId());
            model.setAmosUnitName(unitInfo != null ? unitInfo.getName() : null);
            model.setAmosUnitOrgCode(unitInfo != null ? unitInfo.getAmosCompanyCode() : null);
            RegionalCompanies regionalCompanies = regionalCompaniesMapper.selectRegionName(model.getRegionalCompaniesSeq());
            model.setRegionalCompaniesCode(regionalCompanies != null ? regionalCompanies.getRegionalCompaniesCode() : null);
            model.setRegionalCompaniesName(regionalCompanies != null ? regionalCompanies.getRegionalCompaniesName() : null);
            //收货区域信息
            JSONArray regionName = getRegionName();
            List<RegionModel> list = JSONArray.parseArray(regionName.toJSONString(), RegionModel.class);
            String ConsigneeRegion = "";
            List<Integer> da = model.getConsigneeRegionCode();
            if (da != null && !da.isEmpty()) {
                for (int i = 0; i < da.size(); i++) {
                    for (RegionModel re : list) {
                        if (re.getRegionCode().equals(Integer.valueOf(da.get(i)))) {
                            if (da.size() - 1 == i) {
                                ConsigneeRegion = ConsigneeRegion + re.getRegionName();
                            } else {
                                ConsigneeRegion = ConsigneeRegion + re.getRegionName() + "-";
                            }
                            break;
                        }
                    }
                }

                model.setConsigneeRegion(ConsigneeRegion);
            }

            if (model.getArrivalFile() != null && !model.getArrivalFile().isEmpty()) {

                model.setDeliveryState(ArrivalStateeEnum.已收货.getCode());

                //更新电站施工状态
                LambdaUpdateWrapper<PeasantHousehold> up = new LambdaUpdateWrapper<>();
                up.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.备货完成.getCode());
                List<DocumentStation> idsk = model.getPeasantHouseholdId();
                List<Long> idsH = new ArrayList<>();

                for (DocumentStation documentStation : idsk) {
                    idsH.add(documentStation.getStationId());
                }

                up.in(PeasantHousehold::getSequenceNbr, idsH);
                peasantHouseholdMapper.update(null, up);

            } else {

                if (model.getDeliveryFile() != null && !model.getDeliveryFile().isEmpty()) {

                    model.setDeliveryState(DeliveryStateeEnum.已发货.getCode());

                    //更新电站施工状态
                    LambdaUpdateWrapper<PeasantHousehold> up = new LambdaUpdateWrapper<>();
                    up.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.备货中.getCode());
                    List<DocumentStation> idsk = model.getPeasantHouseholdId();
                    List<Long> idsH = new ArrayList<>();
                    for (DocumentStation documentStation : idsk) {
                        idsH.add(documentStation.getStationId());
                    }
                    up.in(PeasantHousehold::getSequenceNbr, idsH);
                    peasantHouseholdMapper.update(null, up);

                    model.setArrivalState(ArrivalStateeEnum.待收货.getCode());
                    model.setDeliveryTime(new Date());
                } else {
                    model.setDeliveryState(DeliveryStateeEnum.待发货.getCode());
                    model.setArrivalState(DeliveryStateeEnum.待发货.getCode());
                    //历史电站
                    LambdaQueryWrapper<DocumentStation> up = new LambdaQueryWrapper();
                    up.eq(DocumentStation::getPreparationMoneyId, model.getSequenceNbr());
                    List<DocumentStation> idsk = documentStationMapper.selectList(up);
                    //更新电站施工状态
                    LambdaUpdateWrapper<PeasantHousehold> up1 = new LambdaUpdateWrapper<>();
                    up1.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.勘察完成.getCode());
                    List<Long> idsH = new ArrayList<>();
                    for (DocumentStation documentStation : idsk) {
                        idsH.add(documentStation.getStationId());
                    }
                    up1.in(PeasantHousehold::getSequenceNbr, idsH);
                    peasantHouseholdMapper.update(null, up1);

                    //更新 //新选电站状态
                    LambdaUpdateWrapper<PeasantHousehold> up2 = new LambdaUpdateWrapper<>();
                    up2.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.备货中.getCode());
                    List<DocumentStation> idsk2 = model.getPeasantHouseholdId();
                    List<Long> idsH2 = new ArrayList<>();
                    for (DocumentStation documentStation : idsk2) {
                        idsH2.add(documentStation.getStationId());
                    }
                    up2.in(PeasantHousehold::getSequenceNbr, idsH2);
                    peasantHouseholdMapper.update(null, up2);

                }
            }
            preparationMoneyMapper.updateById(model);
            //电站信息存储
            LambdaUpdateWrapper<DocumentStation> up = new LambdaUpdateWrapper();
            up.eq(DocumentStation::getPreparationMoneyId, model.getSequenceNbr());
            documentStationMapper.delete(up);

            List<DocumentStation> ids = model.getPeasantHouseholdId();
            List<DocumentStation> listDocumentStation = new ArrayList<>();
            for (DocumentStation documentStation : ids) {
                documentStation.setPreparationMoneyId(model.getSequenceNbr());
                listDocumentStation.add(documentStation);
            }

            documentStationService.saveBatch(listDocumentStation);

            // 记录操作日志
            if (model.getArrivalFile() != null && !model.getArrivalFile().isEmpty()) {
                PreparationMoneyLog preparationMoneyLog1 = new PreparationMoneyLog();
                preparationMoneyLog1.setPreparationMoneyId(model.getSequenceNbr());
                preparationMoneyLog1.setOperationContent(PreparationEnum.确认收货.getCode());
                preparationMoneyLog1.setExecutionTime(new Date());
                preparationMoneyLog1.setExecutor(agencyUserModel.getRealName());
                preparationMoneyLogService.save(preparationMoneyLog1);
            } else {
                PreparationMoneyLog preparationMoneyLog2 = new PreparationMoneyLog();
                preparationMoneyLog2.setPreparationMoneyId(model.getSequenceNbr());
                if (model.getDeliveryFile() != null && !model.getDeliveryFile().isEmpty()) {
                    preparationMoneyLog2.setOperationContent(PreparationEnum.确认发货.getCode());
                } else {
                    preparationMoneyLog2.setOperationContent(PreparationEnum.编辑货单.getCode());
                }

                preparationMoneyLog2.setExecutionTime(new Date());
                preparationMoneyLog2.setExecutor(agencyUserModel.getRealName());
                preparationMoneyLogService.save(preparationMoneyLog2);

            }
        }

        return model;
    }

    public PreparationMoney saveOrUpdateObjectNew(PreparationMoney model, AgencyUserModel agencyUserModel, String isSubmit) {
        if (null == model.getRegionalCompaniesSeq()){
            throw new BadRequest("区域公司不可为空");
        }
        if (null == model.getAmosUnitId()){
            throw new BadRequest("经销商不可为空");
        }

        if (model.getSequenceNbr() == null) {
            //获取经销商单位信息
            UnitInfo unitInfo = unitInfoService.getById(model.getAmosUnitId());
            model.setAmosUnitName(unitInfo != null ? unitInfo.getName() : null);
            model.setAmosUnitOrgCode(unitInfo != null ? unitInfo.getAmosCompanyCode() : null);
            RegionalCompanies regionalCompanies = regionalCompaniesMapper.selectRegionName(model.getRegionalCompaniesSeq());
            model.setRegionalCompaniesCode(regionalCompanies != null ? regionalCompanies.getRegionalCompaniesCode() : null);
            model.setRegionalCompaniesName(regionalCompanies != null ? regionalCompanies.getRegionalCompaniesName() : null);
            //收货区域信息
            JSONArray regionName = getRegionName();
            List<RegionModel> list = JSONArray.parseArray(regionName.toJSONString(), RegionModel.class);
            String ConsigneeRegion = "";
            List<Integer> da = model.getConsigneeRegionCode();
            if (da != null && !da.isEmpty()) {
                for (int i = 0; i < da.size(); i++) {
                    for (RegionModel re : list) {
                        if (re.getRegionCode().equals(Integer.valueOf(da.get(i)))) {
                            if (da.size() - 1 == i) {
                                ConsigneeRegion = ConsigneeRegion + re.getRegionName();
                            } else {
                                ConsigneeRegion = ConsigneeRegion + re.getRegionName() + "-";
                            }
                            break;
                        }
                    }
                }

                model.setConsigneeRegion(ConsigneeRegion);
            }
            //发货单号

            String code = NumberUtil.getCode(CodeEnum.货单.getCode(), regionalCompanies.getCompanyCode(), regionalCompanies.getRegionalAddress());
            model.setOddNumbers(code);



            //更新电站施工状态
            LambdaUpdateWrapper<PeasantHousehold> up = new LambdaUpdateWrapper<>();
            preparationMoneyMapper.insert(model);
            List<DocumentStation> ids = model.getPeasantHouseholdId();
            if (isSubmit.equals("0")) {
                if (CollUtil.isEmpty(ids) && ids.isEmpty() ){
                    throw new BadRequest("提交时选择电站不可为空");
                }
                up.set(PeasantHousehold::getPreparationMoneyState, ArrivalStateeEnum.待收货.getCode());
                up.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.待收货.getCode());
                //开启工作流 并执行一步
                ActWorkflowBatchDTO actWorkflowBatchDTO = new ActWorkflowBatchDTO();
                List<ActWorkflowStartDTO> params = new ArrayList<>();
                ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
                dto.setProcessDefinitionKey(BusinessTypeEnum.HYGF_FHGL.getCode());
                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);
                HygfPreparationMoneyAuditingDto hygfPreparationMoneyAuditingDto = new HygfPreparationMoneyAuditingDto();
                BeanUtils.copyProperties(workflowResultDto, hygfPreparationMoneyAuditingDto);
                hygfPreparationMoneyAuditingDto.setPreparationMoneyId(model.getSequenceNbr());
                hygfPreparationMoneyAuditingDto.setPromoter(RequestContext.getExeUserId());
                hygfPreparationMoneyAuditingService.createWithModel(hygfPreparationMoneyAuditingDto);
                //完成新增待办
                ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.发货.getCode(), HygfRouthTypeEnum.HYGF_XZFHD.getBusiness());
                toDoTasksServiceImpl.completeToDoTasks(toDoTasks1,"");
                //发起待办
                String taskName="";
                if (CollectionUtil.isNotEmpty(ids)){
                    taskName="[";
                    for (DocumentStation documentStation : ids) {
                        taskName= taskName + documentStation.getOwnersName() + ",";
                    }
                    taskName= taskName.substring(0,taskName.length()-1)+"]";
                }
                RouthPathVO routhPathVO = new RouthPathVO();
                routhPathVO.setRouthPathId(String.valueOf(model.getSequenceNbr()));
                String routhPath = toDoTasksServiceImpl.getRouthPath(TaskTypeStationEnum.发货.getCode(), workflowResultDto.getNextNodeKey(), routhPathVO);
                String wxRouthPath = toDoTasksServiceImpl.getWxRouthPath(TaskTypeStationEnum.发货.getCode(), workflowResultDto.getNextNodeKey(), routhPathVO);
                ToDoTasks toDoTasks=  new ToDoTasks (TaskTypeStationEnum.发货.getCode(),  model.getSequenceNbr(),   taskName+"待确认收货单",model.getRegionalCompaniesCode(),routhPath,wxRouthPath);
                List<String> userIds = Arrays.asList(Optional.ofNullable(workflowResultDto.getNextExecuteUserIds()).orElse("").split(","));
                List<String> filterUsers = toDoTasksServiceImpl.filterUsers(TaskTypeStationEnum.发货.getCode(), workflowResultDto.getNextNodeKey(),userIds, model.getRegionalCompaniesCode(), model.getAmosUnitOrgCode());
                toDoTasksServiceImpl.addToDoTasksByUserIds(filterUsers,toDoTasks);
                //提交时 赋值发货时间及订单状态
                model.setDeliveryTime(new Date());
                model.setDeliveryState(DeliveryStateeEnum.已发货.getName());
                model.setArrivalState(ArrivalStateeEnum.待收货.getName());
                model.setOrderStatus(DeliveryStateeEnum.待确认.getName());
            } else {
                up.set(PeasantHousehold::getConstructionState, DeliveryStateeEnum.暂存发货.getCode());
                up.set(PeasantHousehold::getPreparationMoneyState, DeliveryStateeEnum.暂存发货.getCode());
                model.setOrderStatus(DeliveryStateeEnum.待提交.getName());
            }
            //电站信息存储
            if (CollectionUtil.isNotEmpty(ids) && ids.size()>0){
                List<DocumentStation> listDocumentStation = new ArrayList<>();
                List<Long> idsH = new ArrayList<>();

                for (DocumentStation documentStation : ids) {
                    documentStation.setPreparationMoneyId(model.getSequenceNbr());
                    documentStation.setSequenceNbr(null);
                    idsH.add(documentStation.getStationId());
                    listDocumentStation.add(documentStation);
                }
                up.in(PeasantHousehold::getSequenceNbr, idsH);
                peasantHouseholdMapper.update(null, up);
                documentStationService.saveBatch(listDocumentStation);
            }
            preparationMoneyMapper.updateById(model);



        } else {
            //获取经销商单位信息
            UnitInfo unitInfo = unitInfoService.getById(model.getAmosUnitId());
            model.setAmosUnitName(unitInfo != null ? unitInfo.getName() : null);
            model.setAmosUnitOrgCode(unitInfo != null ? unitInfo.getAmosCompanyCode() : null);
            RegionalCompanies regionalCompanies = regionalCompaniesMapper.selectRegionName(model.getRegionalCompaniesSeq());
            model.setRegionalCompaniesCode(regionalCompanies != null ? regionalCompanies.getRegionalCompaniesCode() : null);
            model.setRegionalCompaniesName(regionalCompanies != null ? regionalCompanies.getRegionalCompaniesName() : null);
            //收货区域信息
            JSONArray regionName = getRegionName();
            List<RegionModel> list = JSONArray.parseArray(regionName.toJSONString(), RegionModel.class);
            String ConsigneeRegion = "";
            List<Integer> da = model.getConsigneeRegionCode();
            if (da != null && !da.isEmpty()) {
                for (int i = 0; i < da.size(); i++) {
                    for (RegionModel re : list) {
                        if (re.getRegionCode().equals(Integer.valueOf(da.get(i)))) {
                            if (da.size() - 1 == i) {
                                ConsigneeRegion = ConsigneeRegion + re.getRegionName();
                            } else {
                                ConsigneeRegion = ConsigneeRegion + re.getRegionName() + "-";
                            }
                            break;
                        }
                    }
                }

                model.setConsigneeRegion(ConsigneeRegion);
            }
            List<DocumentStation> ids = model.getPeasantHouseholdId();
            LambdaUpdateWrapper<PeasantHousehold> up = new LambdaUpdateWrapper<>();
            if (isSubmit.equals("0")) {
                if (CollUtil.isEmpty(ids) && ids.isEmpty() ){
                    throw new BadRequest("提交时选择电站不可为空");
                }
//                LambdaUpdateWrapper<PeasantHousehold> up1 = new LambdaUpdateWrapper<>();
                //更新电站施工状态
                up.set(PeasantHousehold::getPreparationMoneyState, ArrivalStateeEnum.待收货.getCode());
                up.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.待收货.getCode());
                //提交时 赋值发货时间及订单状态
                model.setDeliveryTime(new Date());
                model.setOrderStatus(DeliveryStateeEnum.待确认.getName());
                model.setDeliveryState(DeliveryStateeEnum.已发货.getCode());

                //开启工作流 并执行一步
                ActWorkflowBatchDTO actWorkflowBatchDTO = new ActWorkflowBatchDTO();
                List<ActWorkflowStartDTO> params = new ArrayList<>();
                ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
                dto.setProcessDefinitionKey(BusinessTypeEnum.HYGF_FHGL.getCode());
                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);
                HygfPreparationMoneyAuditingDto hygfPreparationMoneyAuditingDto = new HygfPreparationMoneyAuditingDto();
                BeanUtils.copyProperties(workflowResultDto, hygfPreparationMoneyAuditingDto);
                hygfPreparationMoneyAuditingDto.setPreparationMoneyId(model.getSequenceNbr());
                hygfPreparationMoneyAuditingDto.setPromoter(RequestContext.getExeUserId());
                hygfPreparationMoneyAuditingService.createWithModel(hygfPreparationMoneyAuditingDto);
                //完成新增待办
                ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.发货.getCode(), HygfRouthTypeEnum.HYGF_XZFHD.getBusiness());
                toDoTasksServiceImpl.completeToDoTasks(toDoTasks1,"");
                //发起待办
                String taskName="";
                if (CollectionUtil.isNotEmpty(ids)){
                    taskName="[";
                    for (DocumentStation documentStation : ids) {
                        taskName= taskName + documentStation.getOwnersName() + ",";
                    }
                    taskName= taskName.substring(0,taskName.length()-1)+"]";
                }
                RouthPathVO routhPathVO = new RouthPathVO();
                routhPathVO.setRouthPathId(String.valueOf(model.getSequenceNbr()));
                String routhPath = toDoTasksServiceImpl.getRouthPath(TaskTypeStationEnum.发货.getCode(),workflowResultDto.getNextNodeKey(), routhPathVO);
                String wxRouthPath = toDoTasksServiceImpl.getWxRouthPath(TaskTypeStationEnum.发货.getCode(),workflowResultDto.getNextNodeKey(), routhPathVO);
                ToDoTasks toDoTasks=  new ToDoTasks (TaskTypeStationEnum.发货.getCode(),  model.getSequenceNbr(),   taskName+"待确认收货单",model.getRegionalCompaniesCode(),routhPath,wxRouthPath);
                List<String> userIds = Arrays.asList(Optional.ofNullable(workflowResultDto.getNextExecuteUserIds()).orElse("").split(","));
                List<String> filterUsers = toDoTasksServiceImpl.filterUsers(TaskTypeStationEnum.发货.getCode(), workflowResultDto.getNextNodeKey(),userIds, model.getRegionalCompaniesCode(), model.getAmosUnitOrgCode());
                toDoTasksServiceImpl.addToDoTasksByUserIds(filterUsers,toDoTasks);
            }else {
                up.set(PeasantHousehold::getPreparationMoneyState, DeliveryStateeEnum.暂存发货.getCode());
                up.set(PeasantHousehold::getConstructionState, DeliveryStateeEnum.暂存发货.getCode());
            }

            preparationMoneyMapper.updateById(model);
            //电站信息存储
            LambdaQueryWrapper<DocumentStation> query1 = new LambdaQueryWrapper<>();
            query1.eq(DocumentStation::getPreparationMoneyId, model.getSequenceNbr());
            List<Long> oldIds = documentStationMapper.selectList(query1).stream().map(DocumentStation::getStationId).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(oldIds)){
                LambdaUpdateWrapper<PeasantHousehold> up1 = new LambdaUpdateWrapper<>();
                up1.in(BaseEntity::getSequenceNbr,oldIds);
                up1.set(PeasantHousehold::getPreparationMoneyState, DeliveryStateeEnum.待发货.getCode());
                up1.set(PeasantHousehold::getConstructionState, "勘察完成");
                peasantHouseholdMapper.update(null, up1);

                LambdaUpdateWrapper<DocumentStation> up3 = new LambdaUpdateWrapper();
                up3.eq(DocumentStation::getPreparationMoneyId, model.getSequenceNbr());
                documentStationMapper.delete(up3);

            }

            //电站信息存储
            if (CollectionUtil.isNotEmpty(ids) && ids.size()>0){
                List<DocumentStation> listDocumentStation = new ArrayList<>();
                List<Long> idsH = new ArrayList<>();
                for (DocumentStation documentStation : ids) {
                    documentStation.setPreparationMoneyId(model.getSequenceNbr());
                    documentStation.setSequenceNbr(null);
                    idsH.add(documentStation.getStationId());
                    listDocumentStation.add(documentStation);
                }
                up.in(PeasantHousehold::getSequenceNbr, idsH);
                peasantHouseholdMapper.update(null, up);
                documentStationService.saveBatch(listDocumentStation);
            }
        }

        return model;
    }

    private DocumentStation buildDocumentStations(Long sequenceNbr, PeasantHouseholdDto dto) {
        String recUserId = amosRequestContext.getUserId();
        String recUserName = amosRequestContext.getUserName();
        DocumentStation documentStation = new DocumentStation();
        documentStation.setPreparationMoneyId(sequenceNbr);
        documentStation.setStationId(dto.getSequenceNbr());
        documentStation.setRecUserId(recUserId);
        documentStation.setRecUserName(recUserName);
        return documentStation;
    }

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

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

    /**
     * 更新发货单状态
     *
     * @param sequenceNbr   发货单ID
     * @param operationType 操作类型(RECEIPT-确认收货, DELIVERY-发货, DISCARD-废弃)
     * @return {@link  Boolean}
     * @throws
     * @author Provence
     */
    @Override
    public Boolean updatePreparationMoneyStatus(Long sequenceNbr, String operationType) {
//        PreparationMoney preparationMoney =  preparationMoneyMapper.selectById(sequenceNbr);
//        if (preparationMoney ==  null) {
//            throw new BadRequest("订单不存在");
//        }
//        PreparationMoneyLog preparationMoneyLog = new PreparationMoneyLog();
//        preparationMoneyLog.setPreparationMoneyId(preparationMoney.getSequenceNbr());
//        switch (operationType) {
//            case "RECEIPT":
//                // 确认收货 -> 到货状态 -> 已到货 -> 订单状态改为 已完成
//                if (!PreparationMoneyEnum.SHIPMENT_STATUS.已发货.getName().equals(preparationMoney.getShipmentStatus())) {
//                    throw new BadRequest("订单未发货, 无法确认收货");
//                }
//                preparationMoney.setReceivingStatus(PreparationMoneyEnum.RECEIVING_STATUS.已到货.getName());
//                preparationMoney.setDocumentState(PreparationMoneyEnum.DOCUMENT_STATE.已完成.getName());
//                preparationMoney.setDeliveryTime(new Date());
//                preparationMoneyLog.setOperationContent(String.format("备货单确认收货【备货单号:%s】", preparationMoney.getOddNumbers()));
//                break;
//            case "DELIVERY":
//                // 发货 -> 发货状态 -> 已发货
//                preparationMoney.setShipmentStatus(PreparationMoneyEnum.SHIPMENT_STATUS.已发货.getName());
//                preparationMoneyLog.setOperationContent(String.format("备货单发货【备货单号:%s】", preparationMoney.getOddNumbers()));
//                break;
//            case "DISCARD":
//                // 作废
//                // 订单状态 -> 已废弃
//                if (PreparationMoneyEnum.RECEIVING_STATUS.已到货.getName().equals(preparationMoney.getReceivingStatus())) {
//                    throw new BadRequest("订单已到货, 无法作废");
//                }
//                preparationMoney.setDocumentState(PreparationMoneyEnum.DOCUMENT_STATE.作废.getName());
//                preparationMoneyLog.setOperationContent(String.format("备货单作废【备货单号:%s】", preparationMoney.getOddNumbers()));
//                break;
//            default:
//                break;
//        }
//        preparationMoneyLogService.save(preparationMoneyLog);
//        return preparationMoneyMapper.updateById(preparationMoney) > 0;
        return false;
    }

    /**
     * 根据前端选择的发货电站ID列表计算BOM清单价格
     *
     * @param powerHouseholdIds 发货电站ID
     * @return {@link  PreparationMoneyDto}
     * @throws
     * @author Provence
     */
    public PreparationMoneyDto caculateShippingPriceByPowerHouseHoldIds(List<Long> powerHouseholdIds) {
        List<DocumentBom> documentBoms = documentBomService.assembleDocumentBom(powerHouseholdIds);
        return caculateShippingPrice(documentBoms);
    }

    /**
     * 根据前端选择的发货电站ID列表计算BOM清单价格
     *
     * @param documentBoms BOM清单
     * @return {@link  PreparationMoneyDto}
     * @throws
     * @author Provence
     */
    public PreparationMoneyDto caculateShippingPrice(List<DocumentBom> documentBoms) {
        // 获取BOM清单数据
//        // 单价 * 经销商折扣 * 促销 * 需求数量
//        BigDecimal totalPrice = new BigDecimal(0);
//        BigDecimal totaldemandNumber = new BigDecimal(0);
//        for (DocumentBom documentBom : documentBoms) {
//            BigDecimal unitPrice = new BigDecimal(documentBom.getUnitPrice() == null?0:documentBom.getUnitPrice());//单价
//            BigDecimal demandNumber = new BigDecimal(documentBom.getDemandNumber());//需求数量
//            totalPrice = totalPrice.add(unitPrice.multiply(demandNumber));
//            totaldemandNumber = totaldemandNumber.add(demandNumber);
//        }
//        PreparationMoneyDto preparationMoneyDto = new PreparationMoneyDto();
//        preparationMoneyDto.setInventoryPrice(totalPrice.divide(totaldemandNumber).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());//清单价格
//        preparationMoneyDto.setDiscount(0D);//折扣
//        preparationMoneyDto.setPromotion(0D);//促销
//        preparationMoneyDto.setContractPrice(0D);//合同价格 == 确认
//        preparationMoneyDto.setTotalPrice(totalPrice.doubleValue());
        //      return preparationMoneyDto;
        return null;
    }


    @Transactional
    public void uploadVoucher(PreparationMoney model, String instanceId, String isSubmit) {
        //经销商暂存则只更新发货单属性 不进行业务推动
        if ("1".equals(isSubmit)) {
            preparationMoneyMapper.updateById(model);
        } else {
            model.setDeliveryState(ArrivalStateeEnum.已收货.getCode());
            model.setOrderStatus(DeliveryStateeEnum.待审核.getName());
            //更新电站施工状态
            LambdaUpdateWrapper<PeasantHousehold> up = new LambdaUpdateWrapper<>();
            up.set(PeasantHousehold::getPreparationMoneyState, ArrivalStateeEnum.已收货.getName());
            up.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.已收货.getName());
            List<DocumentStation> idsk = model.getPeasantHouseholdId();
            List<Long> idsH = new ArrayList<>();

            for (DocumentStation documentStation : idsk) {
                idsH.add(documentStation.getStationId());
            }
            if (CollectionUtil.isNotEmpty(idsH)){
                up.in(PeasantHousehold::getSequenceNbr, idsH);
                peasantHouseholdMapper.update(null, up);
            }
            preparationMoneyMapper.updateById(model);

            //执行工作流并保存记录 上传收货走入下一节点 表达式=0
            this.wofkflowExcute(instanceId, "0","",model);
        }
    }

    public void excuteFlow( String instanceId, Map<String, Object> kv,Long sequenceNbr) {

        PreparationMoney model = preparationMoneyMapper.selectById(sequenceNbr);

        model.setDeliveryState(ArrivalStateeEnum.已收货.getCode());
        //更新电站施工状态
        LambdaUpdateWrapper<PeasantHousehold> up = new LambdaUpdateWrapper<>();

        List<Long> idsH = new ArrayList<>();

        LambdaQueryWrapper<DocumentStation> stations = new LambdaQueryWrapper<>();
        stations.eq(DocumentStation::getPreparationMoneyId,model.getSequenceNbr());
        List<DocumentStation> documentStations = documentStationMapper.selectList(stations);
        String taskName= "";
        if(CollectionUtil.isNotEmpty(documentStations)){
            taskName = "[";
            for (DocumentStation documentStation : documentStations) {
                idsH.add(documentStation.getStationId());
                taskName= taskName + documentStation.getOwnersName() + ",";
            }
            taskName= taskName.substring(0,taskName.length()-1)+"]";
        }
        if (kv.getOrDefault("approvalStatus", "").equals("0")) {
            up.set(PeasantHousehold::getPreparationMoneyState, ArrivalStateeEnum.备货完成.getName());
            up.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.备货完成.getName());
            model.setOrderStatus(DeliveryStateeEnum.已完成.getName());
            model.setArrivalTime(new Date());
            //生成施工待办
            RouthPathVO routhPathVO = new RouthPathVO();
            String routhPath = toDoTasksServiceImpl.getRouthPath(TaskTypeStationEnum.施工.getCode(), HygfRouthTypeEnum.HYGF_XZPGD.getCode(), routhPathVO);
            String wxRouthPath = toDoTasksServiceImpl.getWxRouthPath(TaskTypeStationEnum.施工.getCode(), HygfRouthTypeEnum.HYGF_XZPGD.getCode(), routhPathVO);
            ToDoTasks toDoTasks=  new ToDoTasks (TaskTypeStationEnum.施工.getCode(),  HygfRouthTypeEnum.HYGF_XZPGD.getBusiness(),   taskName+"待新增派工单",model.getRegionalCompaniesCode(),routhPath,wxRouthPath);
            String roleId = toDoTasksServiceImpl.getRoleIdByName("户用光伏-经销商-工程");
            List<String> todoUserIds = toDoTasksServiceImpl.getTodoUserIds(model.getRegionalCompaniesCode(), roleId,String.valueOf(model.getAmosUnitOrgCode()));
            toDoTasksServiceImpl.addToDoTasksByUserIds(todoUserIds,toDoTasks);
        } else if (kv.getOrDefault("approvalStatus", "").equals("1")) {
            up.set(PeasantHousehold::getPreparationMoneyState, ArrivalStateeEnum.待收货.getName());
            up.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.待收货.getName());
            model.setArrivalState(ArrivalStateeEnum.待收货.getName());
            model.setDeliveryState(DeliveryStateeEnum.已发货.getName());
            model.setOrderStatus(DeliveryStateeEnum.待确认.getName());
        }
        if (CollectionUtil.isNotEmpty(idsH)){
            up.in(PeasantHousehold::getSequenceNbr, idsH);
            peasantHouseholdMapper.update(null, up);
        }

        //更新发货单信息
        preparationMoneyMapper.updateById(model);

        //执行工作流并保存记录
        this.wofkflowExcute(instanceId, kv.getOrDefault("approvalStatus", "").toString(),kv.getOrDefault("approvalStatus","").toString(),model);
    }


    public void wofkflowExcute(String instanceId, String approvalStatus,String comment,Object model) {
        LambdaQueryWrapper<HygfPreparationMoneyAuditing> query = new LambdaQueryWrapper<>();
        query.eq(HygfPreparationMoneyAuditing::getInstanceId, instanceId);
        query.orderByDesc(BaseEntity::getRecDate);
        query.last("limit 1");
        HygfPreparationMoneyAuditing hygfPreparationMoneyAuditing = hygfPreparationMoneyAuditingService.getBaseMapper().selectOne(query);

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

        task.setTaskId(hygfPreparationMoneyAuditing.getNextTaskId());
        HashMap<String, Object> map = new HashMap<>();
        HygfPreparationMoneyAuditingDto preparationMoneyAuditpDto = new HygfPreparationMoneyAuditingDto();
        task.setResultCode("approvalStatus");
        map.put("approvalStatus", approvalStatus);
        task.setComment(comment == null?"":comment);
        task.setVariable(map);
        //执行流程
        ProcessTaskDTO processTaskDTO = workFlowService.complete(hygfPreparationMoneyAuditing.getNextTaskId(), task);
        List<WorkflowResultDto> workflowResultDtos = workFlowService.buildWorkFlowInfo(CollectionUtil.newArrayList(processTaskDTO));
        WorkflowResultDto workflowResultDto = workflowResultDtos.get(0);
        if( model instanceof PreparationMoney){
            PreparationMoney preparationMoney = (PreparationMoney) model;
            //更新待办
            String taskName="";
            LambdaQueryWrapper<DocumentStation> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DocumentStation::getPreparationMoneyId,preparationMoney.getSequenceNbr());
            List<DocumentStation> documentStations = documentStationMapper.selectList(wrapper);
            if (CollectionUtil.isNotEmpty(documentStations)){
                taskName="[";
                for (DocumentStation documentStation : documentStations) {
                    taskName= taskName + documentStation.getOwnersName() + ",";
                }
                taskName= taskName.substring(0,taskName.length()-1)+"]";
            }
            if("fh_sqbh".equals(workflowResultDto.getNextNodeKey())){
                taskName= taskName + "待申请补货确认";
            }else {
                taskName= taskName + preparationMoney.getOrderStatus()+"收货单";
            }
            RouthPathVO routhPathVO = new RouthPathVO();
            routhPathVO.setRouthPathId(String.valueOf(preparationMoney.getSequenceNbr()));
            String routhPath = toDoTasksServiceImpl.getRouthPath(TaskTypeStationEnum.发货.getCode(),workflowResultDto.getNextNodeKey(), routhPathVO);
            String wxRouthPath = toDoTasksServiceImpl.getWxRouthPath(TaskTypeStationEnum.发货.getCode(),workflowResultDto.getNextNodeKey(), routhPathVO);
            ToDoTasks toDoTasks=  new ToDoTasks (TaskTypeStationEnum.发货.getCode(),  preparationMoney.getSequenceNbr(), taskName,preparationMoney.getRegionalCompaniesCode(),routhPath,wxRouthPath);
            List<String> userIds = Arrays.asList(Optional.ofNullable(workflowResultDto.getNextExecuteUserIds()).orElse("").split(","));
            List<String> filterUsers = toDoTasksServiceImpl.filterUsers(TaskTypeStationEnum.发货.getCode(), workflowResultDto.getNextNodeKey(),userIds, preparationMoney.getRegionalCompaniesCode(), preparationMoney.getAmosUnitOrgCode());
            toDoTasksServiceImpl.completeAndAddToDoTask(filterUsers,toDoTasks,"");
        }
        BeanUtils.copyProperties(workflowResultDto, preparationMoneyAuditpDto);
        preparationMoneyAuditpDto.setPreparationMoneyId(hygfPreparationMoneyAuditing.getPreparationMoneyId());
        preparationMoneyAuditpDto.setPromoter(hygfPreparationMoneyAuditing.getPromoter());
        if (null == preparationMoneyAuditpDto.getInstanceId()) {
            preparationMoneyAuditpDto.setInstanceId(hygfPreparationMoneyAuditing.getInstanceId());
        }
        hygfPreparationMoneyAuditingService.createWithModel(preparationMoneyAuditpDto);
    }


    public void replenishmentSubmit(Long preparationMoneyId) {
        LambdaQueryWrapper<HygfPreparationMoneyAuditing> lambda = new LambdaQueryWrapper();
        lambda.eq(HygfPreparationMoneyAuditing::getPreparationMoneyId, preparationMoneyId);
        lambda.orderByDesc(BaseEntity::getRecDate);
        lambda.last("Limit 1");
        HygfPreparationMoneyAuditing auditing = hygfPreparationMoneyAuditingService.getBaseMapper().selectOne(lambda);

        PreparationMoney preparationMoney = preparationMoneyMapper.selectById(preparationMoneyId);
        preparationMoney.setOrderStatus("申请补货");
        preparationMoneyMapper.updateById(preparationMoney);
        this.wofkflowExcute(auditing.getInstanceId(), "1","",preparationMoney);
    }


    @Transactional
    public void replenishmentRollback(Long sequenceNbr) {
        LambdaQueryWrapper<HygfPreparationMoneyAuditing> lambda = new LambdaQueryWrapper();
        lambda.eq(HygfPreparationMoneyAuditing::getPreparationMoneyId, sequenceNbr);
        lambda.orderByDesc(BaseEntity::getRecDate);
        lambda.last("Limit 1");
        HygfPreparationMoneyAuditing hygfPreparationMoneyAuditing = hygfPreparationMoneyAuditingService.getBaseMapper().selectOne(lambda);


        //将发货单状态修改
        PreparationMoney preparationMoney = preparationMoneyMapper.selectById(sequenceNbr);
        preparationMoney.setOrderStatus(DeliveryStateeEnum.待确认.getName());
        preparationMoneyMapper.updateById(preparationMoney);

        //撤回工作流并创建记录
        ProcessTaskDTO processTaskDTO = workFlowService.rollBackTask(hygfPreparationMoneyAuditing.getInstanceId());
        List<WorkflowResultDto> workflowResultDtos = workFlowService.buildWorkFlowInfo(CollectionUtil.newArrayList(processTaskDTO));
        WorkflowResultDto workflowResultDto = workflowResultDtos.get(0);
        workflowResultDto.setInstanceId(hygfPreparationMoneyAuditing.getInstanceId());

        //更新待办
        String taskName="";
        LambdaQueryWrapper<DocumentStation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocumentStation::getPreparationMoneyId,preparationMoney.getSequenceNbr());
        List<DocumentStation> documentStations = documentStationMapper.selectList(wrapper);
        if (CollectionUtil.isNotEmpty(documentStations)){
            taskName="[";
            for (DocumentStation documentStation : documentStations) {
                taskName= taskName + documentStation.getOwnersName() + ",";
            }
            taskName= taskName.substring(0,taskName.length()-1)+"]";
        }
        if("fh_sqbh".equals(workflowResultDto.getNextNodeKey())){
            taskName= taskName + "待申请补货确认";
        }else {
            taskName= taskName + preparationMoney.getOrderStatus()+"收货单";
        }
        RouthPathVO routhPathVO = new RouthPathVO();
        routhPathVO.setRouthPathId(String.valueOf(preparationMoney.getSequenceNbr()));
        String routhPath = toDoTasksServiceImpl.getRouthPath(TaskTypeStationEnum.发货.getCode(),workflowResultDto.getNextNodeKey(), routhPathVO);
        String wxRouthPath = toDoTasksServiceImpl.getWxRouthPath(TaskTypeStationEnum.发货.getCode(),workflowResultDto.getNextNodeKey(), routhPathVO);
        ToDoTasks toDoTasks=  new ToDoTasks (TaskTypeStationEnum.发货.getCode(),  preparationMoney.getSequenceNbr(), taskName,preparationMoney.getRegionalCompaniesCode(),routhPath,wxRouthPath);
        List<String> userIds = Arrays.asList(Optional.ofNullable(workflowResultDto.getNextExecuteUserIds()).orElse("").split(","));
        List<String> filterUsers = toDoTasksServiceImpl.filterUsers(TaskTypeStationEnum.发货.getCode(), workflowResultDto.getNextNodeKey(),userIds, preparationMoney.getRegionalCompaniesCode(), preparationMoney.getAmosUnitOrgCode());
        toDoTasksServiceImpl.completeAndAddToDoTask(filterUsers,toDoTasks,"");

        HygfPreparationMoneyAuditingDto preparationMoneyAuditpDto = new HygfPreparationMoneyAuditingDto();
        BeanUtils.copyProperties(workflowResultDto, preparationMoneyAuditpDto);
        preparationMoneyAuditpDto.setPreparationMoneyId(sequenceNbr);
        preparationMoneyAuditpDto.setPromoter(preparationMoney.getRecUserId());
        if (null == preparationMoneyAuditpDto.getInstanceId()) {
            preparationMoneyAuditpDto.setInstanceId(hygfPreparationMoneyAuditing.getInstanceId());
        }
        hygfPreparationMoneyAuditingService.createWithModel(preparationMoneyAuditpDto);

        //删除最新的补货单
        QueryWrapper<HygfReplenishment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("preparation_money_id", sequenceNbr);
        queryWrapper.orderByDesc("rec_date");
        queryWrapper.last("Limit 1");
        HygfReplenishment hygfReplenishment = hygfReplenishmentMapper.selectOne(queryWrapper);

        QueryWrapper<HygfReplenishment> deleteWapper = new QueryWrapper<>();
        deleteWapper.eq("sequence_nbr", hygfReplenishment.getSequenceNbr());
        hygfReplenishmentMapper.delete(deleteWapper);
    }
        //补货审核
    public void replenishmentAudit(Long sequenceNbr,Map<String, Object> kv) {
        PreparationMoney preparationMoney = preparationMoneyMapper.selectById(sequenceNbr);

        LambdaQueryWrapper<DocumentStation> stations = new LambdaQueryWrapper<>();
        stations.eq(DocumentStation::getPreparationMoneyId,sequenceNbr);
        List<DocumentStation> documentStations = documentStationMapper.selectList(stations);
        List<Long> collect = documentStations.stream().map(DocumentStation::getStationId).collect(Collectors.toList());

        LambdaUpdateWrapper<PeasantHousehold> up = new LambdaUpdateWrapper<>();
        if (kv.get("approvalStatus").toString().equals("0")){
            preparationMoney.setOrderStatus(DeliveryStateeEnum.待补货.getName());
            up.set(PeasantHousehold::getPreparationMoneyState, DeliveryStateeEnum.待补货.getName());
            up.set(PeasantHousehold::getConstructionState, DeliveryStateeEnum.待补货.getName());
            up.in(BaseEntity::getSequenceNbr,collect);
            preparationMoney.setDeliveryTime(null);
            peasantHouseholdMapper.update(null,up);
        }else {
            preparationMoney.setOrderStatus(DeliveryStateeEnum.待确认.getName());
        }
        preparationMoneyMapper.updateById(preparationMoney);
        this.wofkflowExcute(kv.get("instanceId").toString(), kv.get("approvalStatus").toString(),kv.getOrDefault("comment","").toString(),preparationMoney);
    }

    public PreparationMoney  submitOrder(PreparationMoney model, String instanceId, String isSubmit){
        if (null == model.getRegionalCompaniesSeq()){
            throw new BadRequest("区域公司不可为空");
        }
        if (null == model.getAmosUnitId()){
            throw new BadRequest("经销商不可为空");
        }

        if ("1".equals(isSubmit)){
            preparationMoneyMapper.updateById(model);
        }else {

            if (CollectionUtil.isEmpty(model.getPeasantHouseholdId())){
                throw new BadRequest("提交时选择电站不可为空");
            }
            if (CollectionUtil.isEmpty(model.getDeliveryFile())){
                throw new BadRequest("提交时发货单不可为空");
            }

            //isSubmit = 0 表示提交  也对应工作流表达式 可直接使用
            model.setOrderStatus(DeliveryStateeEnum.待确认.getCode());
            model.setDeliveryTime(new Date());
            preparationMoneyMapper.updateById(model);

            this.wofkflowExcute(instanceId,isSubmit,"",model);
        }

        List<DocumentStation> ids = model.getPeasantHouseholdId();
        LambdaUpdateWrapper<PeasantHousehold> up = new LambdaUpdateWrapper<>();
        //电站信息存储
        LambdaQueryWrapper<DocumentStation> query1 = new LambdaQueryWrapper<>();
        query1.eq(DocumentStation::getPreparationMoneyId, model.getSequenceNbr());
        List<Long> oldIds = documentStationMapper.selectList(query1).stream().map(DocumentStation::getStationId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(oldIds)){
            LambdaUpdateWrapper<PeasantHousehold> up1 = new LambdaUpdateWrapper<>();
            up1.in(BaseEntity::getSequenceNbr,oldIds);
            up1.set(PeasantHousehold::getPreparationMoneyState, DeliveryStateeEnum.待发货.getCode());
            up1.set(PeasantHousehold::getConstructionState, "勘察完成");
            peasantHouseholdMapper.update(null, up1);

            LambdaUpdateWrapper<DocumentStation> up3 = new LambdaUpdateWrapper();
            up3.eq(DocumentStation::getPreparationMoneyId, model.getSequenceNbr());
            documentStationMapper.delete(up3);

        }




        //电站信息存储
        if (CollectionUtil.isNotEmpty(ids) && ids.size()>0){
            List<DocumentStation> listDocumentStation = new ArrayList<>();
            List<Long> idsH = new ArrayList<>();
            for (DocumentStation documentStation : ids) {
                documentStation.setPreparationMoneyId(model.getSequenceNbr());
                documentStation.setSequenceNbr(null);
                idsH.add(documentStation.getStationId());
                listDocumentStation.add(documentStation);
            }
            up.in(PeasantHousehold::getSequenceNbr, idsH);
            if ("1".equals(isSubmit)) {
                up.set(PeasantHousehold::getPreparationMoneyState, DeliveryStateeEnum.待补货.getName());
                up.set(PeasantHousehold::getConstructionState, DeliveryStateeEnum.待补货.getName());
            }else {
                up.set(PeasantHousehold::getPreparationMoneyState, ArrivalStateeEnum.待收货.getName());
                up.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.待收货.getName());
            }

                peasantHouseholdMapper.update(null, up);

            documentStationService.saveBatch(listDocumentStation);
        }

        return model;

    }

    public IPage<Map<String,Object>> preparationStation(Integer current, Integer size, String preparationMoneyState,String ownersName,String regionalcompaniesSeq,String developerId,String state,String province, String projectAddress, String startTime, String endTime,String routhPathId){


         PageHelper.startPage(current,  size);
         List<Map<String, Object>> resultPage = preparationMoneyMapper.preparationStation(preparationMoneyState,ownersName,regionalcompaniesSeq,developerId,state,province, projectAddress, startTime, endTime,routhPathId);

        if(resultPage != null && resultPage.size() > 0) {
            resultPage.forEach(e -> {
                System.out.println("+++++++++++++++" + e.get("peasantHouseholdNo"));
                if(e.get("peasantHouseholdNo") != null) {
                    e.put("scale", householdContractMapper.getHygfCommercialScale((String) e.get("peasantHouseholdNo")));
                    e.put("realScale", powerStationEngineeringInfoMapper.getRealScaleByPeasantHouseholdNo((String) e.get("peasantHouseholdNo")));
                }
            });
        }


        PageInfo<Map<String, Object>> page = new PageInfo(resultPage);
         Page<Map<String, Object>> pagenew = new Page<>();
         pagenew.setTotal(page.getTotal());
         pagenew.setSize(size);
         pagenew.setRecords(page.getList());
         pagenew.setCurrent(current);
         return pagenew;
     }

    public PreparationMoney getFromInfo(List<String> list) {

        LambdaQueryWrapper<PeasantHousehold> query = new LambdaQueryWrapper<>();
        query.in(BaseEntity::getSequenceNbr,list);
        List<PeasantHousehold> peasantHouseholds = peasantHouseholdMapper.selectList(query);

        PreparationMoney preparationMoney = new PreparationMoney();
        preparationMoney.setRegionalCompaniesSeq(peasantHouseholds.get(0).getRegionalCompaniesSeq());

        //农户表中存储的经销商id是平台的 表单经销商接口是unitinfo主键 无法对应 查询后赋值
        LambdaQueryWrapper<UnitInfo> query1 = new LambdaQueryWrapper<>();
        query1.eq(UnitInfo::getAmosCompanyCode,peasantHouseholds.get(0).getDeveloperCode());
        query1.eq(UnitInfo::getAuditStatus,2);
        UnitInfo unitInfo = unitInfoService.getBaseMapper().selectOne(query1);

        preparationMoney.setAmosUnitId(unitInfo.getSequenceNbr());


        LambdaQueryWrapper<RegionalCompanies> qu=new LambdaQueryWrapper();
        qu.eq(RegionalCompanies::getRegionalCompaniesSeq,peasantHouseholds.get(0).getRegionalCompaniesSeq());
        qu.eq(RegionalCompanies::getUnitInfoId,unitInfo.getSequenceNbr());
        qu.eq(RegionalCompanies::getIsDelete,false);
        RegionalCompanies  regionalCompanies=regionalCompaniesMapper.selectOne(qu);
        preparationMoney.setConsignee(regionalCompanies.getConsignee());
        preparationMoney.setPhone(regionalCompanies.getPhone());
        preparationMoney.setConsigneeRegionCode(regionalCompanies.getConsigneeRegionCode());
        preparationMoney.setAddress(regionalCompanies.getAddress());
        List<DocumentStation> stations = new ArrayList<>();
        peasantHouseholds.forEach(e->{
            DocumentStation documentStation = new DocumentStation();
            documentStation.setStationId(e.getSequenceNbr());
            documentStation.setOwnersName(e.getOwnersName());
            documentStation.setDeveloperName(e.getDeveloperName());
            documentStation.setPeasantHouseholdNo(e.getPeasantHouseholdNo());

            if(e.getPeasantHouseholdNo() != null) {
                documentStation.setScale(householdContractMapper.getHygfCommercialScale(e.getPeasantHouseholdNo()));
                documentStation.setRealScale(powerStationEngineeringInfoMapper.getRealScaleByPeasantHouseholdNo(e.getPeasantHouseholdNo()));
            }


            documentStation.setProjectAddressName(e.getProjectAddressName()+"/"+e.getProjectAddressDetail());
            stations.add(documentStation);
        });
        preparationMoney.setPeasantHouseholdId(stations);
        preparationMoney.setOrderTime(new Date());
        return preparationMoney;
    }
}