package com.huaheng.api.SSP.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaheng.api.SSP.domain.ConfirmHeaderModel;
import com.huaheng.api.SSP.domain.ConfirmModel;
import com.huaheng.api.SSP.domain.ConfirmTypeModel;
import com.huaheng.common.exception.service.ServiceException;
import com.huaheng.common.utils.security.ShiroUtils;
import com.huaheng.framework.web.domain.AjaxResult;
import com.huaheng.pc.config.company.mapper.WarehouseCompanyMapperAuto;
import com.huaheng.pc.config.company.service.CompanyService;
import com.huaheng.pc.config.location.domain.Location;
import com.huaheng.pc.config.location.service.LocationService;
import com.huaheng.pc.config.warehouseCompany.domain.WarehouseCompany;
import com.huaheng.pc.config.warehouseCompany.service.WarehouseCompanyService;
import com.huaheng.pc.config.zone.domain.SSPdetail;
import com.huaheng.pc.config.zone.domain.SSPheader;
import com.huaheng.pc.config.zone.mapper.SSPdetailMapperAuto;
import com.huaheng.pc.config.zone.mapper.SSPheaderMapperAuto;
import com.huaheng.pc.inventory.inventoryDetail.domain.InventoryDetail;
import com.huaheng.pc.inventory.inventoryDetail.service.InventoryDetailService;
import com.huaheng.pc.inventory.inventoryHeader.service.InventoryHeaderService;
import com.huaheng.pc.inventory.inventoryTransaction.service.InventoryTransactionService;
import com.huaheng.pc.receipt.receiptDetail.domain.ReceiptDetail;
import com.huaheng.pc.receipt.receiptDetail.service.ReceiptDetailService;
import com.huaheng.pc.receipt.receiptHeader.domain.ReceiptHeader;
import com.huaheng.pc.receipt.receiptHeader.service.ReceiptHeaderService;
import com.huaheng.pc.shipment.shipmentDetail.domain.ShipmentDetail;
import com.huaheng.pc.shipment.shipmentDetail.service.ShipmentDetailService;
import com.huaheng.pc.shipment.shipmentHeader.domain.ShipmentHeader;
import com.huaheng.pc.shipment.shipmentHeader.service.ShipmentHeaderService;
import com.huaheng.pc.task.taskDetail.domain.TaskDetail;
import com.huaheng.pc.task.taskDetail.service.TaskDetailService;
import com.huaheng.pc.task.taskHeader.domain.TaskHeader;
import com.huaheng.pc.task.taskHeader.service.TaskHeaderService;
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.util.List;

/**
 * 钱柜出入库单回传接口Service
 * 1.此Service的作用是钱柜完成系统下发的出入库单后进行回传,回传逻辑是先存进钱柜的临时表中,存进钱柜临时表不按出入库单区分,无论数量是否溢出是否有误,但若单据非第
 * 一次回传至临时表,则在主表中判断该订单是否已经完成。并根据单据增加或减少数量。而后进行库存的修改,并在库存临时表中增加库存修改记录。
 */
@Service
@Transactional
public class OrderConfirmApiService {

    @Resource
    private WarehouseCompanyMapperAuto warehouseCompanyMapperAuto;

    @Autowired
    ReceiptDetailService receiptDetailService;

    @Autowired
    ReceiptHeaderService receiptHeaderService;

    @Autowired
    ShipmentDetailService shipmentDetailService;

    @Autowired
    ShipmentHeaderService shipmentHeaderService;

    @Resource
    private SSPheaderMapperAuto ssPheaderMapperAuto;

    @Resource
    private SSPdetailMapperAuto ssPdetailMapperAuto;

    @Autowired
    LocationService locationService;

    @Autowired
    InventoryDetailService inventoryDetailService;

    @Autowired
    InventoryHeaderService inventoryHeaderService;
    @Autowired
    CompanyService companyService;

    @Autowired
    InventoryTransactionService inventoryTransactionService;

    @Autowired
    TaskHeaderService taskHeaderService;

    @Autowired
    TaskDetailService taskDetailService;
    @Autowired
    WarehouseCompanyService warehouseCompanyService;

