package com.junmp.jyzb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junmp.junmpProcess.dto.HandleDataDTO;
import com.junmp.junmpProcess.dto.StartProcessInstanceDTO;
import com.junmp.junmpProcess.dto.json.UserInfo;
import com.junmp.junmpProcess.service.IFlowInstanceService;
import com.junmp.jyzb.api.bean.dto.BusFormDto;
import com.junmp.jyzb.api.bean.query.BussinessOrderDetialReq;
import com.junmp.jyzb.api.bean.query.InventoryReq;
import com.junmp.jyzb.api.bean.query.QueryBusFormReq;
import com.junmp.jyzb.api.bean.req.UpdateBusFormReq;
import com.junmp.jyzb.api.constant.JYZBConstant;
import com.junmp.jyzb.api.exception.JYZBAppException;
import com.junmp.jyzb.api.exception.enums.InventoryExceptionEnum;
import com.junmp.jyzb.api.exception.enums.OrderExceptionEnum;
import com.junmp.jyzb.cache.MsgRedisCache;
import com.junmp.jyzb.entity.*;
import com.junmp.jyzb.mapper.BusFormMapper;
import com.junmp.jyzb.mapper.InventorySummaryMapper;
import com.junmp.jyzb.mapper.VieWarrantyGroupMapper;
import com.junmp.jyzb.service.*;
import com.junmp.jyzb.utils.BusinessUtil;
import com.junmp.jyzb.utils.DateTimeUtil;
import com.junmp.v2.auth.api.bean.login.LoginUser;
import com.junmp.v2.auth.api.context.LoginContext;
import com.junmp.v2.common.exception.base.ServiceException;
import com.junmp.v2.common.util.BeanPlusUtil;
import com.junmp.v2.db.api.factory.PageFactory;
import com.junmp.v2.db.api.factory.PageResultFactory;
import com.junmp.v2.db.api.page.PageResult;
import com.junmp.v2.dict.entity.SysDict;
import com.junmp.v2.dict.entity.SysDictItem;
import com.junmp.v2.dict.service.SysDictItemService;
import com.junmp.v2.dict.service.SysDictService;
import com.junmp.v2.message.api.MessageApi;
import com.junmp.v2.message.api.bean.req.MessageReq;
import com.junmp.v2.message.api.bean.req.MessageSendReq;
import com.junmp.v2.message.api.bean.res.MessageRes;
import com.junmp.v2.message.api.enums.MsgReadStateEnum;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author lxh专属坐骑
* @description 针对表【base_bus_form】的数据库操作Service实现
* @createDate 2023-09-25 10:16:46
*/
@Service
public class BusFormServiceImpl extends ServiceImpl<BusFormMapper, BusForm> implements BusFormService{
    @Resource
    private MsgRedisCache redisCache;
    @Resource
    private IFlowInstanceService FlowInstanceService;
    @Resource
    private MessageApi messageApi;

    @Resource
    private InventorySummaryService inventorySummaryService;

    @Resource
    private InventoryService inventoryService;

    @Resource
    private InventorySummaryMapper inventorySummaryMapper;

    @Resource
    private OrderLogService orderLogService;

    @Resource
    protected TaskService taskService;
    @Resource
    private BusFormMapper busFormMapper;

    @Resource
    private PolicemanService policemanService;

    @Resource
    private LogSummaryService logSummaryService;

    @Resource
    private VieWarrantyGroupMapper vieWarrantyGroupMapper;

    @Resource
    private VieWarrantyGroupService vieWarrantyGroupService;


    @Resource
    private OrderMainService orderMainService;

    @Resource
    private WarehouseInventoryService warehouseInventoryService;

    @Resource
    private WarehouseService warehouseService;
    @Resource
    private PubOrgService pubOrgService;

    @Resource
    private SysDictService sysDictService;

    @Resource
    private OrderNumService orderNumService;
    @Resource
    private SysDictItemService sysDictItemService;


