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

import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.TableField;
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.enums.SqlKeyword;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler;
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.PeasantHouseholdDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.PreparationMoneyLogDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.PreparationPageDto;
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.dto.PreparationMoneyDto;
import com.yeejoin.amos.boot.module.hygf.api.util.NumberUtil;
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 org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.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.springframework.util.CollectionUtils;
import org.typroject.tyboot.core.foundation.exception.BaseException;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.math.BigDecimal;
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
    PreparationMoneyLogMapper preparationMoneyLogMapper;
    @Autowired
    PeasantHouseholdMapper peasantHouseholdMapper;

    private static final String regionRedis="app_region_redis";
    /**
     * 分页查询
     */
    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.ne(StringUtils.isNotEmpty(dto.getFlag()),PreparationMoney::getDeliveryState,DeliveryStateeEnum.待发货.getCode());

         if(dto.getDeliveryTime()!=null&&!dto.getDeliveryTime().get(0).equals("")){
             qw.between(dto.getDeliveryTime()!=null, PreparationMoney::getDeliveryTime, dto.getDeliveryTime().get(0), dto.getDeliveryTime().get(1));
         }

        qw.orderBy(Boolean.TRUE, Boolean.FALSE, PreparationMoney::getOrderTime);

        IPage<PreparationMoney> warningQuestionInfoIPage = preparationMoneyMapper.selectPage(dto, qw);

        return warningQuestionInfoIPage;
    }

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

    /**
     * 获取发货单详情 by sequenceNbr
     *
     *
     * @param sequenceNbr sequenceNbr
     * @return {@link  PreparationMoneyDto}
     * @author Provence
     * @throws
     */
//    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);
        preparationMoney.setPeasantHouseholdId(li);

        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<>();
        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> lih=documentStationMapper.selectList(q);
        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.put("preparationMoney",preparationMoney);
        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}
     * @author Provence
     * @throws
     */
    @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());

            //更新电站施工状态
            LambdaUpdateWrapper<PeasantHousehold>  up =new LambdaUpdateWrapper<>();
            up.set(PeasantHousehold::getConstructionState,DeliveryStateeEnum.已发货.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());
        }

        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,DeliveryStateeEnum.已发货.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());
                }
            }
            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;
    }

    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}
     * @author Provence
     * @throws
     */
    @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}
     * @author Provence
     * @throws
     */
    public PreparationMoneyDto caculateShippingPriceByPowerHouseHoldIds(List<Long> powerHouseholdIds) {
        List<DocumentBom> documentBoms = documentBomService.assembleDocumentBom(powerHouseholdIds);
        return caculateShippingPrice(documentBoms);
    }

    /**
     * 根据前端选择的发货电站ID列表计算BOM清单价格
     *
     *
     * @param documentBoms BOM清单
     * @return {@link  PreparationMoneyDto}
     * @author Provence
     * @throws
     */
    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;
    }
}