    //订单回传
    public AjaxResult ocfm(ConfirmModel cfm) throws Exception {
        ConfirmHeaderModel headerModel = cfm.getConfirmHeaderModel();
        List<ConfirmTypeModel> typeModels =  cfm.getOrderItems();
        if (headerModel == null||typeModels == null){
            return AjaxResult.error("订单头表为空或订单明细表为空!");
        }if (headerModel.getCubeCode()==null||headerModel.getCubeCode()==""){
            return AjaxResult.error("钱柜编码不能为空!");
        }if (headerModel.getId()==null||headerModel.getId()==""){
            return AjaxResult.error("钱柜系统主表标识不能为空!");
        }if (headerModel.getOrderHeaderId()<1){
            return AjaxResult.error("订单头表标识不能为空!");
        }if (headerModel.getOrderCode()==null||headerModel.getOrderCode()==""){
            return AjaxResult.error("订单编码不能为空!");
        }if (!headerModel.getOrderType().equals("receipt")&&!headerModel.getOrderType().equals("shipment")){
            return AjaxResult.error("订单类型错误!");
        }if (headerModel.getfDatetime()==null||headerModel.getcDatetime()==""){
            return AjaxResult.error("完成的时间不能为空!");
        }if (headerModel.getcDatetime()==null||headerModel.getcDatetime()==""){
            return AjaxResult.error("交互的当前时间不能为空!");
        }
        String wc = headerModel.getWarehouseCode();
        if (wc==null||wc==""){
            return AjaxResult.error("warehouseCode不能为空!!");
        }

        WarehouseCompany warehouseCompany = new WarehouseCompany();
        warehouseCompany.setWarehouseCode(wc);
        WarehouseCompany list = warehouseCompanyMapperAuto.selectFirstEntity(warehouseCompany);
        if (list == null) {
            return AjaxResult.error("系统中没有该仓库:" + warehouseCompany.toString() + "  信息,请先录入仓库信息!");
        }
        //TaskHeader task=taskHeaderService.selectEntityById(headerModel.getOrderHeaderId());
        //TaskHeader taskHeader = taskHeaderService.list(new LambdaQueryWrapper<TaskHeader>().eq(TaskHeader::getId, headerModel.getOrderHeaderId())).get(0);
        TaskHeader taskHeader = taskHeaderService.getById(headerModel.getOrderHeaderId());
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setCode(0);
        ajaxResult.setMsg("接收完成");
        taskHeaderService.completeTask(taskHeader);
        return ajaxResult;
    }