    /**
     * 创建业务单
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String AddBussinessOrder(UpdateBusFormReq req) {
        //附件上传（任何状态下都能进行上传）
        if (ObjectUtil.isNotNull(req.getId()) && ObjectUtil.isNotEmpty(req.getIsUploadAttachment()) && req.getIsUploadAttachment().equals("1")){
            BusForm one = getById(req.getId());
            one.setAttachmentLocation(req.getAttachmentLocation());
            updateById(one);
            return one.getId();
        }
        //判断inventorySummary表中是否有这个装备的已在审核中的数量，如果数量为null或者为0，则表示可以进行审批
        if (req.getBussinessType().equals("remove") && ObjectUtil.isNotEmpty(req.getProcessDefinitionId())){
            Boolean aBoolean = addOrRevokeAgentBrokenNum(req,true);
        }

        BusForm existBusForm=null;
        //获取已经存在的业务单
        if (ObjectUtil.isNotNull(req.getId()) && !req.getId().trim().isEmpty()){
            existBusForm = this.getById(req.getId());
        }
        if (existBusForm!=null) {
            //判断该单据是否可以进行修改(如果审核中则不允许修改)\
            if (ObjectUtil.isNotNull(existBusForm.getExamineState()) && existBusForm.getExamineState().equals("working")){
                throw new ServiceException(OrderExceptionEnum.ORDER_CAN_NOT_UPDATE);
            }
        }

        if (ObjectUtil.isEmpty(req.getProcessDefinitionId()))
        {
            req.setExamineState("none");
        }
        else
        {
            req.setExamineState("working");
        }


        BusForm busForm = new BusForm();
        BeanUtil.copyProperties(req,busForm);
        //设置业务单的使用次数（默认是出库一次，入库一次）
        busForm.setOrderCurrentState("bothuseing");
        busForm.setOrderLastState("bothuseing");
        if (ObjectUtil.isNull(req.getId())){
            String id= UUID.randomUUID().toString();
            busForm.setId(id);
            //设置单据号（调拨的单号根据和登录人员的组织机构id有关）
            //根据userId去查询组织机构id
            OrderNum orderNum=new OrderNum();
            if (req.getBussinessType().equals("allocate")){
                //startOrgId和orgId相等表示调拨下发单，否则为调拨申请单
                if (req.getStartOrgId().equals(req.getOrgId())){
                    orderNum = this.setOrderCode(req.getBussinessType(), req.getStartOrgId());
                } else {
                    orderNum = this.setOrderCode(req.getBussinessType(), req.getEndOrgId());
                }
            }else {
                orderNum = this.setOrderCode(req.getBussinessType(), req.getOrgId());
            }
            //设置单据号（业务类型+时间戳后4位+年月日+单号数），确保唯一性
            long time = new Date().getTime() % 10000;
            String codeValue=String.format("%04d",orderNum.getNum());
            busForm.setBussinessCode(orderNum.getBussinessType()+
                    String.format("%04d",time)+
                    orderNum.getYear()+
                    String.format("%02d",LocalDateTime.now().getMonth().getValue())+
                    String.format("%02d",LocalDateTime.now().getDayOfMonth())+codeValue);

            busForm.setCreateTime(DateTimeUtil.getCurrentDateTime());
        }
        String processInstanceId=null;
        //执行工作流
        if (req.getExamineState().equals("working"))
        {
            StartProcessInstanceDTO startProcessInstanceDTO = setParams(req,busForm);
            processInstanceId= FlowInstanceService.startProcessInstanceById(startProcessInstanceDTO);

        }
        //判断当前审核是否跳过
        if (processInstanceId!=null && processInstanceId.startsWith("skip") ){
            String substring = processInstanceId.substring(4);
            busForm.setProcessId(substring);
            busForm = setAssaign(busForm, existBusForm, req);
            Task currentTask = taskService.createTaskQuery().processInstanceId(substring).singleResult();
            // 直接完成当前任务
            taskService.complete(currentTask.getId());
        }else if (processInstanceId!=null){
            busForm.setProcessId(processInstanceId);

            String assigns= FlowInstanceService.GetNextAssign(processInstanceId);//这里需要手动更新审核人信息
            busForm.setCurrentAssign(assigns);
            busForm = setAssaign(busForm, existBusForm, req);
        }else {
            busForm = setAssaign(busForm, existBusForm, req);
        }

        String objJson= redisCache.get(busForm.getProcessId());
        redisCache.remove(busForm.getProcessId());
        List<MessageSendReq> msgs= JSONObject.parseArray(objJson,MessageSendReq.class);
        if (CollectionUtil.isNotEmpty(msgs)){
            msgs.forEach(msg->
                    {
                        messageApi.sendMessageNoToken(msg);

                    }

            );
        }else{
            HandleDataDTO handleDataDTO = new HandleDataDTO();
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(Long.valueOf(busForm.getAgentId()));
            handleDataDTO.setCurrentUserInfo(userInfo);
            handleDataDTO.setSignInfo("");
            handleDataDTO.setProcessInstanceId(processInstanceId);
            List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).list();
            handleDataDTO.setTaskId(tasks.get(0).getId());
            orderMainService.agree(handleDataDTO);
        }

        return busForm.getId();
    }

    /**
     * 修改单据可看人员以及上级确认标志
     * @param busForm
     * @param existBusForm
     * @param req
     * @return
     */
    private BusForm setAssaign(BusForm busForm,BusForm existBusForm,UpdateBusFormReq req){
        if (existBusForm!=null) {
            //谁能看见单据字段需要进行修改，判断报废单的报废类型，如果是上级报废变成本级报废需要修改，反之本级报废变成上级报废也需要修改
            if (req.getBussinessType().equals("remove") && busForm.getRemoveType()==0 && existBusForm.getRemoveType()==1){//上级变本级
                String userIds=policemanService.searchUserByRoleId(req.getOrgId(), JYZBConstant.SH_ROLR_ID);
                String userId=LoginContext.getContext().getLoginUser().getUserId().toString()+","+userIds;
                busForm.setHistoryAssign(userId);
            } else if (req.getBussinessType().equals("remove") && busForm.getRemoveType()==1 && existBusForm.getRemoveType()==0) {//本级变上级
                String userIds=policemanService.searchUserByRoleId(req.getOrgId(), JYZBConstant.SH_ROLR_ID);
                String newUserIds=policemanService.searchUserByRoleId(Long.valueOf(req.getSupplierId()), JYZBConstant.SH_ROLR_ID);
                String userId=LoginContext.getContext().getLoginUser().getUserId().toString()+","+userIds+","+newUserIds;
                //上级组织的审核人员
                busForm.setHistoryAssign(userId);
                busForm.setRemoveConfirmState(0);
            } else if (req.getBussinessType().equals("allocate") && Objects.equals(req.getOrgId(), req.getStartOrgId())) {
                //调拨下发，需要将下级单位的审核员添加进来
                String userIds=policemanService.searchUserByRoleId(req.getEndOrgId(), JYZBConstant.SH_ROLR_ID);
                String userId=LoginContext.getContext().getLoginUser().getUserId().toString()+","+userIds;
                busForm.setHistoryAssign(userId);
            }
            updateById(busForm);
        } else {
            //保存
            //将创建人员添加（为的是将审核员创建的单子，审核员能看见）
            //将该组织机构下的所有审核人员进行查询，并添加到historyAssign中
            String userIds=policemanService.searchUserByRoleId(req.getOrgId(), JYZBConstant.SH_ROLR_ID);
            String userId="";
            if (req.getBussinessType().equals("remove") && busForm.getRemoveType()==1) {//上级报废
                String newUserIds=policemanService.searchUserByRoleId(Long.valueOf(req.getSupplierId()), JYZBConstant.SH_ROLR_ID);
                userId=LoginContext.getContext().getLoginUser().getUserId().toString()+","+userIds+","+newUserIds;
                busForm.setRemoveConfirmState(0);
            } else if (req.getBussinessType().equals("allocate") && Objects.equals(req.getOrgId(), req.getStartOrgId())) {
                String newUserIds=policemanService.searchUserByRoleId(req.getEndOrgId(), JYZBConstant.SH_ROLR_ID);
                userId=LoginContext.getContext().getLoginUser().getUserId().toString()+","+userIds+","+newUserIds;
                busForm.setHistoryAssign(userId);
            } else {
                userId=LoginContext.getContext().getLoginUser().getUserId().toString()+","+userIds;
            }
            busForm.setHistoryAssign(userId);
            this.save(busForm);
        }
        return busForm;
    }

