package com.sifang.modules.supply.warehouse.service;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.account.dao.TraderAccountDao;
import com.sifang.modules.account.entity.CrmTraderAccount;
import com.sifang.modules.flowable.service.ProcessFlowableService;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.flowpath.dao.BondApplyDao;
import com.sifang.modules.kingdee.service.MisDeliveryService;
import com.sifang.modules.kingdee.service.MiscellaneousService;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.DepartmentSettingDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmDepartment;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.setting.dao.CrmSupplyWarehouseDao;
import com.sifang.modules.supply.setting.entity.CrmSupplyWarehouse;
import com.sifang.modules.supply.stock.dao.MaterialStockDao;
import com.sifang.modules.supply.stock.dao.SupplyMaterialDao;
import com.sifang.modules.supply.stock.entity.MaterialWarehouseStocks;
import com.sifang.modules.supply.stock.entity.SupplyMaterial;
import com.sifang.modules.supply.stock.service.SupplyMaterialKeepService;
import com.sifang.modules.supply.warehouse.dao.CrmSupplyAllocationOrderDao;
import com.sifang.modules.supply.warehouse.dao.CrmSupplyAllocationOrderDetailDao;
import com.sifang.modules.supply.warehouse.dao.CrmSupplyAllocationOrderMsgDao;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyAllocationOrder;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyAllocationOrderDetail;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyMaterialKeep;
import com.sifang.modules.supply.warehouse.entity.SupplyMaterialBatch;
import com.sifang.modules.supply.warehouse.vo.*;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
public class CrmSupplyAllocationOrderService extends BaseService {

    @Autowired
    private CrmSupplyAllocationOrderDao allocationOrderDao;

    @Autowired
    private CrmSupplyAllocationOrderDetailDao allocationOrderDetailDao;

    @Autowired
    private CrmSupplyAllocationOrderMsgDao msgDao;

    @Autowired
    private SupplyMaterialDao materialDao;

    @Autowired
    private CrmSupplyWarehouseDao crmSupplyWarehouseDao;

    @Autowired
    private MaterialStockDao materialStockDao;

    @Autowired
    private SupplyMaterialKeepService materialKeepService;

    @Autowired
    TraderAccountDao accountDao;

    @Autowired
    TaskService taskService;
    @Autowired
    private ProcessFlowableService flowableService;

    @Autowired
    private SupplyMaterialBatchService batchService;
    @Autowired
    private DepartmentSettingDao departmentSettingDao;
    @Autowired
    private BondApplyDao bondApplyDao;



    public CrmSupplyAllocationOrder getById(String id){
        return allocationOrderDao.get(id);
    }

    public void saveOrder(CrmSupplyAllocationOrder order){
        allocationOrderDao.save(order);
    }

    public void allocationOrderList(LayuiPage<Record> page, Map<String, String> map,User user) {
        List<Record> list = allocationOrderDao.getOrderList(page, map,user);
        page.setData(list);
        page.setCount(allocationOrderDao.contOrderList(map));
    }

    public List<AddAllocationDetailVo> getWarehouseStock(List<AddAllocationDetailVo> detailVos, String warehouseId) {
        List<String> materialIds = new ArrayList<>();
        for (AddAllocationDetailVo detailVo : detailVos) {
            materialIds.add(detailVo.getMaterialId());
        }
        Map<String, BigDecimal> stockMap = new HashMap<>();
        List<Record> listStock = Db.find(" SELECT material_id ,warning FROM `crm_supply_material_warehouse_stocks` WHERE warehouse_id=? AND material_id IN (" + StringUtil.joinInSql(materialIds.toArray(new String[materialIds.size()])) + ")   ", warehouseId);
        for (Record record : listStock) {
            stockMap.put(record.getStr("material_id"), record.getBigDecimal("warning"));
        }
        for (AddAllocationDetailVo detailVo : detailVos) {
            String materialId = detailVo.getMaterialId();
            BigDecimal stock = stockMap.get(materialId);
            if (stock == null) {
                detailVo.setWarehouseStock(BigDecimal.ZERO);
            } else {
                detailVo.setWarehouseStock(stock);
            }
        }
        return detailVos;
    }

