package com.junmp.v2.cs.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.junmp.jyzb.api.bean.dto.csDto.*;
import com.junmp.jyzb.api.bean.req.UpdateOrderDetailReq;
import com.junmp.jyzb.api.bean.req.UpdateOrderReq;
import com.junmp.jyzb.api.bean.req.csReq.*;
import com.junmp.jyzb.api.constant.ChargeStationConstant;
import com.junmp.jyzb.api.constant.JYZBConstant;
import com.junmp.jyzb.api.exception.JYZBAppException;
import com.junmp.jyzb.api.exception.enums.CabinetV2ExceptionEnum;
import com.junmp.jyzb.api.exception.enums.JyzbV2ExceptionEnum;
import com.junmp.jyzb.entity.*;
import com.junmp.jyzb.service.*;
import com.junmp.jyzb.utils.DateTimeUtil;
import com.junmp.jyzb.utils.RedisUtils;
import com.junmp.v2.common.util.BeanPlusUtil;
import com.junmp.v2.cs.service.ChargeStationService;
import com.junmp.v2.db.api.factory.PageFactory;
import com.junmp.v2.sys.user.entity.SysUser;
import com.junmp.v2.sys.user.service.SysUserService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
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;

/**
 * <pre>
 *
 * 描述：
 * 版本：1.0.0
 * 日期：2024/9/5 下午4:02
 * 作者：xuzc@junmp.com.cn
 * <br>修改记录
 * <br>修改日期 修改人 修改内容
 *
 * </pre>
 */
@Service
public class ChargeStationServiceImpl implements ChargeStationService
{
    @Resource
    private WarehouseService warehouseService;
    @Resource
    private  PubOrgService pubOrgService;
    @Resource
    private  WarehouseInventoryService warehouseInventoryService;
    @Resource
    private  EquipmentTypeService equipmentTypeService;
    @Resource
    private  EquipmentSizeService equipmentSizeService;

    @Resource
    private SupplierService supplierService;
    @Resource
    private  OrderMainService orderMainService;
    @Resource
    private  OrderDetailService orderDetailService;

    @Autowired
    private RedisUtils redisUtils;

    @Resource
    private PolicemanService policemanService;

    @Resource
    private OrderLogService orderLogService;

    @Resource
    private RepositoryService repositoryService;

    @Resource
    private SysUserService sysUserService;