    @Transactional
    public AjaxResult receipt(SSPheader chm,List<ConfirmTypeModel> ctmlist){
        int firstStatus = 200;
        int lastStatus = 800;
        for (ConfirmTypeModel ctm : ctmlist){
            if (ctm.getItemId()==null||ctm.getItemId()==""){
                return AjaxResult.error("钱柜系统明细标识不能为空!");
            }if (ctm.getOrderDetailId()<1){
                return AjaxResult.error("订单明细表标识不能为空!");
            }if (ctm.getCompanyCode()==null||ctm.getCompanyCode()==""){
                return AjaxResult.error("货主编码不能为空!");
            }if (ctm.getContainerCode()==null||ctm.getContainerCode()==""){
                return AjaxResult.error("容器编码不能为空!");
            }if (ctm.getItemCode()==null||ctm.getItemCode()==""){
                return AjaxResult.error("商品编码不能为空!");
            }if (ctm.getItemBarcode()==null||ctm.getItemBarcode()=="") {
                return AjaxResult.error("商品条码不能为空!");
            }
            SSPheader sh = new SSPheader();
            sh.sethID(chm.gethID());
            sh.setOrderHeaderId(chm.getOrderHeaderId());
            sh.setOrderType(chm.getOrderType());
            //组合入库子单
            SSPdetail sd = new SSPdetail();
            sd.setItemId(ctm.getItemId());
            sd.setOrderDetailId(ctm.getOrderDetailId());
            sd.setOrderHeaderId(chm.getOrderHeaderId());
            sd.setCompanyCode(ctm.getCompanyCode());
            sd.setContainerCode(ctm.getContainerCode());
            sd.setItemCode(ctm.getItemCode());
            sd.setItemName(ctm.getItemName());
            sd.setItemBarcode(ctm.getItemBarcode());
            sd.setItemState("good");
            sd.setQty(ctm.getQty());
            sd.setItemUnit(ctm.getItemUnit());
            sd.setOrderType("receipt");
            String type="receipt";
//            判断系统中是否已有该主单,若无则新增
//            try {

                if (ssPheaderMapperAuto.selectListEntityByEqual(sh).size()<1){
                    //给临时表新增该入库单据
                    ssPheaderMapperAuto.insert(chm);
                    ssPdetailMapperAuto.insert(sd);

                    //ReceiptDetail receiptDetail = receiptDetailService.selectEntityById(ctm.getOrderDetailId());
                    ReceiptDetail receiptDetail = receiptDetailService.getById(ctm.getOrderDetailId());

                    Integer result = receiptDetail.getQty().compareTo(BigDecimal.valueOf(sd.getQty()));//总数量比对完成数量
                    //判断到货数量是否小于总数量,小于则做加法,因为此次是首次加入,库存数量为0
                    if (result==1||result==0){
                        receiptDetail.setTaskQty(receiptDetail.getTaskQty().add(BigDecimal.valueOf(sd.getQty())));
                        Integer rs = receiptDetail.getTaskQty().compareTo(receiptDetail.getQty());//到货数量加原库存比对总数量
                        if (rs==0){//等于
                            receiptDetail.setStatus(lastStatus);
                            receiptDetailService.updateById(receiptDetail);
                            StockTask(sd,chm,type);
                        }
                        if (rs==-1){//小于
                            receiptDetail.setStatus(firstStatus);
                            receiptDetailService.updateById(receiptDetail);
                            StockTask(sd,chm,type);
                        }
                        if (rs==1){//大于
                            return AjaxResult.error("ID为: "+receiptDetail.getId().toString()+"  的入库子单收货数量溢出,请填写正确的收货数量");
                        }
                    }else {
                        return AjaxResult.error("ID为: "+receiptDetail.getId().toString()+"  的入库子单收货数量大于了系统数量,请填写正确的收货数量");
                    }

                }else {
                    //ReceiptHeader rh = new ReceiptHeader();
                    //rh.setId(sh.getOrderHeaderId());
                    //判断主单是否已经完成
                    if (receiptHeaderService.getById(sh.getOrderHeaderId()).getLastStatus() == lastStatus){
                        return AjaxResult.setResultCS(0,"该入库主单已经完成,无需再次回传");
                    }


                    SSPdetail sd1 = new SSPdetail();
                    sd1.setOrderDetailId(ctm.getOrderDetailId());
                    sd1.setOrderHeaderId(chm.getOrderHeaderId());
                    //判断系统中是否已有该子单
                    if (ssPdetailMapperAuto.selectListEntityByEqual(sd1).size() < 1) {
                        ssPdetailMapperAuto.insert(sd);

                        ReceiptDetail receiptDetail = receiptDetailService.getById(sd.getOrderDetailId());
                        if(receiptDetail==null){
                            throw new ServiceException("单据已删除");
                        }
                        Integer result = receiptDetail.getQty().compareTo(BigDecimal.valueOf(sd.getQty()));//总数量比对完成数量
                        //判断到货数量是否小于总数量,小于则做加法,因为此次是首次加入,库存数量为0
                        if (result==1||result==0){
                            receiptDetail.setTaskQty(receiptDetail.getTaskQty().add(BigDecimal.valueOf(sd.getQty())));
                            Integer rs = receiptDetail.getTaskQty().compareTo(receiptDetail.getQty());//到货数量加原库存比对总数量
                            if (rs==0){//等于
                                receiptDetail.setStatus(lastStatus);
                                receiptDetailService.updateById(receiptDetail);
                                StockTask(sd,chm,type);
                            }
                            if (rs==-1){//小于
                                receiptDetail.setStatus(firstStatus);
                                receiptDetailService.updateById(receiptDetail);
                                StockTask(sd,chm,type);
                            }
                            if (rs==1){//大于
                                return AjaxResult.error("ID为: "+receiptDetail.getId().toString()+"  的入库子单收货数量溢出,请填写正确的收货数量");
                            }
                        }else {
                            return AjaxResult.error("ID为: "+receiptDetail.getId().toString()+"  的入库子单收货数量大于了系统数量,请填写正确的收货数量");
                        }


                    } else {
                        sd1.setItemId(ctm.getItemId());
                        sd1.setOrderType("receipt");
                        //如果有,再判断该子单是否是多次回传,以及是否是入库子单
                        if (ssPdetailMapperAuto.selectListEntityByEqual(sd1).size() < 1) {
                            ssPdetailMapperAuto.insert(sd);
                        }

                        ReceiptDetail receiptDetail = receiptDetailService.getById(sd.getOrderDetailId());
                        if(receiptDetail==null){
                            throw new ServiceException("单据已删除");
                        }
                        //判断该子单是否已经完成
                        if (receiptDetail.getQty()==receiptDetail.getTaskQty()){
                            continue;
                        }
                        Integer result = receiptDetail.getQty().compareTo(BigDecimal.valueOf(sd.getQty()));//总数量比对完成数量
                        //判断到货数量是否小于总数量,小于则做加法,因为此次是非首次加入
                        if (result==1||result==0){
                            receiptDetail.setTaskQty(receiptDetail.getTaskQty().add(BigDecimal.valueOf(sd.getQty())));
                            Integer rs = receiptDetail.getTaskQty().compareTo(receiptDetail.getQty());//到货数量加原库存比对总数量
                            if (rs==0){//等于
                                receiptDetail.setStatus(lastStatus);
                                receiptDetailService.updateById(receiptDetail);
                                StockTask(sd,chm,type);
                            }
                            if (rs==-1){//小于
                                receiptDetail.setStatus(firstStatus);
                                receiptDetailService.updateById(receiptDetail);
                                StockTask(sd,chm,type);
                            }
                            if (rs==1){//大于
                                return AjaxResult.error("ID为: "+receiptDetail.getId().toString()+"  的入库子单收货数量溢出,请填写正确的收货数量");
                            }
                        }else {
                            return AjaxResult.error("ID为: "+receiptDetail.getId().toString()+"  的入库子单收货数量大于了系统数量,请填写正确的收货数量");
                        }
                    }
                }
//            }catch (Exception e){
//                throw new ServiceException("入库主单或子单新增失败!");
//            }
        }
        //ReceiptDetail detail = new ReceiptDetail();
        //detail.setReceiptId(chm.getOrderHeaderId());
        List<ReceiptDetail> receiptDetailList = receiptDetailService.list(new LambdaQueryWrapper<ReceiptDetail>().eq(ReceiptDetail::getReceiptId,chm.getOrderHeaderId()));
        int i = 0;
        for (ReceiptDetail rs:receiptDetailList){
            if (rs.getStatus()<=0){
                i++;
            }
            if (rs.getStatus()!=lastStatus){
                i++;
            }
        }
        if (i==0){
            ReceiptHeader receiptHeader = new ReceiptHeader();
            receiptHeader.setId(chm.getOrderHeaderId());
            receiptHeader.setFirstStatus(lastStatus);
            receiptHeader.setLastStatus(lastStatus);
            if (receiptHeaderService.updateById(receiptHeader)){
                throw new ServiceException("修改状态失败!");
            }
        }

        return AjaxResult.setResultCS(0,"入库单回传成功");
    }