    @Transactional(rollbackFor = Exception.class)
    public void addAllocationOrder(AddAllocationOrderVo orderVo) {
        checkBeforSave(orderVo);
        User user = UserUtils.getUser();
        CrmDepartment dep = departmentSettingDao.get(user.getDepartmentId());
        if(dep ==null){
            throw new BusinessException("当前用户无操作权限");
        }
        CrmSupplyAllocationOrder allocationOrder;

        Date date = new Date();
        String xm = CrmUtils.getUserXM(user);
        // 创建明细
        List<PurchaseOrderDetailVo> details = orderVo.getDetails();
        if (StringUtil.isBlank(orderVo.getId())) {
            allocationOrder = new CrmSupplyAllocationOrder();
            allocationOrder.setId(IdGen.uuid());
            allocationOrder.setCode(PlantformUtils.findOrderNumber("DB"));
            allocationOrder.setOrderStatus(OrderConstant.STATUS_DSH);//待审核
            allocationOrder.setStatus(OrderConstant.FLOW_FLOSTATUS_DSH);
            allocationOrder.setCreateBy(user.getId());
            allocationOrder.setCreateTime(date);
            allocationOrder.setCreator(xm);
            allocationOrder.setDepartmentId(user.getDepartmentId());
            allocationOrder.setDepartmentName(dep.getName());
        } else {
            allocationOrder = allocationOrderDao.get(orderVo.getId());
            if (!allocationOrder.getStatus().equals("0")) {
                throw new BusinessException("订单不支持编辑操作！");
            }
            allocationOrder.setOrderStatus(OrderConstant.STATUS_DSH);//待审核
            allocationOrder.setStatus(OrderConstant.FLOW_FLOSTATUS_DSH);
        }
        allocationOrder.setWarehouseId(orderVo.getWarehouseId());
        CrmSupplyWarehouse warehouse = crmSupplyWarehouseDao.get(orderVo.getWarehouseId());
        allocationOrder.setWarehouseName(warehouse.getName());
        allocationOrder.setOutName(warehouse.getAscriptionName());
        allocationOrder.setOutAscriptionId(warehouse.getAscriptionId());

        allocationOrder.setInWarehouseId(orderVo.getInWarehouseId());
        CrmSupplyWarehouse inWarehouse = crmSupplyWarehouseDao.get(orderVo.getInWarehouseId());
        if(!"1".equals(inWarehouse.getType())){
            //判断调入方是否有账户
            CrmTraderAccount account = accountDao.findByTraderId(inWarehouse.getAscriptionId());
            if(account== null){
                throw new BusinessException("请新增调入方的可授信额度！");
            }
        }
        allocationOrder.setInWarehouseName(inWarehouse.getName());
        allocationOrder.setInAscriptionId(inWarehouse.getAscriptionId());

        allocationOrder.setInName(inWarehouse.getAscriptionName());
        allocationOrder.setRemarks(orderVo.getRemark());

        //保存申请的物料种类  和数量
        BigDecimal total = BigDecimal.ZERO;
        for (PurchaseOrderDetailVo detail : details) {
            total = total.add(detail.getAmount());
        }
        allocationOrder.setMaterialTypeAmount(new BigDecimal(details.size()));
        allocationOrder.setTotalApplyAmount(total);
        if (StringUtil.isBlank(orderVo.getId())) {
            String str=StringUtil.isNotBlank(orderVo.getRemark())?"创建调拨单 备注："+orderVo.getRemark():"创建调拨单";
            msgDao.addMsg(user, OrderConstant.TYPE_XZ, allocationOrder.getId(), str, "");
            //提交流程
            Record rd = FormUtils.getdefLatest(FormUtils.TRANSFER_ORDER_APPLICATION);
            if(rd == null){
                throw  new RuntimeException("流程未定义，不可发布申请");
            }
            //启动流程
            String processName="调拨单申请-"+user.getUserName()+'-'+ DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss");
            String processInstanceId=flowableService.startProcessFlowable(user,allocationOrder.getId(),rd, FormUtils.TRANSFER_ORDER_APPLICATION,date,xm,orderVo.getRemark(),processName,inWarehouse.getAscriptionId());
            allocationOrder.setProcessInstanceId(processInstanceId);
            allocationOrder.setProcessDefId(rd.getStr("id"));

            allocationOrder.setOperateUserIds(user.getId()+","+rd.getStr("oneAuditUseId"));
            String taskName=FormUtils.getOneStepTaskName(rd.getStr("id"));
            allocationOrder.setTaskName(taskName);
        } else {
            msgDao.addMsg(user, OrderConstant.TYPE_BJ, allocationOrder.getId(), "编辑调拨单，重新提交 ", "");
            allocationOrderDao.updateBySql("update crm_supply_allocation_order_detail set status = '0' where inventory_id=:p1 ", new Parameter(orderVo.getId()));
            if(StringUtil.isNotBlank(allocationOrder.getProcessInstanceId())){
                Task task = taskService.createTaskQuery().processInstanceId(allocationOrder.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
                flowableService.approveTask2(task,"编辑后提交",allocationOrder.getId(),user, FormUtils.TRANSFER_ORDER_APPLICATION);
            }
        }
        allocationOrderDao.save(allocationOrder);
        List<CrmSupplyAllocationOrderDetail> saveList = new ArrayList<>();
        int i = 0;
        for (PurchaseOrderDetailVo detail : details) {
            i++;
            CrmSupplyAllocationOrderDetail orderDetail = new CrmSupplyAllocationOrderDetail();
            orderDetail.setInventoryId(allocationOrder.getId());
            orderDetail.setMaterialId(detail.getMaterialId());
            orderDetail.setMaterialCode(detail.getMaterialCode());
            orderDetail.setMaterialType(detail.getMaterialType());
            orderDetail.setMaterialRemarks(detail.getMaterialRemark());
            orderDetail.setMaterialUnit(detail.getMaterialUnit());
            orderDetail.setStock(detail.getMaterialStock());
            orderDetail.setAmount(detail.getAmount());
            orderDetail.setSort(i);

            MaterialWarehouseStocks warehouseStocks = materialStockDao.getByHql(" from MaterialWarehouseStocks where materialId = :p1 AND warehouseId = :p2", new Parameter(detail.getMaterialId(), allocationOrder.getWarehouseId()));
            orderDetail.setCostPrice(warehouseStocks.getCostPrice());
            orderDetail.setBdSalePrice(warehouseStocks.getBdSalePrice());
            saveList.add(orderDetail);
        }
        allocationOrderDetailDao.save(saveList);


    }

    public void checkBeforSave(AddAllocationOrderVo orderVo) {
        List<PurchaseOrderDetailVo> details = orderVo.getDetails();
        int index = 1;
        for (PurchaseOrderDetailVo detail : details) {
            SupplyMaterial material = materialDao.get(detail.getMaterialId());
            if (!StrKit.notNull(material)) {
                throw new BusinessException("第" + index + "行物料不存在");
            }
            if (BigDecimal.ZERO.compareTo(detail.getAmount()) == 0) {
                throw new BusinessException("第" + index + "行调拨数量不能为零");
            }
            if (detail.getMaterialStock().compareTo(detail.getAmount()) < 0) {
                throw new BusinessException("第" + index + "行调拨数量不能大于库存数量");
            }
            index++;
        }
    }

    public CrmSupplyAllocationOrder getOrderDetail(String id) {
        CrmSupplyAllocationOrder order = allocationOrderDao.get(id);
        return order;
    }

    public List<Record> getMaterialList(String orderId) {
        return allocationOrderDetailDao.getDetailList(orderId);
    }

    public List<Record> getMaterialList2(String orderId,String warehouseId){
      return allocationOrderDetailDao.getMaterialList2(orderId,warehouseId);
    }

    public List<Record> getMsgs(String orderId) {
        return msgDao.getMsgs(orderId);
    }

    public List<Record> getWarehouseStock2(List<Record> detailVos, String warehouseId) {
        List<String> materialIds = new ArrayList<>();
        for (Record detailVo : detailVos) {
            materialIds.add(detailVo.getStr("material_id"));
        }
        Map<String, BigDecimal> stockMap = new HashMap<>();
        List<Record> listStock = Db.find(" SELECT material_id ,warning FROM `crm_supply_material_warehouse_stocks` WHERE warehouse_id=? AND material_id IN (" + StringUtil.joinInSql(materialIds.toArray(new String[materialIds.size()])) + ")   ", warehouseId);
        for (Record record : listStock) {
            stockMap.put(record.getStr("material_id"), record.getBigDecimal("warning"));
        }
        for (Record detailVo : detailVos) {
            String materialId = detailVo.getStr("material_id");
            BigDecimal stock = stockMap.get(materialId);
            if (stock == null) {
                detailVo.set("stock", BigDecimal.ZERO);
            } else {
                detailVo.set("stock", stock);
            }
        }
        return detailVos;
    }

    @Transactional(rollbackFor = Exception.class)
    public void outAllocationOrder(OutAllocationOrderVo allocationOrderVo,User user) {
        CrmSupplyAllocationOrder allocationOrder = allocationOrderDao.get(allocationOrderVo.getId());
        String userXm=CrmUtils.getUserXM(user);
        if (allocationOrder == null) {
            throw new BusinessException(" 调拨单不存在！");
        }
        if (!OrderConstant.STATUS_DCK.equals(allocationOrder.getOrderStatus())) {
            throw new BusinessException(" 订单状态不支持出库操作！");
        }
        List<CrmSupplyAllocationOrderDetail> details = allocationOrderDetailDao.getDetail(allocationOrderVo.getId());

        List<OutAllocationMaterialVo> detailVos = allocationOrderVo.getDetails();
        Map<String, OutAllocationMaterialVo> voMap = new HashMap<>();
        for (OutAllocationMaterialVo vo : detailVos) {
            voMap.put(vo.getId(), vo);
        }
        BigDecimal xsCount = BigDecimal.ZERO;
        StringBuffer str = new StringBuffer(userXm + " 操作出库 出库的有：");
        for (CrmSupplyAllocationOrderDetail detail : details) {
            OutAllocationMaterialVo outVo = voMap.get(detail.getId());
            if (outVo == null) {
                throw new BusinessException(" 该出库不存在请刷新页面 ！");
            }
          /*  if (outVo.getStock().compareTo(outVo.getOutAmount()) < 0) {
                throw new BusinessException(" 调拨数量不可大于库存数量 ！");
            }*/
            detail.setInoutAmount(outVo.getOutAmount());
            detail.setLocation(outVo.getLocation());
            BigDecimal outAmount = outVo.getOutAmount();
            logger.info(">>>>>>>>>>>>>>>>>>>操作出库 warehouseId：{},materialId:{},outAmount:{}", allocationOrder.getWarehouseId(), outVo.getMaterialId(), outAmount);
            MaterialWarehouseStocks warehouseStocks = materialStockDao.getByHql(" from MaterialWarehouseStocks where materialId = :p1 AND warehouseId = :p2", new Parameter(outVo.getMaterialId(), allocationOrder.getWarehouseId()));
            if (warehouseStocks == null) {
                throw new BusinessException(" 仓库里面没有该物料 ！");
            }
            if (warehouseStocks.getWarning().compareTo(outVo.getOutAmount()) < 0) {
                throw new BusinessException(" 库存数量不足 ！");
            }
            detail.setStock(warehouseStocks.getWarning());
            int row = materialStockDao.update("update MaterialWarehouseStocks set warning=warning-:p1, " +
                            "realNum=realNum-:p2,newestKeepTime=:p3 where materialId=:p4 and warehouseId=:p5",
                    new Parameter(outAmount, outAmount, new Date(),outVo.getMaterialId(), allocationOrder.getWarehouseId()));
            if (row <= 0) {
                throw new BusinessException("库存释放失败");
            }

            SupplyMaterial material = materialDao.get(detail.getMaterialId());
            detail.setUnitCode(material.getUnitCode());
            List<SupplyMaterialBatch> batches = batchService.findBatchesByFIFO(detail.getMaterialId(), allocationOrder.getWarehouseId(), outAmount);

            for (SupplyMaterialBatch batch : batches) {
                logger.info(">>>>>>>>>>>>bach:{}",batch.getId());
                if (outAmount.compareTo(BigDecimal.ZERO) <= 0) {
                    break;
                }

                //入库记录id
                String keepId = IdGen.uuid();
                //可出库数量
                BigDecimal canOutNum = batch.getRemaining();
                //实际出库数量
                BigDecimal outNum = outAmount.compareTo(canOutNum) > 0 ? canOutNum : outAmount;
                outAmount = outAmount.subtract(outNum);
                //修改批次记录
                //扣减批次
                batchService.outStockForInventory(batch, outNum);
                //生成出库记录
                CrmSupplyMaterialKeep keep = materialKeepService.createAllocationMatKeep(allocationOrder,detail,outNum, canOutNum,user,"2",batch,keepId);
                //自选物料不参与授信额计算
                if ("0".equals(material.getMaterialAttribute())) {
                    xsCount=xsCount.add(outNum.multiply(batch.getBdSalePrice()));//出库数量*当前批次的销售价
                }
            }

            str.append(detail.getMaterialCode() + " 出库数量：" + outVo.getOutAmount() + ";该库存量：" + detail.getStock() + ";");
            allocationOrderDetailDao.save(detail);
        }
        allocationOrder.setReceivingImg(allocationOrderVo.getReceivingImg());
        allocationOrder.setDeliveryMethod(allocationOrderVo.getDeliveryMethod());

        allocationOrder.setDeliverDriver(allocationOrderVo.getDeliverDriver());
        allocationOrder.setDeliverMobile(allocationOrderVo.getDeliverMobile());
        allocationOrder.setDeliverCarNum(allocationOrderVo.getDeliverCarNum());

        allocationOrder.setLogisticsNo(allocationOrderVo.getLogisticsNo());
        allocationOrder.setDeliverRemarks(allocationOrderVo.getExamineRemark());
        allocationOrder.setOutTime(new Date());
        allocationOrder.setOrderStatus(OrderConstant.STATUS_DRK);

       /* //现在这个不要了，入库推直接调拨单
       if("a".equals(allocationOrder.getOutAscriptionId())){
            try {
                CrmSupplyWarehouse outWarehouse = crmSupplyWarehouseDao.get(allocationOrder.getWarehouseId());
                String id =  misDeliveryService.saveOutAllocaOrderToKingDee(allocationOrder,details,outWarehouse);
                allocationOrder.setKingDeeId(id);
            } catch (Exception e) {
                logger.error("调拨出库 异常："+e.getMessage());
                throw new BusinessException(" 调拨出库库同步金蝶数据异常 ！");
            }
        }*/

        allocationOrderDao.save(allocationOrder);
        msgDao.addMsg(user, OrderConstant.TYPE_CK, allocationOrder.getId(),  "调拨单出库，发货备注：" + allocationOrderVo.getExamineRemark(), str.toString());
        //释放代理商的可授信额度
        if(!"a".equals(allocationOrder.getOutAscriptionId())){
            CrmTraderAccount account = accountDao.findByTraderId(allocationOrder.getOutAscriptionId());
            if(account== null){
                throw new BusinessException("请新增调出方的可授信额度！");
            }
            account.setBasicQuotaAmountBalance(account.getBasicQuotaAmountBalance().add(xsCount));
            account.setMaxQuotaAmountBalance(account.getMaxQuotaAmountBalance().add(xsCount));
            accountDao.save(account);
        }

    }
    /**
     * 删除 调拨订单
    */
    public void deleteOrder(String orderId,User user){
        CrmSupplyAllocationOrder allocationOrder = allocationOrderDao.get(orderId);

        List<CrmSupplyAllocationOrderDetail> details = allocationOrderDetailDao.getDetail(orderId);
        for(CrmSupplyAllocationOrderDetail detail : details){
            //冻结库存
            MaterialWarehouseStocks warehouseStocks = materialStockDao.getByHql(" from MaterialWarehouseStocks where materialId = :p1 AND warehouseId = :p2", new Parameter(detail.getMaterialId(), allocationOrder.getWarehouseId()));
            if (warehouseStocks == null) {
                throw new BusinessException(" 仓库里面没有该物料 ！");
            }

            detail.setStock(warehouseStocks.getWarning());
            warehouseStocks.setWarning(warehouseStocks.getWarning().add(detail.getInoutAmount()));
            warehouseStocks.setFrozeOutNum(warehouseStocks.getFrozeOutNum().subtract(detail.getInoutAmount()));
            materialStockDao.save(warehouseStocks);
        }
        allocationOrder.setStatus(OrderConstant.STATUS_DELETE);
        msgDao.addMsg(user,OrderConstant.TYPE_DELETE,orderId,"手动删除调拨订单","");
        allocationOrderDetailDao.updateBySql("update crm_supply_allocation_order_detail set status = '0' where inventory_id=:p1 ",new Parameter(orderId));
        allocationOrderDao.save(allocationOrder);
    }



    @Transactional(rollbackFor = Exception.class)
    public void inAllocationOrder(OutAllocationOrderVo allocationOrderVo,User user) {
        String userXm=CrmUtils.getUserXM(user);
        CrmSupplyAllocationOrder allocationOrder = allocationOrderDao.get(allocationOrderVo.getId());
        if (allocationOrder == null) {
            throw new BusinessException(" 调拨单不存在！");
        }
        if (!OrderConstant.STATUS_DRK.equals(allocationOrder.getOrderStatus())) {
            throw new BusinessException(" 订单状态不支持入库操作！");
        }
        List<CrmSupplyAllocationOrderDetail> details = allocationOrderDetailDao.getDetail(allocationOrderVo.getId());

        List<OutAllocationMaterialVo> detailVos = allocationOrderVo.getDetails();
        Map<String, OutAllocationMaterialVo> voMap = new HashMap<>();
        for (OutAllocationMaterialVo vo : detailVos) {
            voMap.put(vo.getId(), vo);
        }
        StringBuffer str = new StringBuffer(userXm + " 操作入库 入库的有：");
        BigDecimal xsCount = BigDecimal.ZERO;
        for (CrmSupplyAllocationOrderDetail detail : details) {
            OutAllocationMaterialVo outVo = voMap.get(detail.getId());
            if (outVo == null) {
                throw new BusinessException(" 该入库不存在请刷新页面 ！");
            }
            String keepId =IdGen.uuid();
            logger.info(">>>>>>>>>>>>>>>>>>>操作入库 warehouseId：{},materialId:{},Amount:{}", allocationOrder.getInWarehouseId(), outVo.getMaterialId(), detail.getInoutAmount());
            CrmSupplyWarehouse warehouse = crmSupplyWarehouseDao.get(allocationOrder.getInWarehouseId());
           //更新仓库库位
            // 仓库归属 1.供应链(平台) 2.经销商 3.供应商
            String sType = ("1".equals(warehouse.getType())) ? "1" : ("2".equals(warehouse.getType())?"3":"2");
            MaterialWarehouseStocks stocks = materialStockDao.findByWarehouse(detail.getMaterialId(), warehouse.getId());
            if(stocks==null){
                stocks=new MaterialWarehouseStocks();
                stocks.setMaterialId(detail.getMaterialId());
                stocks.setWarehouseId(warehouse.getId());
                stocks.setType(sType);
                stocks.setAscriptionId(warehouse.getAscriptionId());
                stocks.setAscriptionName(warehouse.getAscriptionName());
                stocks.setWarning(outVo.getOutAmount());
                stocks.setRealNum(outVo.getOutAmount());
                stocks.setTotal(outVo.getOutAmount());
                stocks.setCreateBy(user.getId());
                stocks.setCreateTime(new Date());
                stocks.setNewestStorageTime(new Date());
                stocks.setCostPrice(detail.getCostPrice());
                stocks.setBdSalePrice(detail.getBdSalePrice());
                materialStockDao.save(stocks);
            }else{

                BigDecimal amount=outVo.getOutAmount();

                int row = materialStockDao.update("update MaterialWarehouseStocks set warning=warning+:p1, " +
                                "realNum=realNum+:p2,total=total+:p3,newestStorageTime=now() where materialId=:p4 and warehouseId=:p5",
                        new Parameter(amount, amount,amount, detail.getMaterialId(), warehouse.getId()));
                logger.info(">>>>>>>>>>>>>>>>>>>操作入库 amount:{},material:{},warehouserId:{},row:{}",amount,detail.getMaterialId(),warehouse.getId(),row);
                if (row <= 0) {
                    throw new BusinessException("更新库存失败");
                }
              //  stocks.setNewestStorageTime(new Date());
            }

            //调拨 入库 生成新批次
            SupplyMaterialBatch batch = batchService.createBatchForAllocationOrder(allocationOrder, detail,warehouse, keepId);
            //生成入库记录
            CrmSupplyMaterialKeep keep = materialKeepService.createAllocationInKeep(allocationOrder,detail,outVo.getOutAmount(),user,"1",batch,keepId);
            SupplyMaterial material = materialDao.get(detail.getMaterialId());
            detail.setUnitCode(material.getUnitCode());
            //自选物料不参与授信额计算
            if ("0".equals(material.getMaterialAttribute())) {
                xsCount=xsCount.add(outVo.getOutAmount().multiply(detail.getBdSalePrice()));
            }
            str.append(detail.getMaterialCode() + " 入库数量：" + outVo.getOutAmount() + ";");

        }
        //修改代理商的可授信额度
        if(!"a".equals(allocationOrder.getInAscriptionId())){
            CrmTraderAccount account = accountDao.findByTraderId(allocationOrder.getInAscriptionId());
            if(account== null){
                throw new BusinessException("请新增调入方的可授信额度！");
            }
            account.setBasicQuotaAmountBalance(account.getBasicQuotaAmountBalance().subtract(xsCount));
            account.setMaxQuotaAmountBalance(account.getMaxQuotaAmountBalance().subtract(xsCount));
            accountDao.save(account);
        }

        allocationOrder.setInReceivingImg(allocationOrderVo.getReceivingImg());
        allocationOrder.setInTime(new Date());
        allocationOrder.setInRemarks(allocationOrderVo.getExamineRemark());
        allocationOrder.setOrderStatus(OrderConstant.STATUS_YWC);
        allocationOrderDao.save(allocationOrder);
        msgDao.addMsg(user, OrderConstant.TYPE_RK, allocationOrder.getId(),  "调拨单入库，入库说明：" + allocationOrderVo.getExamineRemark(), str.toString());

    }

    public MaterialWarehouseStocks findWatehouseStock(String materialId, String warehouseId, User user) {
        MaterialWarehouseStocks warehouseStocks = materialStockDao.getByHql(" from MaterialWarehouseStocks where materialId = :p1 AND warehouseId = :p2", new Parameter(materialId, warehouseId));
        if (warehouseStocks == null) {
            warehouseStocks = new MaterialWarehouseStocks();
            CrmSupplyWarehouse warehouse = crmSupplyWarehouseDao.get(warehouseId);
            // 仓库归属 1.供应链 2.代理商 3.供应商
            // 库存归属 1.供应链 2.供应商 3.代理商
            // 需要转换一下...
            String wType = warehouse.getType();
            String type = "1".equals(wType) ? wType : ("2".equals(wType) ? "3" : "2");
            warehouseStocks.setMaterialId(materialId);
            warehouseStocks.setWarehouseId(warehouseId);
            warehouseStocks.setType(type);
            warehouseStocks.setAscriptionId(warehouse.getAscriptionId());
            warehouseStocks.setAscriptionName(warehouse.getAscriptionName());
            warehouseStocks.setCreateTime(new Date());
            warehouseStocks.setCreateBy(user.getId());
        }
        return warehouseStocks;
    }


    @Transactional(rollbackFor = Exception.class)
    public void deleteAllocationOrder(String orderIds,String type) {
        String[] arr=orderIds.split(",");

        User user = UserUtils.getUser();
        if("system".equals(type)){
            deleteOrder(orderIds,user);
        }else {
            for(String id:arr){
                CrmSupplyAllocationOrder allocationOrder=allocationOrderDao.get(id);
                if(!OrderConstant.STATUS_WTG.equals(allocationOrder.getStatus())){
                    throw new BusinessException(" 您选择的有不能操作删除的采购订单，请重新选择! ");
                }
                allocationOrder.setStatus(OrderConstant.STATUS_DELETE);
                msgDao.addMsg(user,OrderConstant.TYPE_DELETE,id,"删除调拨订单","");
                allocationOrderDetailDao.updateBySql("update crm_supply_allocation_order_detail set status = '0' where inventory_id=:p1 ",new Parameter(id));
            }
        }
    }

    private void setAuditInfo(CrmSupplyAllocationOrder order) {
        Date date = new Date();
        User user = UserUtils.getUser();
        order.setAuditBy(user.getId());
        order.setAuditName(CrmUtils.getUserXM(user));
        order.setAuditTime(date);
    }

    @Transactional(rollbackFor = Exception.class)
    public void firstAudit(String id,String content) {
        User user = UserUtils.getUser();
        CrmSupplyAllocationOrder order=allocationOrderDao.get(id);
        checkStatusBeforeAudit(order);
        //  order.setStatus(InventoryOrderConstants.WAIT_AUDIT_2);
        setAuditInfo(order);
        Date date=new Date();
        //审批通过
       /* flowableService.approveTask(order.getTaskId(),content,order.getId(),user,date,FormUtils.TRANSFER_ORDER_APPLICATION,order.getProcessDefId());
        Task vacationApply = taskService.createTaskQuery().processInstanceId(order.getProcessInstanceId()).singleResult();
        if(vacationApply!=null){
            order.setTaskName(vacationApply.getName());
            order.setTaskId(vacationApply.getId());
        }*/
        allocationOrderDao.save(order);
        Task task = taskService.createTaskQuery().processInstanceId(order.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
        flowableService.approveTask2(task,content,order.getId(),user, FormUtils.TRANSFER_ORDER_APPLICATION);
        msgDao.addMsg(user, OrderConstant.TYPE_SH, order.getId(), "审核通过","");
    }

    private void checkStatusBeforeAudit(CrmSupplyAllocationOrder order) {
        if (!StrKit.notNull(order)) {
            throw new BusinessException("调拨单不存在");
        }
        if (!OrderConstant.STATUS_DSH.equals(order.getOrderStatus())) {
            throw new BusinessException("调拨单状态发生改变");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void reject(String id,String taskId, String reason) {
        User user = UserUtils.getUser();
        CrmSupplyAllocationOrder order=allocationOrderDao.get(id);
        checkStatusBeforeAudit(order);
        order.setOrderStatus(OrderConstant.STATUS_WTG);
        order.setReasonsForFailure(reason);
        setAuditInfo(order);
        /*flowableService.rejectTask(taskId,reason,id,user,FormUtils.TRANSFER_ORDER_APPLICATION);
        Task vacationApply = taskService.createTaskQuery().processInstanceId(order.getProcessInstanceId()).singleResult();
        if(vacationApply!=null){
            order.setTaskName(vacationApply.getName());
            order.setTaskId(vacationApply.getId());
        }*/
        allocationOrderDao.save(order);
        msgDao.addMsg(user, OrderConstant.TYPE_SHWTG, order.getId(), reason,"");
        Task task = taskService.createTaskQuery().processInstanceId(order.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
        flowableService.rejectTask2(task,reason,id,user,FormUtils.TRANSFER_ORDER_APPLICATION,order.getCreateBy());
    }



}