    private StartProcessInstanceDTO setParams(UpdateBusFormReq req,BusForm busForm){
        StartProcessInstanceDTO startProcessInstanceDTO=new StartProcessInstanceDTO();
        startProcessInstanceDTO.setProcessDefinitionId(req.getProcessDefinitionId());
        startProcessInstanceDTO.setOrderId(busForm.getId());
        startProcessInstanceDTO.setTypeOrder("bussinessOrder");
        startProcessInstanceDTO.setUserId(req.getApplyUserId());
        startProcessInstanceDTO.setBussinessType(req.getBussinessType());
        //发物单位和收物单位
        switch (req.getBussinessType()){
            case "use":
                startProcessInstanceDTO.setStartOrgName(req.getOrgName());
                startProcessInstanceDTO.setEndUserName(req.getReturnUser());
                break;
            case "purchase":
                startProcessInstanceDTO.setStartOrgName(req.getSupplierName());
                startProcessInstanceDTO.setEndOrgName(req.getOrgName());
                break;
            case "allocate":
                startProcessInstanceDTO.setStartOrgName(req.getStartOrgName());
                startProcessInstanceDTO.setEndOrgName(req.getEndOrgName());
                break;
            case "repair":
            case "destruction":
                startProcessInstanceDTO.setStartOrgName(req.getOrgName());
                startProcessInstanceDTO.setEndOrgName(req.getSupplierName());
                break;
            case "remove":
                startProcessInstanceDTO.setStartOrgName(req.getOrgName());
                startProcessInstanceDTO.setEndOrgName(req.getOrgName());
                break;
        }
        //装备列表
        startProcessInstanceDTO.setInvList(req.getInvList());
        //业务类型
        startProcessInstanceDTO.setType("busFormDto");

//            Object A= JSON.toJSONString(req);
        if (ObjectUtil.isNotNull(req.getType())){
            req.setType("busFormDto");
        }
        Object A= JSON.toJSONString(req, SerializerFeature.WriteDateUseDateFormat);
        JSONObject jsonObject = JSON.parseObject(A.toString());

        startProcessInstanceDTO.setFormData(jsonObject);
        return startProcessInstanceDTO;
    }

    //在提交审核或者保存草稿的时候判断申请报废数+审核中数量+报废区数量是否等于在库数，如果大于则报错
    //flag表示一个标识，如果是提交业务单那么flag=true，如果是审核拒绝或者删除，那么flag就为false
    public boolean addOrRevokeAgentBrokenNum(UpdateBusFormReq req,boolean flag){
        List<BussinessOrderDetialReq> list = JSON.parseArray(req.getDetailList(), BussinessOrderDetialReq.class);
        List<Object[]> searchItem=new ArrayList<>();
        for (BussinessOrderDetialReq detialReq:list) {
            //我先去数据库查询summary表中的数据
            Object[] item=new Object[]{req.getOrgId(),detialReq.getLocationId(),detialReq.getTypeId(),detialReq.getSizeId(),detialReq.getPrice()};
            searchItem.add(item);
        }
        List<InventorySummary> inventorySummaryList = inventorySummaryMapper.selectSumByItems(searchItem);
        String msg="";
        for (BussinessOrderDetialReq detialReq:list) {
            for (InventorySummary is:inventorySummaryList) {
                if (ObjectUtil.isNull(is.getAgentBrokenNum())){
                    is.setAgentBrokenNum(0);
                }
                if (detialReq.getLocationId().equals(is.getLocationId()) && detialReq.getTypeId().equals(is.getTypeId())
                        && detialReq.getSizeId().equals(is.getSizeId()) && detialReq.getPrice().compareTo(is.getUnitPrice())==0){
                    if (flag){
                        //判断审核中的数量是否为0，如果为0 ，那么直接进行添加，如果不为0，则需要判断审核中的数量加申请报废的数量是否超过可以报废的数量
                        //如果超过那么则直接进行报错提醒
                        if (detialReq.getPlanNum()+is.getAgentBrokenNum()<=is.getStockNumber()){
                            //将库存的审核中的报废数量根据单据重新进行计算
                            is.setAgentBrokenNum(is.getAgentBrokenNum()+detialReq.getPlanNum());
                        }else {
                            msg=msg+"装备：" +detialReq.getTypeName()+"号型："+detialReq.getSizeName()+"已存在审核最大可报废数量;";
                        }
                    }else {
                        //直接将在审核中的数量修改为审核之前的状态
                        is.setAgentBrokenNum(is.getAgentBrokenNum()-detialReq.getPlanNum());
                    }

                }
                break;
            }

        }
        if (!msg.trim().isEmpty()){
            throw new JYZBAppException(InventoryExceptionEnum.EQUIPMENT_NOT_EXIST, msg);
        }
        return inventorySummaryService.updateBatchById(inventorySummaryList);

    }



    @Override
    public Object showOrderByBusOrderId(QueryBusFormReq req) {
        List<BusFormDto> busFormDtos = busFormMapper.showOrderByBusOrderId(req);
        Map<String,Object> map=new HashMap<>();
        if (busFormDtos.size()>1){
            for (BusFormDto busFormDto:busFormDtos) {
                if (ObjectUtil.isNotNull(busFormDto.getOutAndInState()) && busFormDto.getOutAndInState().equals("in")){
                    if (map.containsKey("busForm")) {
                        Object busForm = map.get("busForm");
                        BusFormDto busForm1 = (BusFormDto) busForm;
                        busForm1.setInOrderMainId(busFormDto.getOrderMainId());
                        map.put("busForm",busForm1);
                    }else {
                        busFormDto.setInOrderMainId(busFormDto.getOrderMainId());
                        busFormDto.setOrderMainId(null);
                        map.put("busForm",busFormDto);
                    }

                }else if (ObjectUtil.isNotNull(busFormDto.getOutAndInState()) && busFormDto.getOutAndInState().equals("out")){
                    if (map.containsKey("busForm")) {
                        Object busForm = map.get("busForm");
                        BusFormDto busForm1 = (BusFormDto) busForm;
                        busForm1.setOutOrderMainId(busFormDto.getOrderMainId());
                        map.put("busForm",busForm1);

                    }else {
                        busFormDto.setOutOrderMainId(busFormDto.getOrderMainId());
                        map.put("busForm",busFormDto);
                    }

                }
            }
        }else {
            map.put("busForm",busFormDtos.get(0));
        }

        return map.get("busForm");
    }