    @Transactional
    public AjaxResult shipment(SSPheader chm,List<ConfirmTypeModel> ctmlist){
        int firstStatus = 200;
        int lastStatus = 800;
        for (ConfirmTypeModel ctm : ctmlist){
            if (ctm.getItemId()==null||ctm.getItemId()==""){
                return AjaxResult.error("钱柜系统明细标识不能为空!");
            }if (ctm.getOrderDetailId()<1){
                return AjaxResult.error("订单明细表标识不能为空!");
            }if (ctm.getCompanyCode()==null||ctm.getCompanyCode()==""){
                return AjaxResult.error("货主编码不能为空!");
            }if (ctm.getContainerCode()==null||ctm.getContainerCode()==""){
                return AjaxResult.error("容器编码不能为空!");
            }if (ctm.getItemCode()==null||ctm.getItemCode()==""){
                return AjaxResult.error("商品编码不能为空!");
            }if (ctm.getItemBarcode()==null||ctm.getItemBarcode()=="") {
                return AjaxResult.error("商品条码不能为空!");
            }
            SSPheader sh = new SSPheader();
            sh.sethID(chm.gethID());
            sh.setOrderHeaderId(chm.getOrderHeaderId());
            sh.setOrderType(chm.getOrderType());
            //组合入库子单
            SSPdetail sd = new SSPdetail();
            sd.setItemId(ctm.getItemId());
            sd.setOrderDetailId(ctm.getOrderDetailId());
            sd.setOrderHeaderId(chm.getOrderHeaderId());
            sd.setCompanyCode(ctm.getCompanyCode());
            sd.setContainerCode(ctm.getContainerCode());
            sd.setItemCode(ctm.getItemCode());
            sd.setItemName(ctm.getItemName());
            sd.setItemBarcode(ctm.getItemBarcode());
            sd.setItemState("good");
            sd.setQty(ctm.getQty());
            sd.setItemUnit(ctm.getItemUnit());
            sd.setOrderType("shipment");
            String type="shipment";
            //判断系统中是否已有该主单
//            try {
                if (ssPheaderMapperAuto.selectListEntityByEqual(sh).size()<1){
                    ssPheaderMapperAuto.insert(chm);
                    ssPdetailMapperAuto.insert(sd);

                    ShipmentDetail shipmentDetail = shipmentDetailService.getById(ctm.getOrderDetailId());
                    if(shipmentDetail==null){
                        throw new ServiceException("单据已删除");
                    }
                    Integer result = shipmentDetail.getQty().compareTo(BigDecimal.valueOf(sd.getQty()));//总数量比对完成数量
                    //判断到货数量是否小于总数量,小于则做加法,因为此次是首次加入,库存数量为0
                    if (result==1||result==0){
                        shipmentDetail.setTaskQty(shipmentDetail.getTaskQty().add(BigDecimal.valueOf(sd.getQty())));
                        Integer rs = shipmentDetail.getTaskQty().compareTo(shipmentDetail.getQty());//到货数量加原库存比对总数量
                        if (rs==0){//等于
                            shipmentDetail.setStatus(lastStatus);
                            shipmentDetailService.updateById(shipmentDetail);
                            Boolean resu = StockTask(sd,chm,type);
                            if (resu == false){
                                throw new ServiceException("库存中没有该容器!");
                            }
                        }
                        if (rs==-1){//小于
                            shipmentDetail.setStatus(firstStatus);
                            shipmentDetailService.updateById(shipmentDetail);
                            Boolean resu = StockTask(sd,chm,type);
                            if (resu == false){
                                throw new ServiceException("库存中没有该容器!");
                            }
                        }
                        if (rs==1){//大于
                            return AjaxResult.error("ID为: "+shipmentDetail.getId().toString()+"  的出库子单收货数量溢出,请填写正确的出货数量");
                        }
                    }else {
                        return AjaxResult.error("ID为: "+shipmentDetail.getId().toString()+"  的出库子单收货数量大于了系统数量,请填写正确的出货数量");
                    }

                }else {
                    //ShipmentHeader rh = new ShipmentHeader();
                    //rh.setId(sh.getOrderHeaderId());
                    //判断主单是否已经完成
                    if (shipmentHeaderService.getById(sh.getOrderHeaderId()).getLastStatus() == 800){
                        return AjaxResult.setResultCS(0,"该出库主单已经完成,无需再次回传");
                    }

                    SSPdetail sd1 = new SSPdetail();
                    sd1.setOrderDetailId(ctm.getOrderDetailId());
                    sd1.setOrderHeaderId(chm.getOrderHeaderId());
                    //判断系统中是否已有该子单
                    if (ssPdetailMapperAuto.selectListEntityByEqual(sd1).size()<1){
                        ssPdetailMapperAuto.insert(sd);

                        ShipmentDetail shipmentDetail = shipmentDetailService.getById(sd.getOrderDetailId());
                        if(shipmentDetail==null){
                            throw new ServiceException("单据已删除");
                        }
                        Integer result = shipmentDetail.getQty().compareTo(BigDecimal.valueOf(sd.getQty()));//总数量比对完成数量
                        //判断到货数量是否小于总数量,小于则做加法,因为此次是首次加入,库存数量为0
                        if (result==1||result==0){
                            shipmentDetail.setTaskQty(shipmentDetail.getTaskQty().add(BigDecimal.valueOf(sd.getQty())));
                            Integer rs = shipmentDetail.getTaskQty().compareTo(shipmentDetail.getQty());//到货数量加原库存比对总数量
                            if (rs==0){//等于
                                shipmentDetail.setStatus(lastStatus);
                                shipmentDetailService.updateById(shipmentDetail);
                                Boolean resu = StockTask(sd,chm,type);
                                if (resu == false){
                                    throw new ServiceException("库存中没有该容器!");
                                }
                            }
                            if (rs==-1){//小于
                                shipmentDetail.setStatus(firstStatus);
                                shipmentDetailService.updateById(shipmentDetail);
                                Boolean resu = StockTask(sd,chm,type);
                                if (resu == false){
                                    throw new ServiceException("库存中没有该容器!");
                                }
                            }
                            if (rs==1){//大于
                                return AjaxResult.error("ID为: "+shipmentDetail.getId().toString()+"  的出库子单收货数量溢出,请填写正确的出货数量");
                            }
                        }else {
                            return AjaxResult.error("ID为: "+shipmentDetail.getId().toString()+"  的出库子单收货数量大于了系统数量,请填写正确的出货数量");
                        }

                    }else {
                        sd1.setItemId(ctm.getItemId());
                        sd1.setOrderType("shipment");
                        //如果有,再判断该子单是否是多次回传,以及是否是出库子单
                        if (ssPdetailMapperAuto.selectListEntityByEqual(sd1).size()<1) {
                            ssPdetailMapperAuto.insert(sd);

                            ShipmentDetail shipmentDetail = shipmentDetailService.getById(sd.getOrderDetailId());

                            //判断该子单是否已经完成
                            if (shipmentDetail.getQty()==shipmentDetail.getTaskQty()){
                                continue;
                            }
                            Integer result = shipmentDetail.getQty().compareTo(BigDecimal.valueOf(sd.getQty()));//总数量比对完成数量
                            //判断到货数量是否小于总数量,小于则做加法,因为此次是非首次加入
                            if (result==1||result==0){
                                shipmentDetail.setTaskQty(shipmentDetail.getTaskQty().add(BigDecimal.valueOf(sd.getQty())));
                                Integer rs = shipmentDetail.getTaskQty().compareTo(shipmentDetail.getQty());//到货数量加原库存比对总数量
                                if (rs==0){//等于
                                    shipmentDetail.setStatus(lastStatus);
                                    shipmentDetailService.updateById(shipmentDetail);
                                    Boolean resu = StockTask(sd,chm,type);
                                    if (resu == false){
                                        throw new ServiceException("库存中没有该容器!");
                                    }
                                }
                                if (rs==-1){//小于
                                    shipmentDetail.setStatus(firstStatus);
                                    shipmentDetailService.updateById(shipmentDetail);
                                    Boolean resu = StockTask(sd,chm,type);
                                    if (resu == false){
                                        throw new ServiceException("库存中没有该容器!");
                                    }
                                }
                                if (rs==1){//大于
                                    return AjaxResult.error("ID为: "+shipmentDetail.getId().toString()+"  的出库子单收货数量溢出,请填写正确的出货数量");
                                }
                            }else {
                                return AjaxResult.error("ID为: "+shipmentDetail.getId().toString()+"  的出库子单收货数量大于了系统数量,请填写正确的出货数量");
                            }
                        }
                    }
                }
//            }catch (Exception e){
//                throw new ServiceException("出库主单或出库子单新增失败!");
//            }
        }

        //ShipmentDetail detail = new ShipmentDetail();
        //detail.setShipmentId(chm.getOrderHeaderId());
        List<ShipmentDetail> shipmentDetailList = shipmentDetailService.list(new LambdaQueryWrapper<ShipmentDetail>().eq(ShipmentDetail::getShipmentId,chm.getOrderHeaderId()));
        int i = 0;
        for (ShipmentDetail rs:shipmentDetailList){
            if (rs.getStatus()==null){
                i++;
            }
            if (rs.getStatus()!=lastStatus){
                i++;
            }
        }
        if (i==0){
            ShipmentHeader shipmentHeader = new ShipmentHeader();
            shipmentHeader.setId(chm.getOrderHeaderId());
            shipmentHeader.setFirstStatus(800);
            shipmentHeader.setLastStatus(800);
            if (shipmentHeaderService.updateById(shipmentHeader)){
                throw new ServiceException("修改状态失败!");
            }
        }
        return AjaxResult.setResultCS(0,"出库单回传成功");
    }