    @Override
    public CsWarehouseDto GetWarehouseById(GetWarehouseByIdReq req)
    {
        try {

            if (ObjectUtil.isEmpty(req.getId())){
                throw new JYZBAppException(JyzbV2ExceptionEnum.ID_ERROR);
            }
            Warehouse warehouse = warehouseService.getOne(new LambdaQueryWrapper<Warehouse>().eq(Warehouse::getId, req.getId()));
            if(warehouse != null){
                PubOrg org = pubOrgService.getOne(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getOrgId, warehouse.getOrgIdInt()));

                return new CsWarehouseDto(
                        warehouse.getId(),
                        warehouse.getIsLocked() == 1,
                        1,
                        warehouse.getName(),
                        warehouse.getLocation(),
                        warehouse.getLocation(),
                        warehouse.getOrgIdInt().toString(),
                        org == null ? "" : org.getOrgName(),
                        warehouse.getPhone(),
                        warehouse.getCreateTime(),
                        warehouse.getUpdateTime(),
                        warehouse.getUpdateUser(),
                        warehouse.getVideo());
            }
            else {
                throw new JYZBAppException(JyzbV2ExceptionEnum.REQUEST_DATA_ERROR);
            }
        }
        catch (Exception e) {
            throw new JYZBAppException(JyzbV2ExceptionEnum.OPERATE_FAILED);
        }
    }

    @Override
    public Boolean SetWarehouseState(CsWarehouseReq req)
    {
        try {
            Integer lock = Integer.parseInt(req.getIsLocked());

            Warehouse warehouse = warehouseService.getOne(new LambdaQueryWrapper<Warehouse>().eq(Warehouse::getId, req.getWarehouseId()));

            if(warehouse == null){
                throw new JYZBAppException(JyzbV2ExceptionEnum.ORGANIZATION_ERROR);
            }

            warehouse.setIsLocked(lock);
            warehouse.setUpdateTime(new Date());

            return warehouseService.updateById(warehouse);
        }
        catch (Exception e) {
            throw new JYZBAppException(JyzbV2ExceptionEnum.OPERATE_FAILED);
        }
    }

    @Override
    public List<CsWarehouseInventoryDto> GetAllInventoryList(CsWarehouseReq req)
    {

        if (ObjectUtil.isEmpty(req.getWarehouseId())){
            throw new JYZBAppException(JyzbV2ExceptionEnum.WAREHOUSEID_ERROR);
        }
        List<WarehouseInventory> invs = warehouseInventoryService.list(new LambdaQueryWrapper<WarehouseInventory>()
                .eq(WarehouseInventory::getLocationId, req.getWarehouseId()));

        //获取号型ID与单价映射
        Map<String, BigDecimal> priceDic = new HashMap<>();

        priceDic = redisUtils.get(ChargeStationConstant.SizeIdToPriceMap);
        if(MapUtil.isEmpty(priceDic)) {
            priceDic = new HashMap<>();

            Map<String, BigDecimal> typeDic = equipmentTypeService.list().stream()
                    .collect(Collectors.toMap(EquipmentType::getId, EquipmentType::getPrice));

            for (EquipmentSize s : equipmentSizeService.list()){
                priceDic.put(s.getId(), s.getPrice() == null ? typeDic.get(s.getTypeId()) : s.getPrice());
            }

            redisUtils.set(ChargeStationConstant.SizeIdToPriceMap, priceDic, (long) (60 * 60));
        }

        Map<String, BigDecimal> finalPriceDic = priceDic;

        return invs.stream()
                .collect(Collectors.groupingBy(WarehouseInventory::getTypeId)).entrySet().stream()
                    .map(e ->
                            new CsWarehouseInventoryDto(
                                    e.getValue().size(),
                                    e.getValue().get(0).getTypeName(),
                                    e.getKey(),
                                    e.getValue().stream()
                                            .collect(Collectors.groupingBy(WarehouseInventory::getSizeId)).entrySet().stream()
                                            .map(s ->
                                                    new CsWarehouseInventorySizeDto(
                                                            s.getValue().get(0).getSizeName(),
                                                            s.getKey(),
                                                            s.getValue().size(),
                                                            finalPriceDic.get(s.getKey()))
                                            )
                                            .collect(Collectors.toList())
                            )
                    )
                .collect(Collectors.toList());
    }

    @Override
    public CsOrderInfoDto GetOrderInfo(GetOrderInfoReq req)
    {

        if (ObjectUtil.isEmpty(req.getWarehouseId())){
            throw new JYZBAppException(JyzbV2ExceptionEnum.WAREHOUSEID_ERROR);
        }
        Long page = 1L;
        Long size = 10L;
        if(req.getPage() != null){
            page = Long.parseLong(req.getPage()) + 1;
        }
        if(req.getSize() != null){
            size = Long.parseLong(req.getSize());
        }

        Warehouse warehouse = warehouseService.getById(req.getWarehouseId());
        if(warehouse == null){
            throw new JYZBAppException(JyzbV2ExceptionEnum.WAREHOUSE_ERROR);
        }

        Page<OrderMain> orders = orderMainService.page(
                PageFactory.getDefaultPage(page, size),
                new LambdaQueryWrapper<OrderMain>()
                        .eq(OrderMain::getOrderType, "out")
                        .eq(OrderMain::getStartOrgId, warehouse.getOrgIdInt())
                        .and(a -> a
                                .isNull(OrderMain::getManualState)
                                .or(b -> b
                                        .ne(OrderMain::getManualState, 1)
                                )
                        )
                );
        if(CollectionUtil.isEmpty(orders.getRecords())){
            return new CsOrderInfoDto();
        }

        List<CsOrderContentDto> dtos = new ArrayList<>();

        for (OrderMain order : orders.getRecords()){
            dtos.add(
                    new CsOrderContentDto(
                            order.getId(),
                            order.getId(),
                            "DefaultWarehouse",
                            "0000000000000000" +  order.getOrderCode().substring(order.getOrderCode().length() - 6),
                            order.getOrderType().equals("in") ? order.getEndOrgId().toString() : order.getStartOrgId().toString(),
                            order.getCreateTime(),
                            order.getIsOpen() == 1,
                            StrUtil.isNotBlank(order.getReturnUser()) ?
                                    order.getReturnUser().indexOf("-") != -1 ?
                                            order.getReturnUser().substring(order.getReturnUser().indexOf("-") + 1) :
                                            order.getReturnUser()
                            : (StrUtil.isNotBlank(order.getEndOrgUserName()) ?
                                    order.getEndOrgUserName().indexOf("-") != -1 ?
                                    order.getEndOrgUserName().substring(order.getEndOrgUserName().indexOf("-") + 1) :
                                    order.getEndOrgUserName()
                            : ""),
                            "DefaultWarehouse",
                            "仓库",
                            ConvertToV2OrderType(order.getBussinessType()),
                            order.getInvList()
                    )
            );
        }
        return new CsOrderInfoDto((int) orders.getTotal(), dtos);
    }

    @Override
    public List<CsOrderDetailDto> GetOrderDetail(GetOrderDetailReq req)
    {

        if (ObjectUtil.isEmpty(req.getId())){
            throw new JYZBAppException(JyzbV2ExceptionEnum.ID_ERROR);
        }
        List<OrderDetail> details = orderDetailService.list(new LambdaQueryWrapper<OrderDetail>()
                .eq(OrderDetail::getOrderId, req.getId())
        );

        if(CollectionUtil.isEmpty(details)){
            return Collections.emptyList();
        }

        List<CsOrderDetailDto> dtos = details.stream()
                .map(d ->
                        new CsOrderDetailDto(
                                d.getId().toString(),
                                d.getTypeId(),
                                d.getTypeName(),
                                d.getTypeId(),
                                d.getPlanNum(),
                                d.getActualNum()
                        )
                ).collect(Collectors.toList());

        return dtos;
    }

    @Override
    public Boolean CloseOrder(ControlOrderReq req)
    {
        try{

            if (ObjectUtil.isEmpty(req.getId())){
                throw new JYZBAppException(JyzbV2ExceptionEnum.ID_ERROR);
            }
            OrderMain order = orderMainService.getById(req.getId());

            if(order == null){
                return true;
            }

            order.setUpdateTime(new Date());
            order.setIsOpen(0);

            return orderMainService.updateById(order);
        }
        catch (Exception e){
            throw new JYZBAppException(JyzbV2ExceptionEnum.OPERATE_FAILED, ":" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean OpenThisOrderAndCloseOther(ControlOrderReq req)
    {
        try
        {
            if (ObjectUtil.isEmpty(req.getId())){
                throw new JYZBAppException(JyzbV2ExceptionEnum.ID_ERROR);
            }

            if(req.getId().equals("空的单据信息")){
                if(StrUtil.isBlank(req.getWarehouseId())){
                    throw new JYZBAppException(JyzbV2ExceptionEnum.WAREHOUSEID_ERROR);
                }

                Warehouse warehouse = Optional.ofNullable(
                        warehouseService.getById(req.getWarehouseId())
                ).orElseThrow(() -> new JYZBAppException(JyzbV2ExceptionEnum.WAREHOUSEID_ERROR));

                List<OrderMain> closeOrder = orderMainService.list(
                        new LambdaQueryWrapper<OrderMain>()
                                .eq(OrderMain::getIsOpen, 1)
                                .and(s -> s
                                        .and(v -> v
                                                .eq(OrderMain::getOrderType, "in")
                                                .eq(OrderMain::getEndOrgId, warehouse.getOrgIdInt())
                                        )
                                        .or(b -> b
                                                .eq(OrderMain::getOrderType, "out")
                                                .eq(OrderMain::getStartOrgId, warehouse.getOrgIdInt())
                                        )
                                )
                );
                Boolean rs = true;
                if (CollectionUtil.isNotEmpty(closeOrder)){
                    closeOrder.stream().forEach(s -> {
                        s.setUpdateTime(new Date());
                        s.setIsOpen(0);
                    });
                    rs = orderMainService.updateBatchById(closeOrder);
                }
                return rs;
            }

            OrderMain order = orderMainService.getById(req.getId());

            if(order == null){
                throw new JYZBAppException(JyzbV2ExceptionEnum.ORDER_NOT_EXIST);
            }

            Long orgId = order.getOrderType().equals("in") ? order.getEndOrgId() : order.getStartOrgId();

            List<OrderMain> closeOrder = orderMainService.list(
                    new LambdaQueryWrapper<OrderMain>()
                            .ne(OrderMain::getId, req.getId())
                            .eq(OrderMain::getIsOpen, 1)
                            .and(s -> s
                                    .and(v -> v
                                            .eq(OrderMain::getOrderType, "in")
                                            .eq(OrderMain::getEndOrgId, orgId)
                                    )
                                    .or(b -> b
                                            .eq(OrderMain::getOrderType, "out")
                                            .eq(OrderMain::getStartOrgId, orgId)
                                    )
                            )
            );

            Boolean rs = false;

            if (CollectionUtil.isNotEmpty(closeOrder)){
                closeOrder.stream().forEach(s -> {
                    s.setUpdateTime(new Date());
                    s.setIsOpen(0);
                });
                rs = orderMainService.updateBatchById(closeOrder);
            }

            order.setUpdateTime(new Date());
            order.setIsOpen(1);
            rs = orderMainService.updateById(order);

            return rs;
        }
        catch (Exception e)
        {
            throw new JYZBAppException(JyzbV2ExceptionEnum.OPERATE_FAILED, ":" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean AddAndApprovalBorrowOrder(AddAndApprovalBorrowOrderReq req)
    {
        try
        {
            //生成领用单（借用单）
            //判断前端传递的归还时间是否填写，如果不为空则表示是借用，否则就是领用
            //但是3.0不关心
            //先获取流程定义id
            String formId="1735522446519427072";
            String defId="";

            PubOrg pubOrg = pubOrgService.PubOrgExist(Long.valueOf(req.getOrgId()));
            Warehouse warehouse = warehouseService.WarehoustExist(req.getWarehouseId());

            String returnUserId="";
            String returnUser="";
            if (ObjectUtil.isEmpty(req.getPoliceId())){
                //随便挑选一个警员
                Policeman one = policemanService.getOne(new LambdaQueryWrapper<Policeman>().eq(Policeman::getOrgId, pubOrg.getOrgId()).last("limit 1"));
                if (ObjectUtil.isNull(one)){
                    throw new JYZBAppException(CabinetV2ExceptionEnum.POLICE_NOT_EXIST,"该组织机构下没有警员信息");
                }else {
                    returnUser=one.getName();
                    returnUserId=one.getUserId().toString();
                }
            }else {
                //根据当前警员获取警员信息
                Policeman policeman = policemanService.PoliceExist(req.getPoliceId());
                returnUserId=policeman.getUserId().toString();
                returnUser=policeman.getName();
            }

            UpdateOrderReq reqInfo = createReqInfo(req,pubOrg.getOrgName(),returnUserId,returnUser);
            String invList="";
            if (ObjectUtil.isEmpty(req.getId()) || ObjectUtil.isNull(req.getId())){
                ProcessDefinition ProDef=repositoryService.createProcessDefinitionQuery()
                        .processDefinitionKey("Process_"+formId)
                        .latestVersion()
                        .singleResult();
                if(ProDef!=null)
                {
                    defId=ProDef.getId();
                }
                reqInfo.setProcessDefinitionId(defId);
            }
            List<String> sizeList=new ArrayList<>();
            List<String> typeList=new ArrayList<>();
            List<String> supplierList=new ArrayList<>();
            List<UpdateOrderDetailReq> detailList=new ArrayList<>();
            for (BorrowOrderDetailReq detailReq:req.getDetailList()){
                UpdateOrderDetailReq updateOrderDetailReq = new UpdateOrderDetailReq();
                updateOrderDetailReq.setType("out");
                String typeId=(ObjectUtil.isNotNull(detailReq.getEquipmentId())|| !StrUtil.isEmpty(detailReq.getEquipmentId()))?detailReq.getEquipmentId():detailReq.getEquipmentDetailId();

                updateOrderDetailReq.setTypeId(typeId);
                updateOrderDetailReq.setTypeName(detailReq.getEquipmentName());
                if (!typeList.contains(typeId) && (ObjectUtil.isNull(detailReq.getEquipmentName())|| detailReq.getEquipmentName().isEmpty())){
                    typeList.add(typeId);
                }
                updateOrderDetailReq.setSizeId(detailReq.getEquipmentSizeId());
                if (!sizeList.contains(detailReq.getEquipmentSizeId())){
                    sizeList.add(detailReq.getEquipmentSizeId());
                }
                updateOrderDetailReq.setSupplierId(detailReq.getSupplierId());
                if (!supplierList.contains(detailReq.getSupplierId())){
                    supplierList.add(detailReq.getSupplierId());
                }
                updateOrderDetailReq.setWarehouseId(warehouse.getId());
                updateOrderDetailReq.setWarehouseName(warehouse.getName());
                updateOrderDetailReq.setPlanNum(detailReq.getQuantity());
                updateOrderDetailReq.setActualNum(0);
                updateOrderDetailReq.setModifyQuantity(0);
                updateOrderDetailReq.setPrice(Optional.ofNullable(detailReq.getUnitPrice()).orElse(BigDecimal.ZERO).toString());
                updateOrderDetailReq.setTotalPrice(Optional.ofNullable(detailReq.getUnitPrice()).orElse(BigDecimal.ZERO).multiply(BigDecimal.valueOf(detailReq.getQuantity())));
                updateOrderDetailReq.setOrderType("ready");
                updateOrderDetailReq.setCreateTime(DateTimeUtil.getCurrentDateTime());
                updateOrderDetailReq.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                updateOrderDetailReq.setProperty(0);
                detailList.add(updateOrderDetailReq);
            }
            List<EquipmentType> typeIdToNameList=new ArrayList<>();
            List<EquipmentSize> sizeIdToName=new ArrayList<>();
            List<Supplier> supplierIdToName=new ArrayList<>();
            Map<String, String> typeMap=new HashMap<>();
            Map<String, String> sizeMap=new HashMap<>();
            Map<String, String> supplierMap=new HashMap<>();
            if (CollectionUtil.isNotEmpty(typeList)){
                typeIdToNameList=equipmentTypeService.list(new LambdaQueryWrapper<EquipmentType>().in(EquipmentType::getId,typeList));
                typeMap = typeIdToNameList.stream()
                        .collect(Collectors.toMap(EquipmentType::getId, EquipmentType::getName));
            }
            if (CollectionUtil.isNotEmpty(sizeList)){
                sizeIdToName=equipmentSizeService.list(new LambdaQueryWrapper<EquipmentSize>().in(EquipmentSize::getId,sizeList));;
                sizeMap = sizeIdToName.stream()
                        .collect(Collectors.toMap(EquipmentSize::getId, EquipmentSize::getName));
            }
            if (CollectionUtil.isNotEmpty(supplierList)){
                supplierIdToName=supplierService.list(new LambdaQueryWrapper<Supplier>().in(Supplier::getId,supplierList));;
                supplierMap = supplierIdToName.stream()
                        .collect(Collectors.toMap(Supplier::getId, Supplier::getName));
            }
            List<String> typeIdList=new ArrayList<>();
            for (UpdateOrderDetailReq detailReq:detailList){
                if (ObjectUtil.isEmpty(detailReq.getTypeName())){
                    detailReq.setTypeName(typeMap.isEmpty()?null:typeMap.get(detailReq.getTypeId()));
                }
                detailReq.setSizeName(sizeMap.isEmpty()?null:sizeMap.get(detailReq.getSizeId()));
                detailReq.setSupplierName(supplierMap.isEmpty()?null:supplierMap.get(detailReq.getSupplierId()));
                if ((ObjectUtil.isNotNull(detailReq.getTypeName()) || ObjectUtil.isNotEmpty(detailReq.getTypeName())) && !typeIdList.contains(detailReq.getTypeName())){
                    typeIdList.add(detailReq.getTypeName());
                }
            }
            reqInfo.setDetailList(detailList);

            reqInfo.setInvList(String.join(",",typeIdList));
            return createOrder(reqInfo);
        }
        catch (Exception e)
        {
            throw new JYZBAppException(JyzbV2ExceptionEnum.OPERATE_FAILED, ":" + e.getMessage());
        }
    }

    private String ConvertToV2OrderType(String type){
        switch (type){
            case "purchase":
                return "采购";
            case "gift":
                return "赠予";
            case "other":
                return "其他";
            case "allocate":
                return "库存调拨";
            case "repair":
                return "维修";
            case "return":
                return "归还";
            case "use":
                return "领用";
            case "remove":
                return "报废";
            case "destruction":
                return "销毁";
            default:
                return "";
        }
    }

    private UpdateOrderReq createReqInfo(AddAndApprovalBorrowOrderReq req,String orgName,String returnUserId,String returnUser){
        UpdateOrderReq updateOrderReq = new UpdateOrderReq();
        updateOrderReq.setBussinessType("use");
        updateOrderReq.setOrderType("out");
        updateOrderReq.setUseDate(DateTimeUtil.getCurrentDateTime());
        updateOrderReq.setReturnDate(req.getExpectedTime());
        updateOrderReq.setReturnUser(returnUser);
        updateOrderReq.setReturnUserId(returnUserId);
        updateOrderReq.setStartOrgId(req.getOrgId());
        updateOrderReq.setStartOrgName(orgName);
        updateOrderReq.setStartOrgUserId(req.getApplyId());
        SysUser sysUser = sysUserService.getById(req.getApplyId());
        if (ObjectUtil.isNotNull(sysUser)){
            updateOrderReq.setStartOrgUserName(sysUser.getNickName());
        }else {
            updateOrderReq.setStartOrgUserName(req.getApplyName());
        }
        updateOrderReq.setId(req.getId());
        return updateOrderReq;
    }

    private Boolean createOrder(UpdateOrderReq req){
        //判断是否有工作流id，如果有则将状态进行修改

        OrderMain order = new OrderMain();
        BeanPlusUtil.copyProperties(req, order);

        //先判断该单据id是否存在，如果存在，进行更新操作即可
        if (ObjectUtil.isNotNull(req.getId()) && ! req.getId().trim().isEmpty()){
            //删除子单据
            orderDetailService.remove(new LambdaQueryWrapper<OrderDetail>()
                    .eq(ObjectUtil.isNotNull(req.getId()),OrderDetail::getOrderId,req.getId()));
        }else {
            //设置id
            String id=UUID.randomUUID().toString();
            order.setId(id);
            //设置单据单号
            OrderNum orderNum = orderMainService.setOrderCode(req);
            long time = new Date().getTime() % 10000;
            String codeValue=String.format("%04d",orderNum.getNum());
            order.setOrderCode(orderNum.getBussinessType()+String.format("%04d",time)+orderNum.getYear()+
                    String.format("%02d", LocalDateTime.now().getMonth().getValue())+
                    String.format("%02d",LocalDateTime.now().getDayOfMonth())+codeValue);
        }

        //设置总价格和应出入库数量
        Integer sumNum=0;
        BigDecimal priceTotal=new BigDecimal(0);
        List<OrderDetail> detailList = new ArrayList<>();
        //通过遍历批量保存详细信息
        String s="";

        for (UpdateOrderDetailReq listReq:req.getDetailList()) {
            OrderDetail detail=new OrderDetail();
            if (ObjectUtil.isEmpty(listReq.getProductionDate())|| listReq.getProductionDate().trim().isEmpty()){
                listReq.setProductionDate(null);
            }
            BeanPlusUtil.copyProperties(listReq, detail);
            detail.setOrderId(order.getId());
            //设置单据类型
            detail.setType(order.getOrderType());
            //将数量和价格进行累加
            sumNum += detail.getPlanNum();
            detail.setSupplierId(req.getSupplierId());
            detail.setSupplierName(req.getSupplierName());
            priceTotal = priceTotal.add(detail.getTotalPrice()) ;
            detail.setCreateTime(new Date());
            //添加日志记录
            if (ObjectUtil.isNull(req.getLogSummaryId()) || req.getLogSummaryId()==null){
                s=s+"【"+listReq.getTypeName()+"--"+listReq.getSizeName()+"】预计数量："+listReq.getPlanNum()+"\n";
            }
            detailList.add(detail);
        }
        orderDetailService.saveBatch(detailList);
        //设置总价格和总数量
        order.setPrice(priceTotal);
        order.setInventoryQuantity(sumNum);
        order.setCreateTime(DateTimeUtil.getCurrentDateTime());
        order.setOrderState("ready");
        order.setExamineState("finished");
        String processInstanceId = null;

        //执行工作流
        processInstanceId= UUID.randomUUID().toString();
        order.setProcessId(processInstanceId);
        //list返回数据
        String userId="";
        //当前审核是否跳过
        Long orgId = req.getOrderType().equals("in")?req.getEndOrgId():Long.parseLong(req.getStartOrgId());

        if (ObjectUtil.isNotNull(req.getId()) && !req.getId().trim().isEmpty()) {
            orderMainService.updateById(order);
        } else {
            //保存
            //将创建人员添加（为的是将审核员创建的单子，审核员能看见）
            //将该组织机构下的所有仓管人员进行查询，并添加到historyAssign中
            String userIds=policemanService.searchUserByRoleId(orgId, JYZBConstant.GL_ROLR_ID);
            String userIdsList=policemanService.searchUserByRoleId(orgId,JYZBConstant.SH_ROLR_ID);


            userId=userIds;
            userId=userId+","+userIdsList;

            order.setHistoryAssign(userId);
            orderMainService.save(order);
        }

        //判断orderId在orderLog表中是否存在，如果存在，则直接替换
        //判断是否有流程id，如果有，则进行添加
        if (order.getProcessId()!=null && ObjectUtil.isNull(req.getLogSummaryId())){
            if (ObjectUtil.isNotEmpty(req.getId())){
                orderLogService.remove(new LambdaQueryWrapper<OrderLog>().eq(OrderLog::getOrderId,req.getId()));
            }
            boolean b = orderMainService.addOrderLog(req,order.getId(),order.getOrderCode(),s);
        }
        return true;
    }
}