    //删除待提交的业务单据
    @Override
    public boolean delToSubmitOrder(UpdateBusFormReq req) {
        //根据传递的id进行删除
        BusForm one = getById(req.getId());
        if (ObjectUtil.isNull(one)){
            throw new ServiceException(OrderExceptionEnum.ORDER_NOT_EXIST);
        }
        if (!one.getExamineState().equals("none")){
            throw new ServiceException(OrderExceptionEnum.ORDER_DEL_ERROR);
        }
        //判断该单据是报废
//        if (one.getBussinessType().equals("remove")){
//            BeanPlusUtil.copyProperties(one,req);
//            addOrRevokeAgentBrokenNum(req,false);
//        }
        return removeById(req.getId());
    }


    /**
     * 查询业务单，（可以根据业务单进行修改）
     * @param
     * @return
     */
    @Override
    public PageResult<BusForm>showBussinessOrder(QueryBusFormReq req) {
        //(如果传其他不是数据库字段参数或者排序规则不是deac或者asc可能会出现错误)
        if (ObjectUtil.isNotNull(req.getColumn()) && !req.getColumn().trim().isEmpty() &&
                (req.getOrder().equalsIgnoreCase("asc")|| req.getOrder().equalsIgnoreCase("desc")) &&
                ObjectUtil.isNotNull(req.getOrder()) && !req.getOrder().trim().isEmpty()) {
            //修改字段，和数据库字段进行统一
            req.setColumn(req.getColumn().replaceAll("[A-Z]", "_$0").toLowerCase());
            req.setOrder(req.getOrder().toLowerCase());
        }
        LambdaQueryWrapper<BusForm> eq = createWrapper(req);
        Page<BusForm> page = page(PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize()), eq);
        List<BusForm> records = page.getRecords();
        int size = records.size();
        //是否创建创建空的数据返回前端
        if(req.getIsCreateNullDate()==null || req.getIsCreateNullDate()){
            Class<BusForm> busForm=BusForm.class;
            List<BusForm> nullData = BusinessUtil.createNullData((long)size, req.getPageNo(), req.getPageSize(), busForm);
            records.addAll(nullData);
        }
        return PageResultFactory.createPageResult(page);
    }



    //更新报废数（inventorySummary,审核通过之后更新）
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBrokenResult(BusForm busForm) {
        //获取数量
        String detailList = busForm.getDetailList();
        List<BussinessOrderDetialReq> list = JSONArray.parseArray(detailList, BussinessOrderDetialReq.class);
        //更新inventory表的表达式
        List<Object[]> searchItem=new ArrayList<>();
        for (BussinessOrderDetialReq detialReq:list) {
            //我先去数据库查询summary表中的数据
            Object[] item=new Object[]{busForm.getOrgId(),detialReq.getLocationId(),detialReq.getTypeId(),detialReq.getSizeId(),detialReq.getPrice(),0};
            searchItem.add(item);

        }

        List<Inventory> inventoryList=inventoryService.selectSum(searchItem,null);

        List<Inventory> updateInvList=new ArrayList<>();
        List<InventorySummary> inventorySummaryList = inventorySummaryMapper.selectSum(searchItem);
        List<InventorySummary> updateSummaryList=new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("组织机构为:"+busForm.getOrgId()+"单号为:"+busForm.getBussinessCode()+"的报废业务单将报废数量进行修改:");
        //加入map
        Map<String,VieWarrantyGroup> map=new HashMap<>();
        for (BussinessOrderDetialReq detialReq:list) {
            Integer oldPlanNum = detialReq.getPlanNum();

            for (InventorySummary is:inventorySummaryList) {
                if (detialReq.getLocationId().equals(is.getLocationId()) && detialReq.getTypeId().equals(is.getTypeId())
                    && detialReq.getSizeId().equals(is.getSizeId()) && detialReq.getPrice().compareTo(is.getUnitPrice())==0
                        && Objects.equals(detialReq.getProperty(), is.getProperty())){
                    //如果数量相同则直接将全部在库数的装备表中的该仓库的装备状态全部设置为报废，并且修改库存汇总表中的数据
                    //将库存的报废数量根据单据重新进行计算
                    Integer brokenNum=detialReq.getPlanNum()+is.getBrokenNumber();
                    stringBuilder.append("装备为"+detialReq.getTypeName()+","+detialReq.getSizeName()+"的报废数量从"+is.getBrokenNumber()+"改成"+brokenNum+",");
                    is.setBrokenNumber(brokenNum);
                    if (ObjectUtil.isNull(is.getBrokenCount())){
                        is.setBrokenCount(0);
                    }
                    is.setBrokenCount(is.getBrokenCount()+brokenNum);
                    is.setStockNumber(Math.max(is.getStockNumber()-detialReq.getPlanNum(),0));
                    is.setStockNumberPrice(is.getPrice().multiply(BigDecimal.valueOf(is.getStockNumber())));
                    is.setBrokenNumberPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(brokenNum)));
                    is.setAgentBrokenNum(ObjectUtil.isNull(is.getAgentBrokenNum())?0:Math.max(is.getAgentBrokenNum()-detialReq.getPlanNum(),0) );

                    if (detialReq.getPlanNum()>=is.getExpireNumber()){
                        //数量大于过质保数量
                        is.setExpireNumber(0);
                        is.setExpireNumberPrice(BigDecimal.ZERO);
                    } else {
                        //如果数量不相等，状态不进行修改，只修改库存汇总表中的信息
                        //将库存的报废数量根据单据重新进行计算
                        is.setExpireNumber(Math.max(is.getExpireNumber()-detialReq.getPlanNum(),0));
                        is.setExpireNumberPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getExpireNumber())));
                    }
                    updateSummaryList.add(is);

                    break;
                }

            }
            //批量修改inventtorySummary表中的数据
            if (updateSummaryList.size()>0){
                inventorySummaryService.updateBatchById(updateSummaryList);
            }

            for (Inventory inv:inventoryList) {
                if (detialReq.getPlanNum()>0){
                    if (detialReq.getLocationId().equals(inv.getLocationId()) && detialReq.getTypeId().equals(inv.getTypeId())
                            && detialReq.getSizeId().equals(inv.getSizeId()) && detialReq.getPrice().compareTo(inv.getPrice())==0
                            && detialReq.getProperty().equals(inv.getProperty())){
                        detialReq.setPlanNum(detialReq.getPlanNum()-1);
                        inv.setState("broken");
                        updateInvList.add(inv);
                    }
                }else {
                    break;
                }
            }
            //改inventory表中的装备状态
            inventoryService.updateBatchById(updateInvList);

            //重新计算过质保数
            String key=detialReq.getOrgId()+ detialReq.getLocationId()+detialReq.getTypeId()+detialReq.getSizeId()+detialReq.getPrice();
            if (map.containsKey(key)){
                VieWarrantyGroup vieWarrantyGroup = map.get(key);
                vieWarrantyGroup.setCountOfItems(vieWarrantyGroup.getCountOfItems()+oldPlanNum);
                map.put(key,vieWarrantyGroup);
            }else {
                VieWarrantyGroup vieWarrantyGroup = new VieWarrantyGroup();
                vieWarrantyGroup.setSizeId(detialReq.getSizeId());
                vieWarrantyGroup.setSizeName(detialReq.getSizeName());
                vieWarrantyGroup.setTypeId(detialReq.getTypeId());
                vieWarrantyGroup.setTypeName(detialReq.getTypeName());
                vieWarrantyGroup.setOrgName(detialReq.getOrgName());
                vieWarrantyGroup.setOrgId(detialReq.getOrgId().toString());
                vieWarrantyGroup.setCountOfItems(oldPlanNum);
                vieWarrantyGroup.setPrice(detialReq.getPrice());
                vieWarrantyGroup.setLocationId(detialReq.getLocationId());
                vieWarrantyGroup.setLocationName(detialReq.getLocationName());
                map.put(key,vieWarrantyGroup);
            }

        }
        //更新过质保期表
        //通过map查询出过质保期，过质保的数据 进行删除，
        List<VieWarrantyGroup> valuesList = new ArrayList<>(map.values());
        List<VieWarrantyGroup> warrantyList=vieWarrantyGroupMapper.selectByTerms(valuesList);
        for (VieWarrantyGroup invSum:valuesList) {
            for (VieWarrantyGroup warrantyInv:warrantyList) {
                if (invSum.getLocationId().equals(warrantyInv.getLocationId()) && invSum.getTypeId().equals(warrantyInv.getTypeId())
                        && invSum.getSizeId().equals(warrantyInv.getSizeId()) && invSum.getOrgId().equals(warrantyInv.getOrgId())
                && invSum.getPrice().compareTo(warrantyInv.getPrice())==0){
                    warrantyInv.setCountOfItems(warrantyInv.getCountOfItems()-invSum.getCountOfItems());
                    break;
                }
            }
        }
        vieWarrantyGroupService.updateBatchById(warrantyList);

        //创建log记录日志
        String string = stringBuilder.toString();
        string=string.substring(0,string.length()-1);
        OrderLog orderLog = new OrderLog();
        orderLog.setHistoryMsg(string);
        orderLog.setOrgId(busForm.getOrgId());
        orderLog.setBussinessType(busForm.getBussinessType());
        orderLog.setOrderCode(busForm.getBussinessCode());
        orderLog.setOrderId(busForm.getId());
        orderLog.setOrgName(busForm.getOrgName());
        orderLog.setCreateTime(DateTimeUtil.getCurrentDateTime());
        orderLogService.save(orderLog);
        //记录logSummary和logDetail的数据。
        List<InventoryReq> collect = updateInvList.stream().map(inventory -> {
            InventoryReq inventoryReq = new InventoryReq();
            BeanPlusUtil.copyProperties(inventory, inventoryReq);
            return inventoryReq;
        }).collect(Collectors.toList());
        LoginUser loginUser = LoginContext.getContext().getLoginUser();
        logSummaryService.addLogSummaryByInv(collect,busForm.getId(),busForm.getBussinessCode(),busForm.getBussinessType(),4,"0",loginUser.getUserInfo().getRealName(),loginUser.getOrgName(),null);
        return true;
    }

    /**
     * 设置单据单号
     * 通用方法，根据组织机构id以及业务单据类型来进行设置
     * @param
     */
    public OrderNum setOrderCode(String bussinessType,Long orgId){
        //设置业务单号，需要先判断该组织机构的业务单号是否存在，如果存在则将数量进行增加，如果不存在则新增一条对应的数据
        OrderNum orderNum = new OrderNum();
        orderNum.setYear(LocalDateTime.now().getYear());
        orderNum.setBussinessType(bussinessType);
        orderNum.setOrgId(orgId);
        //将业务类型转为中文简写
        Long sysDictId = sysDictService.getOne(new LambdaQueryWrapper<SysDict>()
                .eq(SysDict::getDictCode, "busstype_chinese")).getDictId();

        String itemValue = sysDictItemService.getOne(new LambdaQueryWrapper<SysDictItem>()
                .eq(SysDictItem::getItemText, bussinessType)
                .eq(SysDictItem::getDictId,sysDictId)).getItemValue();
        orderNum.setBussinessType(itemValue);

        List<OrderNum> list = orderNumService.list(new LambdaQueryWrapper<OrderNum>()
                .eq(OrderNum::getOrgId, orderNum.getOrgId())
                .eq(OrderNum::getBussinessType, orderNum.getBussinessType())
                .eq(OrderNum::getYear, orderNum.getYear()));
        OrderNum one = null;
        if (CollectionUtil.isNotEmpty(list)){
            one=list.get(0);
        }
        //设置num的数量
        if (ObjectUtil.isNull(one)){
            orderNum.setNum(1);
            orderNumService.save(orderNum);
            return orderNum;
        }else {
            one.setNum(one.getNum()+1);
            orderNumService.updateById(one);
            return one;
        }
    }


    private LambdaQueryWrapper<BusForm> createWrapper(QueryBusFormReq req) {
        LambdaQueryWrapper<BusForm> eq = new LambdaQueryWrapper<BusForm>()


                .eq(ObjectUtil.isNotNull(req.getProcessId()),BusForm::getProcessId,req.getProcessId())
                //装备名称模糊查询
                .like(ObjectUtil.isNotNull(req.getTypeName()),BusForm::getInvList,req.getTypeName())
                //单号
                .like(ObjectUtil.isNotNull(req.getBussinessCode()),BusForm::getBussinessCode,req.getBussinessCode())
                //领用人
                .like(ObjectUtil.isNotNull(req.getReturnUser()),BusForm::getReturnUser,req.getReturnUser())
                //经办人
                .like(ObjectUtil.isNotNull(req.getAgent()),BusForm::getAgent,req.getAgent())
                //厂商名称
                .like(ObjectUtil.isNotNull(req.getSupplierName()),BusForm::getSupplierName,req.getSupplierName())
                //发物单位
                .like(ObjectUtil.isNotNull(req.getStartOrgName()),BusForm::getStartOrgName,req.getStartOrgName())
                //收物单位
                .like(ObjectUtil.isNotNull(req.getEndOrgName()),BusForm::getEndOrgName,req.getEndOrgName())
                //开始时间
                .ge(ObjectUtil.isNotNull(req.getStartTime()),BusForm::getCreateTime, req.getStartTime())
                //结束时间
                .le(ObjectUtil.isNotNull(req.getEndTime()),BusForm::getCreateTime, req.getEndTime())
                .last("order by " + req.getColumn() + " " + req.getOrder());
        //组织机构
        if (req.getBussinessType().equals("remove")){
            eq.and(wrapper -> wrapper.eq(BusForm::getOrgId, req.getOrgId())
                    .or()
                    .eq(BusForm::getSupplierId, String.valueOf(req.getOrgId())));
        }
        else {
            eq.eq(ObjectUtil.isNotNull(req.getOrgId()) && !req.getBussinessType().equals("allocate"),BusForm::getOrgId,req.getOrgId());
        }
        //业务单据审核状态
        if (ObjectUtil.isNotNull(req.getExamineState()) && req.getExamineState().equals("unaudited")){

            List<String> examineStateList=new ArrayList<>();
            examineStateList.add("none");
            examineStateList.add("working");
            eq.in( BusForm::getExamineState,examineStateList);
        } else if (ObjectUtil.isNotNull(req.getExamineState()) && req.getExamineState().equals("finished")) {
            eq.eq(ObjectUtil.isNotNull(req.getExamineState() ) && !req.getExamineState().trim().isEmpty(), BusForm::getExamineState, req.getExamineState());
        }else if(ObjectUtil.isNotNull(req.getExamineState()) && req.getExamineState().equals("approved")){
            List<String> examineStateList=new ArrayList<>();
            examineStateList.add("finished");
            examineStateList.add("refuse");
            eq.in( BusForm::getExamineState,examineStateList);
        }

        //报废、销毁的业务类型
        if (ObjectUtil.isNotNull(req.getBussinessType()) && req.getBussinessType().equals("both")){
            List<String> bussinessTypeList=new ArrayList<>();
            bussinessTypeList.add("remove");
            bussinessTypeList.add("destruction");
            eq.in( BusForm::getBussinessType,bussinessTypeList);
        }else {
            eq.eq(ObjectUtil.isNotNull(req.getBussinessType()) && !req.getBussinessType().trim().isEmpty(), BusForm::getBussinessType, req.getBussinessType());
        }
       //判断单子是否全部可见（0不是，1是）
        if (ObjectUtil.isNotNull(req.getIsAllVisible()) && req.getIsAllVisible()!=0) {
            //领用人
            if (ObjectUtil.isNotNull(req.getUserId()) && req.getBussinessType().equals("use")) {
                //当前登录人
                eq.eq(BusForm::getReturnUserId, req.getUserId());
            } else {
                LoginUser StartUser = LoginContext.getContext().getLoginUser();
                //当前登录人
                eq.and(wrapper -> wrapper.eq(BusForm::getAgentId, StartUser.getUserId())
                        .or()
                        .like(BusForm::getHistoryAssign, StartUser.getUserId()));
            }

            //谁申请谁能看见
//            if (ObjectUtil.isNotNull(req.getUserId())){
//                eq.eq(BusForm::getAgentId,req.getUserId());
//            }else {
//                LoginUser StartUser = LoginContext.getContext().getLoginUser();
//                eq.eq(BusForm::getAgentId,StartUser.getUserId());
//            }
        }
        if (req.getBussinessType().equals("allocate")){
            if (req.getStartOrgId()!=null){
                eq.eq(BusForm::getStartOrgId,req.getStartOrgId());
            }
            if (req.getEndOrgId()!=null){
                eq.eq(BusForm::getEndOrgId,req.getEndOrgId());
            }
            if (req.getStartOrgId()==null && req.getEndOrgId()==null){
                eq.and(wrapper-> wrapper.eq(BusForm::getStartOrgId,req.getOrgId()).or().eq(BusForm::getEndOrgId,req.getOrgId()));
            }
            eq.eq(ObjectUtil.isNotNull(req.getAllocateType()) && !req.getAllocateType().isEmpty(),BusForm::getAllocateType,req.getAllocateType());
        }
        //当前单子状态
        if (ObjectUtil.isNotNull(req.getOrderCurrentState())){
            List<String> orderCurrentStateList=new ArrayList<>();
            if (req.getOrderCurrentState().equals("incoming")){
                orderCurrentStateList.add("incoming");
                orderCurrentStateList.add("bothuseing");
                eq.in( BusForm::getOrderCurrentState,orderCurrentStateList);
            }else if (req.getOrderCurrentState().equals("outgoing")){
                orderCurrentStateList.add("outgoing");
                orderCurrentStateList.add("bothuseing");
                eq.in( BusForm::getOrderCurrentState,orderCurrentStateList);
            }
        }

        return eq;
    }

    //上级单位报废发送消息
    @Override
    public void sendMsgByRemove(BusForm busForm) {
        List<MessageSendReq> msgList=new ArrayList<>();
        String newUserIds=policemanService.searchUserByRoleId(Long.valueOf(busForm.getSupplierId()), JYZBConstant.SH_ROLR_ID);
        List<String> userIdList = Arrays.asList(newUserIds.split(","));
        userIdList.forEach(userId -> {
            MessageSendReq sendReq= new MessageSendReq();
            sendReq.setReceiveUserIds(String.valueOf(userId));
            sendReq.setMsgTitle("您有新的待办任务");
            sendReq.setSendUserId("10000");
            sendReq.setBizType("assign/removeByUpper");
            sendReq.setMsgContent(busForm.getOrgName()+"创建的报废单【"+busForm.getBussinessCode()+"】需要您确认，请及时处理");
            sendReq.setBizId(Long.valueOf(busForm.getProcessId()));
            sendReq.setPriority("0");
            sendReq.setSendTime(DateTime.now());
            msgList.add(sendReq);
        });
        if (CollectionUtil.isNotEmpty(msgList)){
            msgList.forEach(msg->
                    {
                        messageApi.sendMessageNoToken(msg);
                    }
            );
        }
    }

    /**
     * 上级更新报废单据并且修改库存
     * @param busForm
     * @return
     */
    @Override
    @Transactional
    public boolean updateBrokenResultByUpper(BusForm busForm) {
        //查询上级组织机构的仓库信息
        Warehouse warehouse = warehouseService.getById(busForm.getWarehouseId());
        PubOrg pubOrg = pubOrgService.getById(Long.valueOf(busForm.getSupplierId()));
        //1.将单子进行修改确认状态
        busForm.setRemoveConfirmState(1);
        updateById(busForm);
        //2.将未读消息进行设置为已读
        MessageReq reqmsg=new MessageReq();
        reqmsg.setBizId(Long.valueOf(busForm.getProcessId()));
        reqmsg.setReadFlag(0);
        List<MessageRes> msgRes= messageApi.queryList(reqmsg);
        if (msgRes.size()>0)
        {
            // 使用流将 id 取出，并用逗号拼接成字符串
            String ids = msgRes.stream()
                    .map(MessageRes::getMsgId)
                    .map(String::valueOf) // 将 id 转换为字符串
                    .collect(Collectors.joining(","));
            messageApi.batchReadFlagByMessageIds(ids, MsgReadStateEnum.READ);
        }
        //3.修改上级单位库存
        String detailList = busForm.getDetailList();
        List<BussinessOrderDetialReq> list = JSONArray.parseArray(detailList, BussinessOrderDetialReq.class);
        List<Object[]> searchItem=new ArrayList<>();
        List<Object[]> upperSearchItem=new ArrayList<>();
        for (BussinessOrderDetialReq detialReq:list) {
            //我先去数据库查询summary表中的数据
            Object[] item=new Object[]{busForm.getOrgId(),detialReq.getLocationId(),detialReq.getTypeId(),detialReq.getSizeId(),detialReq.getPrice(),0};
            searchItem.add(item);

            Object[] upperItem=new Object[]{Long.valueOf(busForm.getSupplierId()),busForm.getWarehouseId(),detialReq.getTypeId(),detialReq.getSizeId(),detialReq.getPrice(),0};
            upperSearchItem.add(upperItem);

        }
        List<Inventory> inventoryList=inventoryService.selectSum(searchItem,null);

        List<Inventory> updateInvList=new ArrayList<>();
        //本级单位的库存
        List<InventorySummary> inventorySummaryList = inventorySummaryMapper.selectSum(searchItem);
        //上级单位的库存
        List<InventorySummary> upperInvSumList = inventorySummaryMapper.selectSum(upperSearchItem);
        List<InventorySummary> updateSummaryList=new ArrayList<>();
        List<InventorySummary> deleteSummaryList=new ArrayList<>();

        List<InventorySummary> upperUpdateSumList=new ArrayList<>();
        List<InventorySummary> upperAddSumList=new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder();
        //加入map
        Map<String,VieWarrantyGroup> map=new HashMap<>();
        stringBuilder.append("组织机构为:"+busForm.getOrgName()+"单号为:"+busForm.getBussinessCode()+"的报废业务单由上级单位确认，将报废数量进行修改:");
        for (BussinessOrderDetialReq detialReq:list) {
            Integer oldPlanNum = detialReq.getPlanNum();
            Boolean flag=false;
            for (InventorySummary is:upperInvSumList) {
                if (busForm.getWarehouseId().equals(is.getLocationId()) && detialReq.getTypeId().equals(is.getTypeId())
                        && detialReq.getSizeId().equals(is.getSizeId()) && detialReq.getPrice().compareTo(is.getUnitPrice())==0){
                    //如果数量相同则直接将全部在库数的装备表中的该仓库的装备状态全部设置为报废，并且修改库存汇总表中的数据
                    //将库存的报废数量根据单据重新进行计算
                    flag=true;
                    Integer brokenNum=detialReq.getPlanNum()+is.getBrokenNumber();
                    stringBuilder.append("装备为"+detialReq.getTypeName()+","+detialReq.getSizeName()+"的报废数量从"+is.getBrokenNumber()+"改成"+brokenNum+",");
                    is.setBrokenNumber(brokenNum);
                    is.setBrokenNumberPrice(detialReq.getPrice().multiply(BigDecimal.valueOf(brokenNum)));
                    is.setStockNumber(is.getNumber()+detialReq.getPlanNum());
                    is.setPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getNumber())));
                    if (ObjectUtil.isNull(is.getBrokenCount())){
                        is.setBrokenCount(0);
                    }
                    is.setBrokenCount(is.getBrokenCount()+brokenNum);
                    is.setBrokenNumberPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(brokenNum)));
                    upperUpdateSumList.add(is);

                    break;
                }

            }
            if (!flag){
                //需要新增
                InventorySummary inventorySummary=inventorySummaryService.createInventorySummary(Long.valueOf(busForm.getSupplierId()),
                        busForm.getSupplierName(),pubOrg.getOrgCode(),detialReq.getTypeId(),detialReq.getTypeName(),detialReq.getSizeId(),detialReq.getSizeName(),
                        busForm.getWarehouseId(),warehouse.getName(),0,0,detialReq.getPrice(),
                        0,0,0,0,0,0,detialReq.getPlanNum(),"0");
                upperAddSumList.add(inventorySummary);
            }

            //重新计算过质保数汇总
            String key=busForm.getSupplierId()+busForm.getWarehouseId()+detialReq.getTypeId()+detialReq.getSizeId()+detialReq.getPrice();
            if (map.containsKey(key)){
                VieWarrantyGroup vieWarrantyGroup = map.get(key);
                vieWarrantyGroup.setCountOfItems(vieWarrantyGroup.getCountOfItems()+oldPlanNum);
                map.put(key,vieWarrantyGroup);
            }else {
                VieWarrantyGroup vieWarrantyGroup = new VieWarrantyGroup();
                vieWarrantyGroup.setSizeId(detialReq.getSizeId());
                vieWarrantyGroup.setSizeName(detialReq.getSizeName());
                vieWarrantyGroup.setTypeId(detialReq.getTypeId());
                vieWarrantyGroup.setTypeName(detialReq.getTypeName());
                vieWarrantyGroup.setOrgName(busForm.getSupplierName());
                vieWarrantyGroup.setOrgId(busForm.getSupplierId());
                vieWarrantyGroup.setCountOfItems(oldPlanNum);
                vieWarrantyGroup.setPrice(detialReq.getPrice());
                vieWarrantyGroup.setLocationId(busForm.getWarehouseId());
                vieWarrantyGroup.setLocationName(warehouse.getName());
                map.put(key,vieWarrantyGroup);
            }

        }
        //批量修改inventtorySummary表中的数据
        if (upperUpdateSumList.size()>0){
            inventorySummaryService.updateBatchById(upperUpdateSumList);
        }
        if (upperAddSumList.size()>0){
            inventorySummaryService.saveBatch(upperAddSumList);
        }

        //4.修改本级单位库存
        for (BussinessOrderDetialReq detialReq:list) {
            for (InventorySummary is : inventorySummaryList) {
                if (detialReq.getLocationId().equals(is.getLocationId()) && detialReq.getTypeId().equals(is.getTypeId())
                        && detialReq.getSizeId().equals(is.getSizeId()) && detialReq.getPrice().compareTo(is.getUnitPrice()) == 0) {
                    //直接减库存
                    is.setStockNumber(Math.max(is.getStockNumber() - detialReq.getPlanNum(), 0));
                    is.setStockNumberPrice(is.getPrice().multiply(BigDecimal.valueOf(is.getStockNumber())));
                    is.setNumber(Math.max(is.getNumber() - detialReq.getPlanNum(), 0));
                    is.setAgentBrokenNum(ObjectUtil.isNull(is.getAgentBrokenNum()) ? 0 : Math.max(is.getAgentBrokenNum() - detialReq.getPlanNum(), 0));
                    if (detialReq.getPlanNum() >= is.getExpireNumber()) {
                        //数量大于过质保数量
                        is.setExpireNumber(0);
                        is.setExpireNumberPrice(BigDecimal.ZERO);
                    } else {
                        //如果数量不相等，状态不进行修改，只修改库存汇总表中的信息
                        //将库存的报废数量根据单据重新进行计算
                        is.setExpireNumber(is.getExpireNumber() - detialReq.getPlanNum());
                        is.setExpireNumberPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getExpireNumber())));
                    }
                    if (is.getNumber()==0 && is.getStockNumber()==0 && is.getOutboundNumber()==0 && is.getBrokenNumber()==0 && is.getDestructionNumber()==0){
                        deleteSummaryList.add(is);
                    }else {
                        updateSummaryList.add(is);
                    }

                    break;
                }

            }

            //获取需要改变的装备
            for (Inventory inv : inventoryList) {
                if (detialReq.getPlanNum() > 0) {
                    if (detialReq.getLocationId().equals(inv.getLocationId()) && detialReq.getTypeId().equals(inv.getTypeId())
                            && detialReq.getSizeId().equals(inv.getSizeId()) && detialReq.getPrice().compareTo(inv.getPrice()) == 0) {
                        detialReq.setPlanNum(detialReq.getPlanNum() - 1);
                        inv.setState("broken");
                        inv.setOrgId(Long.valueOf(busForm.getSupplierId()));
                        inv.setLocationId(busForm.getWarehouseId());
                        updateInvList.add(inv);
                    }
                } else {
                    break;
                }
            }

        }
        //批量修改inventtorySummary表中的数据
        if (updateSummaryList.size() > 0) {
            inventorySummaryService.updateBatchById(updateSummaryList);
        }
        if (deleteSummaryList.size() > 0){
            inventorySummaryService.removeByIds(deleteSummaryList);
        }

        //5.装备修改组织机构单位以及状态
        //改inventory表中的装备状态
        inventoryService.updateBatchById(updateInvList);
        List<String> epcList = updateInvList.stream().map(Inventory::getEpc).collect(Collectors.toList());
        warehouseInventoryService.update(new LambdaUpdateWrapper<WarehouseInventory>()
                .set(WarehouseInventory::getLocationId,busForm.getWarehouseId())
                .set(WarehouseInventory::getLocationName,warehouse.getName())
                .set(WarehouseInventory::getOrgId,Long.valueOf(busForm.getSupplierId()))
                .set(WarehouseInventory::getOrgName,busForm.getSupplierName())
                .in(WarehouseInventory::getEpc,epcList));

        //6.创建日志记录
        String string = stringBuilder.toString();
        string=string.substring(0,string.length()-1);
        OrderLog orderLog = new OrderLog();
        orderLog.setHistoryMsg(string);
        orderLog.setOrgId(Long.valueOf(busForm.getSupplierId()));
        orderLog.setBussinessType(busForm.getBussinessType());
        orderLog.setOrderCode(busForm.getBussinessCode());
        orderLog.setOrderId(busForm.getId());
        orderLog.setOrgName(busForm.getSupplierName());
        orderLog.setCreateTime(DateTimeUtil.getCurrentDateTime());
        orderLogService.save(orderLog);
        //记录logSummary和logDetail的数据。
        List<InventoryReq> collect = updateInvList.stream().map(inventory -> {
            InventoryReq inventoryReq = new InventoryReq();
            BeanPlusUtil.copyProperties(inventory, inventoryReq);
            return inventoryReq;
        }).collect(Collectors.toList());
        LoginUser loginUser = LoginContext.getContext().getLoginUser();
        logSummaryService.addLogSummaryByInv(collect,busForm.getId(),busForm.getBussinessCode(),busForm.getBussinessType(),
                4,"0",loginUser.getUserInfo().getRealName(),busForm.getSupplierName(),null);
        return true;
    }
}