    /**
     * 钱柜生成任务
     */
    @Transactional
    public boolean StockTask(SSPdetail ssPdetail,SSPheader ssPheader,String type){
        Boolean result=true;
        //这里根据传过来的仓库code查到仓库ID
        WarehouseCompany warehouseCompany = new WarehouseCompany();
        warehouseCompany.setCompanyCode(ssPdetail.getCompanyCode());
        warehouseCompany.setWarehouseCode(ssPheader.getWarehouseCode());
        //warehouseCompany=companyService.selcetIWCBycode(warehouseCompany);
        warehouseCompany= warehouseCompanyService.list(new LambdaQueryWrapper<WarehouseCompany>()
                .eq(WarehouseCompany::getCompanyCode,ssPdetail.getCompanyCode())
                .eq(WarehouseCompany::getWarehouseCode,ssPdetail.getCompanyCode())).get(0);


        //获取库位
        String containerCode=ssPdetail.getContainerCode();
        Location location=new Location();
        location.setWarehouseCode(warehouseCompany.getWarehouseCode());
        location.setContainerCode(containerCode);
        location=locationService.selectFirstEntity(location);

        //创建任务
        TaskHeader task=new TaskHeader();
        task.setWarehouseId(warehouseCompany.getWarehouseId());
        task.setWarehouseCode(warehouseCompany.getWarehouseCode());
        task.setCompanyId(warehouseCompany.getCompanyId());
        task.setCompanyCode(warehouseCompany.getCompanyCode());
        if(type.equals("receipt")) {
            task.setTaskType(200);
        }else {
            task.setTaskType(400);
        }
        task.setContainerCode(containerCode);
        task.setRoadway(location.getRoadway());
        task.setFromLocation(location.getCode());
        task.setToLocation(location.getCode());
        task.setStatus(1);
        task.setZoneCode("QG");
        task.setCreatedBy(ShiroUtils.getLoginName());
//        task.setBeginTime(new Date());
//        task.setEndTime(new Date());
        task.setCreatedBy(ShiroUtils.getLoginName());
        try {
            taskHeaderService.save(task);
        }catch (Exception e){
            throw new ServiceException("任务创建失败");
        }

        //获得库存
        //Inventory inventory=new Inventory();
        //inventory.setMaterialCode(ssPdetail.getItemCode());
        //inventory.setWarehouseCode(warehouseCompany.getWarehouseCode());
        //inventory.setContainerCode(containerCode);
        //inventory=iInventoryService.selectFirstEntity(inventory);
        InventoryDetail inventoryDetail = inventoryDetailService.list(new LambdaQueryWrapper<InventoryDetail>()
                .eq(InventoryDetail::getMaterialCode, ssPdetail.getCompanyCode())
                .eq(InventoryDetail::getWarehouseCode, warehouseCompany.getWarehouseCode())
                .eq(InventoryDetail::getContainerCode, containerCode)).get(0);

        //创建子任务
        TaskDetail taskDetail=new TaskDetail();
        taskDetail.setTaskId(task.getId());
        taskDetail.setWarehouseId(warehouseCompany.getWarehouseId());
        taskDetail.setWarehouseCode(warehouseCompany.getWarehouseCode());
        taskDetail.setCompanyId(warehouseCompany.getCompanyId());
        taskDetail.setCompanyCode(warehouseCompany.getCompanyCode());
        taskDetail.setBillCode(ssPheader.getOrderCode());
        taskDetail.setBillId(ssPheader.getOrderHeaderId());
        taskDetail.setBillDetailId(ssPdetail.getOrderDetailId());
        taskDetail.setMaterialCode(ssPdetail.getItemCode());
        taskDetail.setMaterialName(ssPdetail.getItemName());
        taskDetail.setContainerCode(containerCode);
        if(inventoryDetail!=null){
            if(type.equals("receipt")) {
                taskDetail.setToInventoryId(inventoryDetail.getId());
            }else {
                taskDetail.setFromInventoryId(inventoryDetail.getId());
            }

        }
        taskDetail.setFromLocation(location.getCode());
        taskDetail.setToLocation(location.getCode());
        taskDetail.setQty(new BigDecimal(ssPdetail.getQty()));
        taskDetail.setStatus(1);
        //if(type.equals("receipt")) {
        //    taskDetail.setType("r");
        //}else {
        //    taskDetail.setType("s");
        //}
        if(type.equals("receipt")) {
            taskDetail.setTaskType(100);
        }else {
            taskDetail.setTaskType(300);
        }
        taskDetail.setLastUpdatedBy(ShiroUtils.getLoginName());
        try {
            taskDetailService.save(taskDetail);
        }catch (Exception e){
            throw new ServiceException("子任务创建失败");
        }
        Integer[] ids=new Integer[1];
        ids[0]=task.getId();
        String[] strings=new String[1];
        try {
            taskHeaderService.completeTaskByWMS(ids,strings);
        } catch (Exception e) {
            throw new ServiceException("完成任务失败");
        }
        return result;
    }
//    /**
//     * 钱柜入库库存修改类
//     * @param
//     * @return
//     */
//    public boolean StockReceipt(SSPdetail ssPdetail,SSPheader ssPheader){
//        //这里根据传过来的仓库code查到仓库ID
//        WarehouseCompany warehouseCompany = new WarehouseCompany();
//        warehouseCompany.setCompanyCode(ssPdetail.getCompanyCode());
//        warehouseCompany.setWarehouseCode(ssPheader.getWarehouseCode());
//        warehouseCompany=iCompanyService.selcetIWCBycode(warehouseCompany);
//
//        Inventory it = new Inventory();
//        it.setContainerCode(ssPdetail.getContainerCode());
//        it.setReceiptDetailId(ssPdetail.getOrderDetailId());
//        //根据传过来的容器编码和子单ID查询库存中是否已给该子单分配库位和库存
//        Inventory inventory = iInventoryService.selectFirstEntity(it);
//        //组合库存记录实体
//        InventoryTransaction inventoryTransaction = new InventoryTransaction();
//        inventoryTransaction.setWarehouseId(warehouseCompany.getWarehouseId());
//        inventoryTransaction.setWarehouseCode(warehouseCompany.getWarehouseCode());
//        inventoryTransaction.setType("receipt");
//        inventoryTransaction.setMaterialName(ssPdetail.getItemName());
//        inventoryTransaction.setMaterialCode(ssPdetail.getItemCode());
//        inventoryTransaction.setBillId(ssPheader.getOrderHeaderId());
//        inventoryTransaction.setBillCode(ssPheader.getOrderCode());
//        inventoryTransaction.setBillDetailId(ssPdetail.getOrderDetailId());
//        inventoryTransaction.setStatus("good");
//        inventoryTransaction.setCreatedBy(ShiroUtils.getLoginName());
//        inventoryTransaction.setLastUpdatedBy(ShiroUtils.getLoginName());
//        inventoryTransaction.setZoneCode(ssPheader.getCubeCode());
//        if (inventory != null){//已给该子单分配库位,由于没有任务锁定,则增加数量即可
//            BigDecimal qty = inventory.getQty();
//            BigDecimal qty1 = inventory.getQty().add(BigDecimal.valueOf(ssPdetail.getQty()));
//            inventory.setQty(qty1);
//            inventory.setLastUpdatedBy(ShiroUtils.getLoginName());
//            if (iInventoryService.updateById(inventory) > 0){
//                inventoryTransaction.setLocationCode(inventory.getLocationCode());
//                inventoryTransaction.setContainerCode(inventory.getContainerCode());
//                inventoryTransaction.setCompanyId(inventory.getCompanyId());
//                inventoryTransaction.setCompanyCode(inventory.getCompanyCode());
//                inventoryTransaction.setQty(qty);
//                inventoryTransaction.setTaskQty(BigDecimal.valueOf(ssPdetail.getQty()));
//                try{
//                    iInventoryTransactionService.insert(inventoryTransaction);
//                }catch (Exception e){
//                    throw new ServiceException("入库库存记录新增失败!");
//                }
//                return true;
//            }
//        }else {//未给该子单分配库位,需在库位里找一个库位分配容器和子单
//            Location location = new Location();
//            location.setContainerCode(ssPdetail.getContainerCode());
//            Location location1 = iLocationService.selectFirstEntity(location);
//            if (location1 != null){//库位里有该容器
//                it.setWarehouseId(warehouseCompany.getWarehouseId());
//                it.setWarehouseCode(ssPheader.getWarehouseCode());
//                it.setLocationId(location1.getId());
//                it.setLocationCode(location1.getCode());
//                it.setCompanyId(warehouseCompany.getCompanyId());
//                it.setCompanyCode(warehouseCompany.getCompanyCode());
//                it.setMaterialCode(ssPdetail.getItemCode());
//                it.setReceiptId(ssPheader.getOrderHeaderId());
//                it.setReceiptCode(ssPheader.getOrderCode());
//                it.setReceiptDetailId(ssPdetail.getOrderDetailId());
//                it.setStatus(ssPdetail.getItemState());
//                it.setQty(BigDecimal.valueOf(ssPdetail.getQty()));
//                it.setCreatedBy(ShiroUtils.getLoginName());
//                if (iInventoryService.insert(it)>0){
//                    inventoryTransaction.setLocationCode(location1.getCode());
//                    inventoryTransaction.setContainerCode(location1.getContainerCode());
//                    inventoryTransaction.setCompanyId(warehouseCompany.getCompanyId());
//                    inventoryTransaction.setCompanyCode(warehouseCompany.getCompanyCode());
//                    inventoryTransaction.setTaskQty(BigDecimal.valueOf(ssPdetail.getQty()));
//                    try{
//                        iInventoryTransactionService.insert(inventoryTransaction);
//                    }catch (Exception e){
//                        throw new ServiceException("入库库存记录新增失败!");
//                    }
//                    return true;
//                }
//            }else {//库位里没有该容器,将在库位中找一个最底层没有放货的容器
//                Location location0 = iLocationService.selectSSPLocation();
//
//                it.setWarehouseId(warehouseCompany.getWarehouseId());
//                it.setWarehouseCode(ssPheader.getWarehouseCode());
//                it.setLocationId(location0.getId());
//                it.setLocationCode(location0.getCode());
//                it.setCompanyId(warehouseCompany.getCompanyId());
//                it.setCompanyCode(warehouseCompany.getCompanyCode());
//                it.setMaterialCode(ssPdetail.getItemCode());
//                it.setReceiptId(ssPheader.getOrderHeaderId());
//                it.setReceiptCode(ssPheader.getOrderCode());
//                it.setReceiptDetailId(ssPdetail.getOrderDetailId());
//                it.setStatus(ssPdetail.getItemState());
//                it.setQty(BigDecimal.valueOf(ssPdetail.getQty()));
//                it.setCreatedBy(ShiroUtils.getLoginName());
//                if (iInventoryService.insert(it)>0){
//                    iLocationService.updateContainerCode(location0.getCode(),ssPdetail.getContainerCode());
//                    inventoryTransaction.setTaskQty(BigDecimal.valueOf(ssPdetail.getQty()));
//                    inventoryTransaction.setLocationCode(location0.getCode());
//                    inventoryTransaction.setContainerCode(location0.getContainerCode());
//                    inventoryTransaction.setCompanyId(warehouseCompany.getCompanyId());
//                    inventoryTransaction.setCompanyCode(warehouseCompany.getCompanyCode());
//                    try{
//                        iInventoryTransactionService.insert(inventoryTransaction);
//                    }catch (Exception e){
//                        throw new ServiceException("入库库存记录新增失败!");
//                    }
//                    return true;
//                }
//            }
//        }
//         throw new ServiceException("入库库存修改失败!");
//    }
//
//    /**
//     * 钱柜出库库存修改类
//     * @param
//     * @return
//     */
//    public boolean StockShipment(SSPdetail ssPdetail,SSPheader ssPheader) {
//        Inventory it = new Inventory();
//        it.setContainerCode(ssPdetail.getContainerCode());
//        it.setMaterialCode(ssPdetail.getItemCode());
//        //根据传过来的容器编码和子单ID查询库存中是否已给该子单分配库位和库存
//        Inventory inventory = iInventoryService.selectFirstEntity(it);
//        if (inventory != null) {//已给该子单分配库位,由于没有任务锁定,则减少数量即可
//            BigDecimal qty = inventory.getQty();
//            BigDecimal qty1 = inventory.getQty().subtract(BigDecimal.valueOf(ssPdetail.getQty()));
//            inventory.setQty(qty1);
//            inventory.setLastUpdatedBy(ShiroUtils.getLoginName());
//            if (iInventoryService.updateById(inventory) > 0) {
//                //组合库存记录实体
//                InventoryTransaction inventoryTransaction = new InventoryTransaction();
//                inventoryTransaction.setWarehouseId(inventory.getWarehouseId());
//                inventoryTransaction.setWarehouseCode(inventory.getWarehouseCode());
//                inventoryTransaction.setLocationId(inventory.getLocationId());
//                inventoryTransaction.setLocationCode(inventory.getLocationCode());
//                inventoryTransaction.setContainerCode(inventory.getContainerCode());
//                inventoryTransaction.setType("shipment");
//                inventoryTransaction.setCompanyId(inventory.getCompanyId());
//                inventoryTransaction.setCompanyCode(inventory.getCompanyCode());
//                inventoryTransaction.setMaterialName(ssPdetail.getItemName());
//                inventoryTransaction.setMaterialCode(ssPdetail.getItemCode());
//                inventoryTransaction.setBillId(ssPheader.getOrderHeaderId());
//                inventoryTransaction.setBillCode(ssPheader.getOrderCode());
//                inventoryTransaction.setBillDetailId(ssPdetail.getOrderDetailId());
//                inventoryTransaction.setStatus("good");
//                inventoryTransaction.setLastUpdatedBy(ShiroUtils.getLoginName());
//                inventoryTransaction.setCreatedBy(ShiroUtils.getLoginName());
//                inventoryTransaction.setQty(qty);
//                inventoryTransaction.setTaskQty(BigDecimal.valueOf(ssPdetail.getQty()).multiply(new BigDecimal(-1)));
//                try{
//                    iInventoryTransactionService.insert(inventoryTransaction);
//                }catch (Exception e){
//                    throw new ServiceException("入库库存记录新增失败!");
//                }
//                return true;
//            }
//        } else {
//            return false;
//        }
//        return false;
//    }
}