package com.zbf.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zbf.common.annotation.DataScope;
import com.zbf.common.annotation.Log;
import com.zbf.common.core.domain.entity.SysUser;
import com.zbf.common.exception.ServiceException;
import com.zbf.common.utils.DateUtils;
import com.zbf.common.utils.OrderCodeFactory;
import com.zbf.common.utils.SecurityUtils;
import com.zbf.common.utils.StringUtils;
import com.zbf.common.utils.bean.BeanUtils;
import com.zbf.common.utils.uuid.IdUtils;
import com.zbf.system.domain.*;
import com.zbf.system.mapper.*;
import com.zbf.system.service.*;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
//import sun.security.util.AuthResources_it;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.validation.Validator;
import java.math.BigDecimal;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 入库通知单Service业务层处理
 *
 * @author tony
 * @date 2024-06-18
 */
@Service
public class TRkWareNoticeServiceImpl extends ServiceImpl<TRkWareNoticeMapper, TRkWareNotice>
        implements ITRkWareNoticeService // 修改
{
    private final Logger logger = LoggerFactory.getLogger(TRkWareNoticeServiceImpl.class);
    @Autowired
    private TRkWareNoticeMapper tRkWareNoticeMapper;

    @Autowired
    private TRkWareNoticeBakMapper tRkWareNoticeBakMapper;

    @Autowired
    private TOngoodsshelfMapper tOngoodsshelfMapper;

    @Autowired
    private TOngoodsshelfBakMapper tOngoodsshelfBakMapper;

    @Autowired
    private TRkReceivingGoodsMapper tRkReceivingGoodsMapper;

    @Autowired
    private TBaseStorageMapper tBaseStorageMapper;

    @Autowired
    private TMiStockMapper tMiStockMapper;

    @Autowired
    private TMiStockFMapper tMiStockFMapper;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private IPlcService plcService;

    @Autowired
    private ITCallNoticeService tNoticeService;

    @Autowired
    private TBaseStorageAreaLocationMapper tBaseStorageAreaLocationMapper;

    @Autowired
    private ISysConfigService configService;
    @Autowired
    protected Validator validator;
    @Autowired
    private TRkWareNoticeTabMapper tRkWareNoticeTabMapper;

    @Autowired
    private PlcMapper plcMapper;

    @Autowired
    private TBasePalletMapper palletMapper;

    @Autowired
    private TBaseStorageAreaLocationMapper service;

    @Autowired
    private TRkWareNoticeTabMapper mapper;

    @Autowired
    private ITCallNoticeOrderService tNoticeOrderService;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;


    @Autowired
    private TCallNoticeOrderMapper callNoticeOrderMapper;

    @Autowired
    private TBaseGoodsMapper tBaseGoodsMapper;

    @Autowired
    private TCallNoticeOrderMapper mappers;

    @Autowired
    private TOngoodsshelfMapper tOgoodsshelfMapper;

    @Autowired
    private SysUserMapper sysUserMapper;


    /**
     * 查询入库通知单
     *
     * @param id 入库通知单主键
     * @return 入库通知单
     */
    @Override
    public TRkWareNotice selectTRkWareNoticeById(String id) {
        return tRkWareNoticeMapper.selectTRkWareNoticeById(id);
    }

    /**
     * 查询入库通知单
     *
     * @param id 入库通知单主键
     * @return 入库通知单
     */
    @Override
    public TRkWareNotice selectTRkWareNoticeByNoticeId(String id) {
        return tRkWareNoticeMapper.selectTRkWareNoticeByNoticeId(id);
    }

    /**
     * 查询入库通知单
     *
     * @param id 入库通知单主键
     * @return 入库通知单
     */
    @Override
    public TRkWareNotice selectTRkWareNoticeByDeliveryId(String id) {
        return tRkWareNoticeMapper.selectTRkWareNoticeByDeliveryId(id);
    }

    /**
     * 查询入库通知单列表
     *
     * @param tRkWareNotice 入库通知单
     * @return 入库通知单
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<TRkWareNotice> selectTRkWareNoticeList(TRkWareNotice tRkWareNotice) {
        return tRkWareNoticeMapper.selectTRkWareNoticeList(tRkWareNotice);
    }

    /**
     * 导出入库通知单列表
     *
     * @param tRkWareNotice 入库通知单
     * @return 入库通知单
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<TRkWareNotice> exportTRkWareNoticeList(TRkWareNotice tRkWareNotice) {
        return tRkWareNoticeMapper.exportTRkWareNoticeList(tRkWareNotice);
    }

    /**
     * 新增入库通知单
     *
     * @param tRkWareNotice 入库通知单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertTRkWareNotice(TRkWareNotice tRkWareNotice) {

        // 来源单号
        int cnt = tRkWareNoticeMapper.selectTRkWareNoticeByOrginalId(tRkWareNotice.getDeliveryId());

        if (cnt > 0) {
            throw new RuntimeException("来源单号重复");
        }

        tRkWareNotice.setCreateTime(DateUtils.getNowDate());
        int rows = tRkWareNoticeMapper.insertTRkWareNotice(tRkWareNotice);
        // insertTRkWareNoticeTab(tRkWareNotice);
        return rows;
    }

    /**
     * 修改入库通知单
     *
     * @param tRkWareNotice 入库通知单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateTRkWareNotice(TRkWareNotice tRkWareNotice) {

        // 来源单号
        int cnt = tRkWareNoticeMapper.selectTRkWareNoticeByOrginalId(tRkWareNotice.getDeliveryId());

        if (cnt > 0) {
            throw new RuntimeException("来源单号重复");
        }

        tRkWareNotice.setUpdateTime(DateUtils.getNowDate());
        tRkWareNoticeMapper.deleteTRkWareNoticeTabByNoticeId(tRkWareNotice.getId());
        // insertTRkWareNoticeTab(tRkWareNotice);
        return tRkWareNoticeMapper.updateTRkWareNotice(tRkWareNotice);
    }

    /**
     * 批量删除入库通知单
     *
     * @param ids 需要删除的入库通知单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTRkWareNoticeByIds(String[] ids) {
        tRkWareNoticeMapper.deleteTRkWareNoticeTabByNoticeIds(ids);
        LambdaQueryWrapper<TCallNoticeOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(TCallNoticeOrder::getTaskId, ids);

        List<TCallNoticeOrder> orders = mappers.selectList(wrapper);
        if (orders.size() > 0) {
            List<String> collect = orders.stream().map(TCallNoticeOrder::getId).collect(Collectors.toList());
            mappers.deleteTCallNoticeOrderByIds(collect.toArray(new String[0]));
        }


        return tRkWareNoticeMapper.deleteTRkWareNoticeByIds(ids);
    }

    /**
     * 删除入库通知单信息
     *
     * @param id 入库通知单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTRkWareNoticeById(String id) {
        tRkWareNoticeMapper.deleteTRkWareNoticeTabByNoticeId(id);
        return tRkWareNoticeMapper.deleteTRkWareNoticeById(id);
    }

    /**
     * 批量禁用
     *
     * @param id 入库通知单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int disabledTRkWareNoticeByIds(String[] ids) {
        return tRkWareNoticeMapper.disabledTRkWareNoticeByIds(ids);
    }

    /**
     * 批量启用
     *
     * @param id 入库通知单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int enableTRkWareNoticeByIds(String[] ids) {
        return tRkWareNoticeMapper.enableTRkWareNoticeByIds(ids);
    }

    /**
     * 修改状态
     *
     * @param tRkWareNotice 工序管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int updateStatus(TRkWareNotice tRkWareNotice) {
        return tRkWareNoticeMapper.updateTRkWareNotice(tRkWareNotice);
    }

    /**
     * 新增入库通知单明细信息
     *
     * @param tRkWareNotice 入库通知单对象
     */
    public void insertTRkWareNoticeTab(TRkWareNotice tRkWareNotice) {
        List<TRkWareNoticeTab> tRkWareNoticeTabList = tRkWareNotice.getTRkWareNoticeTabList();
        String id = tRkWareNotice.getId();
        if (StringUtils.isNotNull(tRkWareNoticeTabList)) {
            List<TRkWareNoticeTab> list = new ArrayList<TRkWareNoticeTab>();
            for (TRkWareNoticeTab tRkWareNoticeTab : tRkWareNoticeTabList) {
                tRkWareNoticeTab.setNoticeId(id);
                list.add(tRkWareNoticeTab);
            }
            if (list.size() > 0) {
                tRkWareNoticeMapper.batchTRkWareNoticeTab(list);
            }
        }
    }

    /**
     * 收货
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, String> confirmNoticeTab(TRkWareNoticeTabUpdate params) {

        // 返回结果
        Map<String, String> resultMap = new HashMap<>();

        // 查询入库通知单明细
        TRkWareNotice tRkWareNotice = tRkWareNoticeMapper.selectTRkWareNoticeById(params.getId());

        // 手持通知信息
        TCallNotice tCallNotice = new TCallNotice();
        tCallNotice.setId(IdUtils.randomUUID());
        params.getParams().put("callNoticeId", tCallNotice.getId());

        if (tRkWareNotice == null) {
            resultMap.put("error", "入库通知单不存在");
            throw new RuntimeException("入库通知单不存在");

        }

        // 托盘号为空
        if (ObjectUtils.isEmpty(params.getCtlNo())) {
            // 查询PLC表
            List<Plc> plcSList = plcService.selectPlcList();
            Plc plc = plcSList.get(0);

            // 到达9999999 则自动从0开始
            if (plc.getPlcid() == 9999999) {
                plc.setPlcid(0L);
            } else {
                plc.setPlcid(plc.getPlcid() + 1);
            }

            plc.setId(1);
            plcService.updatePlc(plc);

            params.getParams().put("plcId", plc.getPlcid());

        } else {

            // 校验同一托盘号在库存中是否存在
            /*TMiStock tMiStock = new TMiStock();
            tMiStock.setCtl(params.getCtlNo());
            List<TMiStock> tMiStocks = tMiStockMapper.selectTMiStockList(tMiStock);

            if (tMiStocks.size() > 0) {
                resultMap.put("error", "托盘【" + params.getCtlNo() + "】已占用，请更换");
                throw  new RuntimeException("托盘" + params.getCtlNo() + "已占用，请更换");
            }*/


            //校验托盘容器是否正确
            LambdaQueryWrapper<TBasePallet> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TBasePallet::getPalletId, params.getCtlNo());
            List<TBasePallet> plcs = palletMapper.selectList(wrapper);
            if (plcs.isEmpty()) {
                resultMap.put("error", "托盘不存在");
                throw new RuntimeException("托盘" + params.getCtlNo() + "不存在");
            }

            TBasePallet palletChk = plcs.get(0);
            if ("1".equals(palletChk.getIsLock())) {
                resultMap.put("error", "托盘号【" + params.getCtlNo() + "】已禁用");
                log.error("托盘号【" + params.getCtlNo() + "】已禁用");
                throw new RuntimeException("托盘号【" + params.getCtlNo() + "】已禁用");
            }
            if ("0".equals(palletChk.getStatus()) || StringUtils.isBlank(palletChk.getStatus())) {
                TBasePallet tBasePallet = new TBasePallet();
                tBasePallet.setStatus("1");
                tBasePallet.setId(palletChk.getId());
                tBasePallet.setUpdateBy(params.getUserName());
                tBasePallet.setUpdateTime(new Date());
                palletMapper.updateTBasePallet(tBasePallet);
            }
        }

        // 通知单明细map
        Map<String, TRkWareNoticeTab> trkWareNoticeTabMap = new HashMap<String, TRkWareNoticeTab>();
        for (int i = 0; i < tRkWareNotice.getTRkWareNoticeTabList().size(); i++) {
            TRkWareNoticeTab noticeTab = tRkWareNotice.getTRkWareNoticeTabList().get(i);
            trkWareNoticeTabMap.put(noticeTab.getSalesOrderNumber() + noticeTab.getGoodsId(), noticeTab);
        }

        if ("".equals(params.getUserName())) {
            params.setUserName(params.getRecordPerson());
        }

        List<TRkWareNoticeTab> updateNoticeTabs = new ArrayList<TRkWareNoticeTab>();
        List<TOngoodsshelf> insertTOngoodsshelfs = new ArrayList<TOngoodsshelf>();


        //冻结校验
        List<TRkWareNoticeTab> list1 = params.getTrkWareNoticeTabList();
        for (TRkWareNoticeTab tab : list1) {
            TRkWareNoticeTab tRkWareNoticeTab = mapper.selectTRkWareNoticeTabById(tab.getId());
            if ("1".equals(tRkWareNoticeTab.getInStatus())) {
                resultMap.put("error", "物料【" + tRkWareNoticeTab.getGoodsName() + "】已冻结，不可收货");
                log.error("物料【" + tRkWareNoticeTab.getInStatus() + "】已冻结，不可收货");
                throw new RuntimeException("物料【" + tRkWareNoticeTab.getInStatus() + tRkWareNoticeTab.getGoodsName() + " 】已冻结，不可收货");
            }
        }


        // 遍历提交的通知单明细数据
        for (TRkWareNoticeTab tabNew : params.getTrkWareNoticeTabList()) {
            TRkWareNoticeTab tabOld = trkWareNoticeTabMap.get(tabNew.getSalesOrderNumber() + tabNew.getGoodsId());

            if (tabOld == null) {
                resultMap.put("error", "物料【" + tabNew.getGoodsName() + "】的通知单明细不存在");
                throw new RuntimeException("物料【" + tabNew.getGoodsName() + "】的通知单明细不存在");
            }


            // 仓库ID
            String storageId = params.getStorageId();
            if (!ObjectUtils.isEmpty(tabNew.getStorageId())) {
                storageId = tabNew.getStorageId();
            }

            // 获取仓库信息
            TBaseStorage tBaseStorage = new TBaseStorage();
            tBaseStorage.setStorageId(null);
            List<TBaseStorage> sTBaseStorages = tBaseStorageMapper.selectTBaseStorageList(tBaseStorage);

            if (sTBaseStorages.size() > 0) {
                tBaseStorage = sTBaseStorages.get(0);

                // 判断是否为AGV库 TODO
                if ("1".equals(tBaseStorage.getIsAgv())) {

                    // 更新入库通知单明细状态

                    // 创建入库任务：待执行

                    // 调用AGV接口

                    continue;
                }
            } else {
                resultMap.put("error", "物料【" + tabNew.getGoodsName() + "】设置的仓库【" + storageId + "】不存在");
                throw new RuntimeException("物料【" + tabNew.getGoodsName() + "】设置的仓库【" + storageId + "】不存在");
            }


            BigDecimal recNumNowNew = tabNew.getRecNumNow() == null ? BigDecimal.ZERO : tabNew.getRecNumNow();
            if (recNumNowNew.compareTo(BigDecimal.ZERO) == 0) {
                throw new RuntimeException("物料【" + tabNew.getGoodsName() + "】的收货数量不能为0");
            }

            BigDecimal recNum = tabOld.getRecNum() == null ? BigDecimal.ZERO : tabOld.getRecNum();
            BigDecimal receivingNum = tabOld.getReceivingNum() == null ? BigDecimal.ZERO : tabOld.getReceivingNum();

            // if (recNumNowNew == BigDecimal.ZERO) {
            // resultMap.put("error", "物料【" + tabNew.getGoodsName() + "】的签收数量不能为0");
            // return resultMap;
            // }

            if (recNumNowNew.add(recNum).compareTo(receivingNum) > 0) {
                resultMap.put("error", "物料【" + tabNew.getGoodsName() + "】的收货数量不能大于签收数量");
                throw new RuntimeException("物料【" + tabNew.getGoodsName() + "】的收货数量不能大于签收数量");
            }

            // 设置更新信息
            tabOld.setRecNum(recNumNowNew.add(recNum));

            if (tabOld.getRecNum().compareTo(receivingNum) == 0) {
                // 物料明细冻结
                tabOld.setInStatus("1");
            }

            //
//            tabOld.setReceivingStatus("0");

            tabOld.setRecNumNow(recNumNowNew);
            tabOld.setStorageId(storageId);
            // 托盘
            tabOld.setCtl(params.getCtlNo());

            tabOld.setUpdateBy(params.getUserName());
            tabOld.setUpdateTime(new Date());

            // 仓库名称
            if (sTBaseStorages.size() > 0) {
                tBaseStorage = sTBaseStorages.get(0);
                tabOld.setStorageShortName(tBaseStorage.getStorageShortName());
            }

            updateNoticeTabs.add(tabOld);

            tRkWareNoticeTabMapper.updateTRkWareNoticeTab(tabOld);




            // 生成入库任务
            insertTOngoodsshelfs.add(makeTOngoodsshelf(tRkWareNotice, tabOld, params));
        }

        // 生成入库任务
        if (insertTOngoodsshelfs.size() > 0) {
            for (TOngoodsshelf tOngoodsshelf : insertTOngoodsshelfs) {
                tOngoodsshelfMapper.insertTOngoodsshelf(tOngoodsshelf);
            }

            // 仓库id
            tCallNotice.setStorageId(params.getStorageId());
            // 托盘号
            tCallNotice.setCtl(params.getCtlNo());
            // pLCID
            tCallNotice.setPlcid((Long) params.getParams().get("plcId"));
            // 任务类型 0:入库任务
            tCallNotice.setTaskType("0");
            // 物料编码
            // tCallNotice.setGoodsId(tOngoodsshelf.getGoodsId());
            // 物料名称
            // tCallNotice.setGoodsName(tOngoodsshelf.getGoodsName());
            // 入库任务ID
            // tCallNotice.setRukuId(tOngoodsshelf.getId());
            // 创建者
            tCallNotice.setCreateBy(params.getCreateBy());
            // 时间
            tCallNotice.setCreateTime(new Date());
            // 状态 0：未处理
            tCallNotice.setStatus("0");
            // 虚拟入库任务
            tCallNotice.setFictitious(params.getFictitious());
            // 通知单号
            tCallNotice.setTaskId(tRkWareNotice.getNoticeId());

            tNoticeService.sendNotice(tCallNotice);

        }


        resultMap.put("success", "收货成功");
        resultMap.put("error", "");
        return resultMap;
    }

    /**
     * 编辑入库任务
     *
     * @param notice
     * @param noticeTab
     * @return
     */
    private TOngoodsshelf makeTOngoodsshelf(TRkWareNotice notice, TRkWareNoticeTab noticeTab,
                                            TRkWareNoticeTabUpdate params) {
        TOngoodsshelf tOngoodsshelf = new TOngoodsshelf();
        // 入库数量 TODO
        tOngoodsshelf.setAccNum(noticeTab.getRecNumNow());
        // 需求数量 TODO
        // tOngoodsshelf.setStoNum();

        tOngoodsshelf.setId(OrderCodeFactory.getOrderCode("S", ""));

        // 中标供应商
        tOngoodsshelf.setProviderId(notice.getProviderId());
        // 单位
        tOngoodsshelf.setUnit(noticeTab.getUnit());
        // 子需求编号
        tOngoodsshelf.setSalesOrderNumber(noticeTab.getSalesOrderNumber());
        // 物料名称
        tOngoodsshelf.setGoodsName(noticeTab.getGoodsName());
        // 规格型号
        tOngoodsshelf.setSpecification(noticeTab.getSpecification());
        // 物料描述
        tOngoodsshelf.setRecoil(noticeTab.getRecoil());
        // 招标员
        tOngoodsshelf.setCustomerId(notice.getTenderer());
        // 需求组织
        tOngoodsshelf.setOperatorId(notice.getOperatorId());
        // 申请部门
        tOngoodsshelf.setSupplier(noticeTab.getSupplier());
        // 创建时间
        tOngoodsshelf.setOperateDate(noticeTab.getOperateDate());
        // 上报时间
        tOngoodsshelf.setReportTime(noticeTab.getReportTime());
        // 申请单号 设置为来源单号 发货单号 TODO
        tOngoodsshelf.setLotId(notice.getPurchaseId());
        // 申请人
        tOngoodsshelf.setApplicant(notice.getApplicant());
        // 主管部门 TODO
        // tOngoodsshelf.setRespDept(null);
        // 计划日期
        tOngoodsshelf.setPlanDate(noticeTab.getPlanDate());
        // 计划期间
        tOngoodsshelf.setPlanTime(noticeTab.getPlanTime());
        // 需求周期
        tOngoodsshelf.setNeedCycle(noticeTab.getNeedCycle());
        // 需求类型
        tOngoodsshelf.setNeedType(noticeTab.getNeedType());
        // 物料编码
        tOngoodsshelf.setGoodsId(noticeTab.getGoodsId());
        // 物料分类
        tOngoodsshelf.setGoodsTypeId(noticeTab.getGoodsTypeId());
        // 品牌
        tOngoodsshelf.setBrand(noticeTab.getBrand());
        // 计划单价（含税）
        tOngoodsshelf.setPrice(noticeTab.getPrice());
        // 计划金额
        tOngoodsshelf.setTotalMoney(noticeTab.getTotalMoney());
        // 需求时间
        tOngoodsshelf.setExpiryDate(noticeTab.getExpiryDate());
        // 建议供应商名称 TODO
        tOngoodsshelf.setProviderName(notice.getProviderName());
        // 收货人
        tOngoodsshelf.setReceiver(notice.getReceiver());
        // 需求部门
        tOngoodsshelf.setNeedDept(noticeTab.getNeedDept());
        // 采购组织
        tOngoodsshelf.setPurchaseDept(notice.getPurchaseDept());
        // 收货组织
        tOngoodsshelf.setProduclotId(notice.getProduclotId());
        // 收货人部门
        tOngoodsshelf.setReceiverDept(notice.getReceiverDept());
        // 送货区域
        tOngoodsshelf.setReceivingArea(notice.getReceivingArea());
        // 技术需求附件
        tOngoodsshelf.setPackageId(noticeTab.getPackageId());
        // 物资计划明细备注
        tOngoodsshelf.setRemark(noticeTab.getRemark());
        // 用途
        tOngoodsshelf.setUseType(noticeTab.getUseType());
        // 中标供应商联系方式
        tOngoodsshelf.setTelephone(notice.getTelephone());
        // wms订单号
        tOngoodsshelf.setAcceId(notice.getNoticeId());


        // 状态 0:未执行
        tOngoodsshelf.setInStatus("0");
        // 打印状态
        tOngoodsshelf.setPrintSts("0");
        // 打印次数
        tOngoodsshelf.setPrintCs(BigDecimal.ZERO);
        // 生产日期
        tOngoodsshelf.setProductionDate(noticeTab.getProductionDate());
        // 入库类型
        tOngoodsshelf.setStorageMode(params.getStorageMode());
        // 仓库编号
        tOngoodsshelf.setStorageId(noticeTab.getStorageId());
        tOngoodsshelf.setStorageShortName(noticeTab.getStorageShortName());
        // 库位
        tOngoodsshelf.setLocationId(noticeTab.getStorageLocation());
        // 入库方式 TODO
        // tOngoodsshelf.setPurchaseType(noticeTab.getpu.getPurchaseType()));
        // 入库时间
        tOngoodsshelf.setOndate(DateUtils.getTime());
        // 是否人工码盘
        tOngoodsshelf.setManualTrayState("1");
        // 增加采购入库单号 TODO 交货单号
        tOngoodsshelf.setWmsOrderId(notice.getDeliveryId());
        // 增加外部批次号
        tOngoodsshelf.setBatchNo(noticeTab.getBatchNo());
        // 条码
        tOngoodsshelf.setBarcode(noticeTab.getBarcode());

        // 通知单明细编号
        tOngoodsshelf.setNoticeTabId(noticeTab.getId());

        // 托盘
        tOngoodsshelf.setCtl(params.getCtlNo());

        if (ObjectUtils.isEmpty(params.getCtlNo())) {
            tOngoodsshelf.setPlcId((Long) params.getParams().get("plcId"));
            // 状态 2:任务完成 待确认
            tOngoodsshelf.setInStatus("2");
        }

        tOngoodsshelf.setDeptId(params.getDeptId());

        tOngoodsshelf.setCreateBy(SecurityUtils.getUserNick());
        tOngoodsshelf.setCreateTime(new Date());

        // 入库级别
        tOngoodsshelf.setLevelType(noticeTab.getLevelType());
        //申请人
        tOngoodsshelf.setNeedPerson(noticeTab.getNeedPerson());
        tOngoodsshelf.setNeedTel(noticeTab.getNeedTel());

        tOngoodsshelf.setRfidEpc(params.getRfidEpc());

        tOngoodsshelf.setRfidTid(params.getRfidTid());
        // 呼叫任务号
        if (!ObjectUtils.isEmpty(params.getParams().get("callNoticeId"))) {
            tOngoodsshelf.setCallNoticeId((String) params.getParams().get("callNoticeId"));
        }

        return tOngoodsshelf;
    }

    /**
     * 编辑库存信息
     *
     * @param notice
     * @param noticeTab
     * @return
     */
    private TMiStock makeTMiStock(TRkWareNotice notice, TRkWareNoticeTab noticeTab, TRkWareNoticeTabUpdate params ,TOngoodsshelf tOngoodsshelf) {
        TMiStock tMiStock = new TMiStock();

        // 需求数量 TODO
        // tMiStock.setStoNum();

        tMiStock.setId(OrderCodeFactory.getOrderCode("TMI", ""));

        // 上架数量

        tMiStock.setShelvesNum(noticeTab.getAmount());

        // 中标供应商
        tMiStock.setProviderId(notice.getProviderId());
        // 单位
        tMiStock.setUnit(noticeTab.getUnit());
        // 子需求编号
        tMiStock.setSalesOrderNumber(noticeTab.getSalesOrderNumber());
        // 物料名称
        tMiStock.setGoodsName(noticeTab.getGoodsName());
        // 规格型号
        tMiStock.setSpecification(noticeTab.getSpecification());
        // 物料描述
        tMiStock.setRecoil(noticeTab.getRecoil());
        // 招标员
        tMiStock.setCustomerId(notice.getTenderer());
        // 需求组织
        tMiStock.setOperatorId(notice.getOperatorId());
        // 申请部门
        tMiStock.setSupplier(noticeTab.getSupplier());
        // 创建时间
        tMiStock.setOperateDate(noticeTab.getOperateDate());
        // 上报时间
        if (StringUtils.isNotBlank(noticeTab.getReportTime())) {
            tMiStock.setReportTime(noticeTab.getReportTime());
        } else {
            tMiStock.setReportTime(DateUtils.getDate());
        }
        // 申请单号 设置为来源单号 发货单号 TODO
        if (StringUtils.isNotBlank(notice.getDeliveryId())) {
            tMiStock.setLotId(notice.getDeliveryId());
        } else if (StringUtils.isNotBlank(notice.getPurchaseId())) {
            tMiStock.setLotId(notice.getPurchaseId());
        } else if (StringUtils.isNotBlank(noticeTab.getSourceNum())) {
            tMiStock.setLotId(noticeTab.getSourceNum());
        } else {
            tMiStock.setLotId(noticeTab.getPurchaseId());
        }
        // 申请人
        tMiStock.setApplicant(notice.getApplicant());
        // 计划日期
        tMiStock.setPlanDate(noticeTab.getPlanDate());
        // 计划期间
        tMiStock.setPlanTime(noticeTab.getPlanTime());
        // 需求周期
        tMiStock.setNeedCycle(noticeTab.getNeedCycle());
        // 需求类型
        tMiStock.setNeedType(noticeTab.getNeedType());
        // 物料编码
        tMiStock.setGoodsId(noticeTab.getGoodsId());
        // 物料分类
        tMiStock.setGoodsTypeId(noticeTab.getGoodsTypeId());
        // 品牌
        tMiStock.setBrand(noticeTab.getBrand());
        // 计划单价（含税）
        tMiStock.setPrice(noticeTab.getPrice() != null ? noticeTab.getPrice().toString() : null);
        // 计划金额
        tMiStock.setTotalMoney(noticeTab.getTotalMoney());
        // 需求时间
        tMiStock.setExpiryDate(noticeTab.getExpiryDate());
        // 建议供应商名称 TODO
        tMiStock.setProviderName(notice.getProviderName());
        // 收货人
        tMiStock.setReceiver(notice.getReceiver());
        // 需求部门
        tMiStock.setNeedDept(noticeTab.getNeedDept());
        // 采购组织
        tMiStock.setPurchaseDept(notice.getPurchaseDept());
        // 收货组织
        tMiStock.setProduclotId(notice.getProduclotId());
        // 收货人部门
        tMiStock.setReceiverDept(notice.getReceiverDept());
        // 送货区域
        tMiStock.setReceivingArea(notice.getReceivingArea());
        // 技术需求附件
        tMiStock.setPackageId(noticeTab.getPackageId());
        // 物资计划明细备注
        tMiStock.setRemark(noticeTab.getRemark());
        // 用途
        tMiStock.setUseType(noticeTab.getUseType());
        // 中标供应商联系方式
        tMiStock.setTelephone(notice.getTelephone());
        // wms订单号 入库通知单号
        tMiStock.setNoticeId(notice.getId());
        // 生产日期
        tMiStock.setProductionDate(noticeTab.getProductionDate());
        // 入库类型
        tMiStock.setStorageMode(params.getStorageMode());
        // 仓库编号
        tMiStock.setStorageId(noticeTab.getStorageId());


        TBaseStorage tBaseStorage = tBaseStorageMapper.getName(noticeTab.getStorageId());
        tMiStock.setStorageShortName(tBaseStorage.getStorageShortName());
        // 库位
        tMiStock.setLocationId(noticeTab.getStorageLocation());
        // 增加外部批次号
        tMiStock.setBatchNo(noticeTab.getBatchNo());
        // 条码
        tMiStock.setBarcode(noticeTab.getBarcode());
        // 入库级别
        tMiStock.setLevelType(noticeTab.getLevelType());

        // 标准超期呆滞
        tMiStock.setStandard(params.getExtras().get("extraTime"));

        // 托盘
        tMiStock.setCtl(params.getCtlNo());

        tMiStock.setRecordPerson(params.getRecordPerson());

        // 入库时间

        tMiStock.setWareDate(DateUtils.getTime());

        tMiStock.setDeptId(params.getDeptId());
        tMiStock.setNeedPerson(noticeTab.getNeedPerson());
        tMiStock.setNeedTel(noticeTab.getNeedTel());
        tMiStock.setExpiryDate(noticeTab.getExpiryDate());

        tMiStock.setCreateBy(params.getUserName());
        tMiStock.setUpdateBy(params.getUserName());

        tMiStock.setCreateTime(new Date());
        tMiStock.setPurchaseId(noticeTab.getPurchaseId());

        tMiStock.setUpdateTime(new Date());
        tMiStock.setOperateDate(new Date());

        tMiStock.setRfidEpc(tOngoodsshelf.getRfidEpc());

        tMiStock.setRfidTid(tOngoodsshelf.getRfidTid());
        return tMiStock;
    }

    /**
     * 编辑库存信息
     *
     * @param notice
     * @param noticeTab
     * @return
     */
    private TMiStockF makeTMiStockF(TRkWareNotice notice, TRkWareNoticeTab noticeTab, TRkWareNoticeTabUpdate params) {
        TMiStockF tMiStock = new TMiStockF();

        // 需求数量 TODO
        // tMiStock.setStoNum();

        tMiStock.setId(OrderCodeFactory.getOrderCode("TMI", ""));

        // 上架数量
        tMiStock.setShelvesNum(noticeTab.getAmount());
        // 中标供应商
        tMiStock.setProviderId(notice.getProviderId());
        // 单位
        tMiStock.setUnit(noticeTab.getUnit());
        // 子需求编号
        tMiStock.setSalesOrderNumber(noticeTab.getSalesOrderNumber());
        // 物料名称
        tMiStock.setGoodsName(noticeTab.getGoodsName());
        // 规格型号
        tMiStock.setSpecification(noticeTab.getSpecification());
        // 物料描述
        tMiStock.setRecoil(noticeTab.getRecoil());
        // 招标员
        tMiStock.setCustomerId(notice.getTenderer());
        // 需求组织
        tMiStock.setOperatorId(notice.getOperatorId());
        // 申请部门
        tMiStock.setSupplier(noticeTab.getSupplier());
        // 创建时间
        tMiStock.setOperateDate(noticeTab.getOperateDate());
        // 上报时间
        tMiStock.setReportTime(DateUtils.getDate());
        // 申请单号 设置为来源单号 发货单号 TODO
        tMiStock.setLotId(notice.getPurchaseId());
        // 申请人
        tMiStock.setApplicant(notice.getApplicant());
        // 计划日期
        tMiStock.setPlanDate(noticeTab.getPlanDate());
        // 计划期间
        tMiStock.setPlanTime(noticeTab.getPlanTime());
        // 需求周期
        tMiStock.setNeedCycle(noticeTab.getNeedCycle());
        // 需求类型
        tMiStock.setNeedType(noticeTab.getNeedType());
        // 物料编码
        tMiStock.setGoodsId(noticeTab.getGoodsId());
        // 物料分类
        tMiStock.setGoodsTypeId(noticeTab.getGoodsTypeId());
        // 品牌
        tMiStock.setBrand(noticeTab.getBrand());
        // 计划单价（含税）
        tMiStock.setPrice(noticeTab.getPrice() != null ? noticeTab.getPrice().toString() : null);
        // 计划金额
        tMiStock.setTotalMoney(noticeTab.getTotalMoney());
        // 需求时间
        tMiStock.setExpiryDate(noticeTab.getExpiryDate());
        // 建议供应商名称 TODO
        tMiStock.setProviderName(notice.getProviderName());
        // 收货人
        tMiStock.setReceiver(notice.getReceiver());
        // 需求部门
        tMiStock.setNeedDept(noticeTab.getNeedDept());
        // 采购组织
        tMiStock.setPurchaseDept(notice.getPurchaseDept());
        // 收货组织
        tMiStock.setProduclotId(notice.getProduclotId());
        // 收货人部门
        tMiStock.setReceiverDept(notice.getReceiverDept());
        // 送货区域
        tMiStock.setReceivingArea(notice.getReceivingArea());
        // 技术需求附件
        tMiStock.setPackageId(noticeTab.getPackageId());
        // 物资计划明细备注
        tMiStock.setRemark(noticeTab.getRemark());
        // 用途
        tMiStock.setUseType(noticeTab.getUseType());
        // 中标供应商联系方式
        tMiStock.setTelephone(notice.getTelephone());
        // wms订单号 入库通知单号
        tMiStock.setNoticeId(notice.getNoticeId());
        // 生产日期
        tMiStock.setProductionDate(noticeTab.getProductionDate());
        // 入库类型
        tMiStock.setStorageMode(params.getStorageMode());
        // 仓库编号
        tMiStock.setStorageId(noticeTab.getStorageId());
        tMiStock.setStorageShortName(noticeTab.getStorageShortName());
        // 库位
        tMiStock.setLocationId(noticeTab.getStorageLocation());
        // 增加外部批次号
        tMiStock.setBatchNo(noticeTab.getBatchNo());
        // 条码
        tMiStock.setBarcode(noticeTab.getBarcode());
        // 入库级别
        tMiStock.setLevelType(noticeTab.getLevelType());

        // 标准超期呆滞
        tMiStock.setStandard(params.getExtras().get("extraTime"));

        // 托盘
        tMiStock.setCtl(params.getCtlNo());

        tMiStock.setCreateBy(params.getUserName());
        tMiStock.setCreateTime(new Date());
        tMiStock.setRecordPerson(params.getRecordPerson());

        // 入库时间
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        tMiStock.setWareDate(df.format(new Date()));

        tMiStock.setDeptId(params.getDeptId());

        tMiStock.setNoticeTabId(noticeTab.getId());

        return tMiStock;
    }

    /**
     * 删除入库通知单明细
     */
    @Transactional
    @Override
    public Map<String, String> deleteTRkWareNoticeTabByIds(String[] ids) {

        Map<String, String> resultMap = new HashMap<>();

        // 查询是否存在部分收货
        int num = tRkWareNoticeMapper.selectTRkWareNoticeTabByIds(ids);

        if (num != ids.length) {
            resultMap.put("error", "存在部分收货或全部收货的明细数据，不能删除");
            return resultMap;
        }

        tRkWareNoticeMapper.deleteTRkWareNoticeTabByIds(ids);

        resultMap.put("success", "删除成功");
        resultMap.put("error", "");

        return resultMap;
    }

    /**
     * 保存通知单明细
     */
    @Override
    @Transactional
    public Map<String, String> saveNoticeTab(TRkWareNoticeTabUpdate params) {
        // 返回结果
        Map<String, String> resultMap = new HashMap<>();

        // 查询入库通知单明细
        TRkWareNotice tRkWareNotice = tRkWareNoticeMapper.selectTRkWareNoticeById(params.getId());

        if (tRkWareNotice == null) {
            resultMap.put("error", "入库通知单不存在");
            return resultMap;
        }

        if ("2".equals(tRkWareNotice.getReceivingStatus())) {
            resultMap.put("error", "入库通知单已全部收货，请刷新");
            return resultMap;
        }

        // 通知单明细map
        Map<String, TRkWareNoticeTab> trkWareNoticeTabMap = new HashMap<String, TRkWareNoticeTab>();
        for (int i = 0; i < tRkWareNotice.getTRkWareNoticeTabList().size(); i++) {
            TRkWareNoticeTab noticeTab = tRkWareNotice.getTRkWareNoticeTabList().get(i);
            trkWareNoticeTabMap.put(noticeTab.getSalesOrderNumber() + noticeTab.getGoodsId(), noticeTab);
        }

        List<TRkWareNoticeTab> iRkWareNoticeTabs = new ArrayList<TRkWareNoticeTab>();

        // 遍历提交的通知单明细数据
        for (TRkWareNoticeTab tabNew : params.getTrkWareNoticeTabList()) {

            if (trkWareNoticeTabMap.containsKey(tabNew.getSalesOrderNumber() + tabNew.getGoodsId())) {
                throw new RuntimeException(
                        "子需求单号【" + tabNew.getSalesOrderNumber() + "】和物料ID【" + tabNew.getGoodsId() + "】组合重复. ");
            }

            if (ObjectUtils.isEmpty(tabNew.getGoodsId())) {
                resultMap.put("error", "物料编码不能为空");
                return resultMap;
            }

            if (ObjectUtils.isEmpty(tabNew.getGoodsName())) {
                resultMap.put("error", "物料名称不能为空");
                return resultMap;
            }

            BigDecimal receivingNum = tabNew.getReceivingNum() == null ? BigDecimal.ZERO : tabNew.getReceivingNum();
            BigDecimal arraMount = tabNew.getArraMount() == null ? BigDecimal.ZERO : tabNew.getArraMount();

            // if (recNumNowNew.compareTo(BigDecimal.ZERO) > 0
            // || recNumNew.compareTo(BigDecimal.ZERO) > 0) {
            // resultMap.put("error", "物料【" + tabNew.getGoodsName() + "】的签收数量不为0");
            // return resultMap;
            // }

            if (receivingNum.compareTo(BigDecimal.ZERO) <= 0) {
                resultMap.put("error", "物料【" + tabNew.getGoodsName() + "】的签收数量必须大于0");
                return resultMap;
            }

            if (arraMount.compareTo(BigDecimal.ZERO) <= 0) {
                resultMap.put("error", "物料【" + tabNew.getGoodsName() + "】的到货数量必须大于0");
                return resultMap;
            }
            if (receivingNum.compareTo(arraMount) > 0) {
                resultMap.put("error", "物料【" + tabNew.getGoodsName() + "】签收数量不能大于到货数量");
                return resultMap;
            }

            if (receivingNum.compareTo(arraMount) < 0) {
                //拒绝数量
                tabNew.setRejectNum(arraMount.subtract(receivingNum));
            }

            /** 在途 */
            tabNew.setReceivingStatus("0");
            tabNew.setNoticeId(tRkWareNotice.getId());
            tabNew.setId(OrderCodeFactory.getOrderCode("TRKTAB", ""));

            // 托盘
            // tabNew.setCtl(params.getCtlNo());

            tabNew.setCreateBy(SecurityUtils.getUserNick());
            tabNew.setCreateTime(new Date());
            tabNew.setUpdateBy(SecurityUtils.getUserNick());
            tabNew.setUpdateTime(new Date());
            // 二级库
            tabNew.setLevelType("2");

            tabNew.setSourceNum(tRkWareNotice.getDeliveryId());
            tabNew.setDeliveryId(tRkWareNotice.getDeliveryId());

            iRkWareNoticeTabs.add(tabNew);
        }

        if (iRkWareNoticeTabs.size() > 0) {
            // 入库通知单明细批量插入
            tRkWareNoticeMapper.batchTRkWareNoticeTab(iRkWareNoticeTabs);
        }

        resultMap.put("success", "保存成功");
        resultMap.put("error", "");

        return resultMap;
    }

    /**
     * 手动完成通知单明细
     */
    @Override
    @Transactional
    public Map<String, String> manualCompletion(TRkWareNoticeTabUpdate params) {
        // 返回结果
        Map<String, String> resultMap = new HashMap<>();

        List<TRkWareNoticeTab> updateList = new ArrayList<>();
        for (TRkWareNoticeTab tab : params.getTrkWareNoticeTabList()) {
            tab = tRkWareNoticeMapper.selectTRkWareNoticeTabById(tab.getId());
            /** 查询是否存在未完成的入库任务 */
            TOngoodsshelf tOngoodsshelf = new TOngoodsshelf();
            tOngoodsshelf.setNoticeTabId(tab.getId());
            tOngoodsshelf.setInStatus("2");
            List<TOngoodsshelf> tOngoodsshelfs = tOngoodsshelfMapper.selectTOngoodsshelfList(tOngoodsshelf);

            if (tOngoodsshelfs.size() > 0) {
                resultMap.put("error", "通知单明细[" + tab.getId() + "]存在未完成的任务，不能删除");
                return resultMap;
            }

            // 人工设置为全部收货
            tab.setReceivingStatus("2");
            tab.setUpdateTime(new Date());
            tab.setUpdateBy(params.getUserName());

            updateList.add(tab);

            tRkWareNoticeTabMapper.updateTRkWareNoticeTab(tab);
        }

        /** 设置通知单明细为完成状态 */
//        if (updateList.size() > 0) {
//            tRkWareNoticeMapper.updateForeach(updateList);
//        }

        // 查询入库通知单明细
        TRkWareNotice tRkWareNotice = tRkWareNoticeMapper.selectTRkWareNoticeById(params.getId());

        if (tRkWareNotice == null) {
            resultMap.put("error", "入库通知单不存在");
            return resultMap;
        }

        boolean allReceived = true;
        for (TRkWareNoticeTab tab : tRkWareNotice.getTRkWareNoticeTabList()) {
            if ("2".equals(tab.getReceivingStatus())) {
                allReceived = false;
                break;
            }
        }

        // 更细入库通知单状态
        if (allReceived) {
            // 2:全部收货
            tRkWareNotice.setReceivingStatus("2");
            tRkWareNotice.setUpdateBy(params.getUserName());
            tRkWareNotice.setUpdateTime(new Date());
            tRkWareNoticeMapper.updateTRkWareNotice(tRkWareNotice);
        }

        // 查询存货表数据
        TRkReceivingGoods tRkReceivingGoods = tRkReceivingGoodsMapper
                .selectTRkReceivingGoodsByNoticeId(tRkWareNotice.getNoticeId());

        String trkReceivingGoodsId = OrderCodeFactory.getOrderCode("R", "");
        if (tRkReceivingGoods != null) {
            tRkReceivingGoods.setReceivingStatus(tRkWareNotice.getReceivingStatus());
            tRkReceivingGoods.setUpdateBy(params.getUserName());
            tRkReceivingGoods.setUpdateTime(new Date());
            tRkReceivingGoodsMapper.updateTRkReceivingGoods(tRkReceivingGoods);

            trkReceivingGoodsId = tRkReceivingGoods.getId();
        } else {
            TRkReceivingGoods tGoods = new TRkReceivingGoods();
            BeanUtils.copyProperties(tRkWareNotice, tGoods);
            tGoods.setId(trkReceivingGoodsId);
            tGoods.setUpdateBy(params.getUserName());
            tGoods.setUpdateTime(new Date());
            tGoods.setCreateBy(params.getUserName());
            tGoods.setCreateTime(new Date());
            tRkReceivingGoodsMapper.insertTRkReceivingGoods(tGoods);
        }

        // 查询是否存在收货表数据
        if (tRkWareNotice.getTRkWareNoticeTabList().size() > 0) {

            Map<String, TRkReceivingGoodsTab> trkReceiveGoodsTabMap = new HashMap<String, TRkReceivingGoodsTab>();

            if (tRkReceivingGoods != null) {

                for (TRkReceivingGoodsTab goodsTab : tRkReceivingGoods.getTRkReceivingGoodsTabList()) {
                    trkReceiveGoodsTabMap.put(goodsTab.getSalesOrderNumber() + goodsTab.getGoodsId(), goodsTab);
                }
            }
            List<TRkReceivingGoodsTab> insertGoodsTabs = new ArrayList<>();
            // 存货表更新集合
            List<TRkReceivingGoodsTab> tReceivingGoodsTabs = new ArrayList<TRkReceivingGoodsTab>();

            for (TRkWareNoticeTab noticeTab : tRkWareNotice.getTRkWareNoticeTabList()) {
                TRkReceivingGoodsTab goodsTab = trkReceiveGoodsTabMap
                        .get(noticeTab.getSalesOrderNumber() + noticeTab.getGoodsId());
                if (goodsTab != null) {
                    goodsTab.setRecNum(noticeTab.getRecNum());
                    goodsTab.setReceivingStatus(noticeTab.getReceivingStatus());
                    goodsTab.setUpdateBy(params.getUserName());
                    goodsTab.setUpdateTime(new Date());
                    tReceivingGoodsTabs.add(goodsTab);
                } else {
                    goodsTab = new TRkReceivingGoodsTab();
                    BeanUtils.copyProperties(noticeTab, goodsTab);
                    goodsTab.setNoticeId(trkReceivingGoodsId);
//                    goodsTab.setId(OrderCodeFactory.getOrderCode("RTAB", ""));
                    insertGoodsTabs.add(goodsTab);
                }
            }

            if (tReceivingGoodsTabs.size() > 0) {
                // 批量更新存货明细表
                tRkReceivingGoodsMapper.updateForeach(tReceivingGoodsTabs);
            }

            if (insertGoodsTabs.size() > 0) {
                tRkReceivingGoodsMapper.batchTRkReceivingGoodsTab(insertGoodsTabs);
            }
        }

        // 入库通知单及明细数据 移到 bak表
        if (allReceived) {
            // 查询入库通知单明细
            tRkWareNotice = tRkWareNoticeMapper.selectTRkWareNoticeByNoticeId(params.getNoticeId());
            TRkWareNoticeBak tRkWareNoticeBak = new TRkWareNoticeBak();
            BeanUtils.copyProperties(tRkWareNotice, tRkWareNoticeBak);
//            String tRkWareNoticeBakId = OrderCodeFactory.getOrderCode("TRKBAK", "");
//            tRkWareNoticeBak.setId(tRkWareNoticeBakId);
            tRkWareNoticeBakMapper.insertTRkWareNoticeBak(tRkWareNoticeBak);

            List<TRkWareNoticeTabBak> tRkWareNoticeTabBaks = new ArrayList<TRkWareNoticeTabBak>();
            for (TRkWareNoticeTab trWareNoticeTab : tRkWareNotice.getTRkWareNoticeTabList()) {
                TRkWareNoticeTabBak tRkWareNoticeTabBak = new TRkWareNoticeTabBak();
//                trWareNoticeTab.setId(OrderCodeFactory.getOrderCode("TRKTABBAK", ""));
//                trWareNoticeTab.setNoticeId(tRkWareNoticeBakId);
                BeanUtils.copyProperties(trWareNoticeTab, tRkWareNoticeTabBak);
                tRkWareNoticeTabBak.setPurchaser(tRkWareNotice.getPurchaser());
                tRkWareNoticeTabBak.setSendeDate(tRkWareNotice.getSendeDate());
                tRkWareNoticeTabBak.setProviderName(tRkWareNotice.getProviderName());
                tRkWareNoticeTabBak.setRecPerson(tRkWareNotice.getRecPerson());
                tRkWareNoticeTabBaks.add(tRkWareNoticeTabBak);
            }
            if (tRkWareNoticeTabBaks.size() > 0) {
                tRkWareNoticeBakMapper.batchTRkWareNoticeTabBak(tRkWareNoticeTabBaks);
            }

            // 删除入库通知单和明细
            tRkWareNoticeMapper.deleteTRkWareNoticeById(tRkWareNotice.getId());
            tRkWareNoticeMapper.deleteNoticeTabByNoticeId(tRkWareNotice.getId());
        }

        resultMap.put("success", "通知单明细已人工完成");
        resultMap.put("error", "");

        return resultMap;
    }

    /**
     * 入库任务上架确认
     */
    @Override
    @Transactional
    public Map<String, String> shelvesConfirm(TRkWareNoticeTabUpdate params) {
        // 返回结果
        Map<String, String> resultMap = new HashMap<>();



        // 库位
        if (ObjectUtils.isEmpty(params.getStorageLocation())) {
            resultMap.put("error", "库位不能为空");
            return resultMap;
        }

        LambdaQueryWrapper<TBaseStorageAreaLocation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TBaseStorageAreaLocation::getLocationId, params.getStorageLocation());
        List<TBaseStorageAreaLocation> areaLocations = service.selectList(wrapper);
        if (areaLocations.isEmpty()) {
            throw new RuntimeException("库位号错误");
        }

        TBaseStorageAreaLocation locationCheck = areaLocations.get(0);
        if ("1".equals(locationCheck.getIsLock())) {
            resultMap.put("error", "库位【" + params.getStorageLocation() + "】已禁用");
            log.error("库位【" + params.getStorageLocation() + "】已禁用");
            throw new RuntimeException("库位【" + params.getStorageLocation() + "】已禁用");
        }

//        if("0".equals(locationCheck.getStatus())){
//            locationCheck.setStatus("1");
//            service.updateLocationSts(locationCheck);
//        }

        if ("0".equals(locationCheck.getStatus()) || StringUtils.isBlank(locationCheck.getStatus())) {
            TBaseStorageAreaLocation location11 = new TBaseStorageAreaLocation();
            location11.setStatus("1");
            location11.setId(locationCheck.getId());
            location11.setUpdateBy(params.getUserName());
            location11.setUpdateTime(new Date());
            service.updateTBaseStorageAreaLocation(location11);
        }


        if (StringUtils.isNotBlank(params.getCtlNo())) {

            //校验托盘容器是否正确
            LambdaQueryWrapper<TBasePallet> ctlWrapper = new LambdaQueryWrapper<>();
            ctlWrapper.eq(TBasePallet::getPalletId, params.getCtlNo());
            List<TBasePallet> plcs = palletMapper.selectList(ctlWrapper);
            if (!plcs.isEmpty()) {
                TBasePallet palletChk = plcs.get(0);
                if ("1".equals(palletChk.getIsLock())) {
                    resultMap.put("error", "托盘号【" + params.getCtlNo() + "】已禁用");
                    log.error("托盘号【" + params.getCtlNo() + "】已禁用");
                    throw new RuntimeException("托盘号【" + params.getCtlNo() + "】已禁用");
                }

                if ("0".equals(palletChk.getStatus()) || StringUtils.isBlank(palletChk.getStatus())) {
                    TBasePallet tBasePallet = new TBasePallet();
                    tBasePallet.setStatus("1");
                    tBasePallet.setId(palletChk.getId());
                    tBasePallet.setUpdateBy(params.getUserName());
                    tBasePallet.setUpdateTime(new Date());
                    palletMapper.updateTBasePallet(tBasePallet);
                }
            }
        }

        // List<TMiStock> tMiStocks = null;
        // if (!ObjectUtils.isEmpty(params.getCtlNo())) {
        //     // 校验同一托盘号在库存中是否存在
        //     TMiStock tMiStock = new TMiStock();
        //     tMiStock.setCtl(params.getCtlNo());
        //     tMiStocks = tMiStockMapper.selectTMiStockList(tMiStock);

        //     if (tMiStocks.size() > 0) {
        //         resultMap.put("error", "托盘【" + params.getCtlNo() + "】已占用，请更换");
        //         return resultMap;
        //     }
        // }

        // // 校验同一库位是否占用
        // TMiStock tMiStock2 = new TMiStock();
        // tMiStock2.setLocationId(params.getStorageLocation());
        // tMiStocks = tMiStockMapper.selectTMiStockList(tMiStock2);

        // if (tMiStocks.size() > 0) {
        //     resultMap.put("error", "库位【" + params.getCtlNo() + "】已占用，请更换");
        //     return resultMap;
        // }

        // 超期呆滞时间获取
        SysConfig sysConfig = new SysConfig();
        sysConfig.setConfigKey("overdue.stagnation");
        List<SysConfig> sList = sysConfigMapper.selectConfigList(sysConfig);

        if (sList.size() > 0) {
            params.getExtras().put("extraTime", sList.get(0).getConfigValue());
        } else {
            params.getExtras().put("extraTime", "");
        }


        List<TRkWareNoticeTab> updateNoticeTabs = new ArrayList<TRkWareNoticeTab>();
        List<TMiStock> insertTMiStocks = new ArrayList<TMiStock>();
        List<TMiStockF> insertTMiStockFs = new ArrayList<TMiStockF>();

        // 判断通知单明细是否存在为完成的
        Boolean allReceive = true;

        String noticeId = "";
        TRkWareNotice tRkWareNotice = null;

        String callNoticeId = "";

        // 遍历提交的入库任务列表
        for (TOngoodsshelf tOngoodsshelf : params.gettOngoodsshelfList()) {

            // 备份呼叫任务号
            callNoticeId = tOngoodsshelf.getCallNoticeId();

            if (StringUtils.isBlank(noticeId)) {

                noticeId = tOngoodsshelf.getAcceId();

                // 查询入库通知单
                tRkWareNotice = tRkWareNoticeMapper.selectTRkWareNoticeByNoticeId(noticeId);

                if (tRkWareNotice == null) {
                    resultMap.put("error", "入库通知单不存在");
                    return resultMap;
                }

                if ("2".equals(tRkWareNotice.getReceivingStatus())) {
                    resultMap.put("error", "入库通知单已全部收货，请刷新");
                    return resultMap;
                }
            }
            // 根据ID查询入库通知单明细数据
            TRkWareNoticeTab tabOld = tRkWareNoticeMapper.selectTRkWareNoticeTabById(tOngoodsshelf.getNoticeTabId());

            if (tabOld == null) {
                resultMap.put("error", "物料的通知单明细不存在");
                return resultMap;
            }

            if ("2".equals(tabOld.getReceivingStatus())) {
                continue;
            }

            // 累计收货数量
            BigDecimal recNum = tabOld.getRecNum() == null ? BigDecimal.ZERO : tabOld.getRecNum();
            //累计入库数量
            BigDecimal acceNum = tabOld.getAcceNum() == null ? BigDecimal.ZERO : tabOld.getAcceNum();
            // 本次上架数量
            BigDecimal AccNumNew = tOngoodsshelf.getAccNum() == null ? BigDecimal.ZERO : tOngoodsshelf.getAccNum();

            if (AccNumNew.compareTo(BigDecimal.ZERO) == 0) {
                resultMap.put("error", "物料【" + tabOld.getGoodsName() + "】的上架数量不能为0");
                return resultMap;
            }

            // 收货状态：全部收货
            String receiveStatus = "2";

            BigDecimal AccNumTotalNum = AccNumNew.add(acceNum);

            if (AccNumTotalNum.compareTo(recNum) < 0) {
                /** 部分收货 */
                receiveStatus = "1";
            }

            // 设置更新信息
            tabOld.setReceivingStatus(receiveStatus);
            // 本次上架数量
            tabOld.setAmount(AccNumNew);
            // 累计上架数量
            tabOld.setAcceNum(AccNumTotalNum);
            // 托盘
            tabOld.setCtl(params.getCtlNo());

            // LambdaQueryWrapper<TBaseStorage> queryWrapper = new LambdaQueryWrapper<>();
            // queryWrapper.eq(TBaseStorage::getStorageId, tOngoodsshelf.getStorageId());
            // TBaseStorage storage = tBaseStorageMapper.selectOne(queryWrapper);
            // tabOld.setStorageShortName(storage.getStorageShortName());

            tabOld.setUpdateBy(params.getUserName());
            tabOld.setUpdateTime(new Date());

            // 仓库信息
            tabOld.setStorageId(tOngoodsshelf.getStorageId());
            tabOld.setStorageLocation(params.getStorageLocation());
            tabOld.setApplicant(params.getUserName());
            //更新明细
            tRkWareNoticeTabMapper.updateTRkWareNoticeTab(tabOld);
            updateNoticeTabs.add(tabOld);

            // 入库任务: 3 确认完成
            tOngoodsshelf.setStatus("3");
            // 库位
            tOngoodsshelf.setLocationId(params.getStorageLocation());
            // 托盘号
            tOngoodsshelf.setCtl(params.getCtlNo());

            // 入库时间

            tOngoodsshelf.setOndate(DateUtils.getTime());


            TOngoodsshelf rfid = tOngoodsshelfMapper.selectTOngoodsshelfById(tOngoodsshelf.getId());



            // 生成入库任务bak数据
            TOngoodsshelfBak tOngoodsshelfBak = new TOngoodsshelfBak();
            BeanUtils.copyProperties(tOngoodsshelf, tOngoodsshelfBak);
//            tOngoodsshelfBak.setId(OrderCodeFactory.getOrderCode("TSB", ""));
            tOngoodsshelfBakMapper.insertTOngoodsshelfBak(tOngoodsshelfBak);


            // 生成库存信息
            if ("0".equals(params.getFictitious())) {
                String id = tOngoodsshelf.getId();


                insertTMiStocks.add(makeTMiStock(tRkWareNotice, tabOld, params ,rfid));
            } else {
                insertTMiStockFs.add(makeTMiStockF(tRkWareNotice, tabOld, params));
            }

            // 删除入库任务
            tOngoodsshelfMapper.deleteTOngoodsshelfById(tOngoodsshelf.getId());
        }

        if (!StringUtils.isEmpty(callNoticeId)) {
            TOngoodsshelf tOngoodsshelf = new TOngoodsshelf();
            tOngoodsshelf.setCallNoticeId(callNoticeId);
            List<TOngoodsshelf> tOngoodsshelfs = tOngoodsshelfMapper.selectTOngoodsshelfList(tOngoodsshelf);

            if (tOngoodsshelfs.size() == 0) {
                // 关闭入库任务通知
                TCallNotice tCallNotice = new TCallNotice();
                tCallNotice.setId(callNoticeId);
                tCallNotice.setTaskType("0");
                tCallNotice.setUpdateBy(params.getUserName());
                tCallNotice.setUpdateTime(new Date());
                tNoticeService.updateTaskStatus(tCallNotice);
            }
        }

        if ("0".equals(params.getFictitious())) {
            // 更新库存信息
            if (insertTMiStocks.size() > 0) {
                for (TMiStock tMiStock1 : insertTMiStocks) {
                    String goodsId = tMiStock1.getGoodsId();
                    LambdaQueryWrapper<TBaseGoods> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(TBaseGoods::getGoodsId, goodsId);
                    TBaseGoods tBaseGoods = tBaseGoodsMapper.selectOne(queryWrapper);
                    //原来仓库
                    if (tBaseGoods == null) {
                        throw new RuntimeException("物料ID:" + goodsId + "在基础物料没维护，请先维护！");
                    }
                    tMiStock1.setOriginal(tBaseGoods.getStorageId());
                    tMiStock1.setPrice(String.valueOf(tBaseGoods.getPrice()));

                    //总价
                    BigDecimal shelvesNum = tMiStock1.getShelvesNum();
                    BigDecimal price = tBaseGoods.getPrice();
                    if (price == null || price.compareTo(BigDecimal.ZERO) == 0) {
                        price = BigDecimal.ZERO; // 默认值为 1
                    }

                    if (shelvesNum.compareTo(BigDecimal.ZERO) == 0) {
                        throw new RuntimeException("入库数量为0异常");
                    }

                    BigDecimal totalPrice = price.multiply(shelvesNum);
                    tMiStock1.setTotalMoney(totalPrice);
                    tMiStock1.setPrice(String.valueOf(price));


                    tMiStockMapper.insertTMiStock(tMiStock1);
                }
            }
        } else {
            // 更新虚拟库存信息
            if (insertTMiStockFs.size() > 0) {
                for (TMiStockF tMiStock1 : insertTMiStockFs) {
                    tMiStockFMapper.insertTMiStock(tMiStock1);
                }
            }
        }



        // 获取最新的通知单信息，判断是否全部完成
        tRkWareNotice = tRkWareNoticeMapper.selectTRkWareNoticeByNoticeId(noticeId);
        for (TRkWareNoticeTab trkNoticeTab : tRkWareNotice.getTRkWareNoticeTabList()) {
            if (!"2".equals(trkNoticeTab.getReceivingStatus())) {
                allReceive = false;
                break;
            }
        }

        // 更细入库通知单状态
        if (allReceive) {
            // 2:全部收货
            tRkWareNotice.setReceivingStatus("2");
            tRkWareNotice.setUpdateBy(params.getUserName());
            tRkWareNotice.setUpdateTime(new Date());
            tRkWareNoticeMapper.updateTRkWareNotice(tRkWareNotice);
        }

        // 查询存货表数据
        TRkReceivingGoods tRkReceivingGoods = tRkReceivingGoodsMapper
                .selectTRkReceivingGoodsByNoticeId(tRkWareNotice.getNoticeId());

        String trkReceivingGoodsId = OrderCodeFactory.getOrderCode("R", "");
        if (tRkReceivingGoods != null) {
            tRkReceivingGoods.setReceivingStatus(tRkWareNotice.getReceivingStatus());
            tRkReceivingGoods.setUpdateBy(params.getUserName());
            tRkReceivingGoods.setUpdateTime(new Date());
            tRkReceivingGoodsMapper.updateTRkReceivingGoods(tRkReceivingGoods);

            trkReceivingGoodsId = tRkReceivingGoods.getId();
        } else {
            TRkReceivingGoods tGoods = new TRkReceivingGoods();
            BeanUtils.copyProperties(tRkWareNotice, tGoods);
            tGoods.setId(trkReceivingGoodsId);
            tGoods.setUpdateBy(params.getUserName());
            tGoods.setUpdateTime(new Date());
            tGoods.setCreateBy(params.getUserName());
            tGoods.setCreateTime(new Date());
            tRkReceivingGoodsMapper.insertTRkReceivingGoods(tGoods);
        }

        // 查询是否存在收货表数据
        if (updateNoticeTabs.size() > 0) {

            Map<String, TRkReceivingGoodsTab> trkReceiveGoodsTabMap = new HashMap<String, TRkReceivingGoodsTab>();

            if (tRkReceivingGoods != null) {
                for (TRkReceivingGoodsTab goodsTab : tRkReceivingGoods.getTRkReceivingGoodsTabList()) {
                    trkReceiveGoodsTabMap.put(goodsTab.getSalesOrderNumber() + goodsTab.getGoodsId(), goodsTab);
                }
            }

            List<TRkReceivingGoodsTab> insertGoodsTabs = new ArrayList<>();
            // 存货表更新集合
            List<TRkReceivingGoodsTab> tReceivingGoodsTabs = new ArrayList<TRkReceivingGoodsTab>();

            for (TRkWareNoticeTab noticeTab : updateNoticeTabs) {
                TRkReceivingGoodsTab goodsTab = trkReceiveGoodsTabMap
                        .get(noticeTab.getSalesOrderNumber() + noticeTab.getGoodsId());
                if (goodsTab != null) {
                    goodsTab.setRecNum(noticeTab.getRecNum());
                    goodsTab.setReceivingStatus(noticeTab.getReceivingStatus());
                    goodsTab.setUpdateBy(params.getUserName());
                    goodsTab.setUpdateTime(new Date());
                    tReceivingGoodsTabs.add(goodsTab);
                } else {
                    goodsTab = new TRkReceivingGoodsTab();
                    BeanUtils.copyProperties(noticeTab, goodsTab);
                    goodsTab.setNoticeId(trkReceivingGoodsId);
//                    goodsTab.setId(OrderCodeFactory.getOrderCode("RTAB", ""));
                    insertGoodsTabs.add(goodsTab);
                }
            }

            if (tReceivingGoodsTabs.size() > 0) {
                // 批量更新存货明细表
                tRkReceivingGoodsMapper.updateForeach(tReceivingGoodsTabs);
            }

            if (insertGoodsTabs.size() > 0) {
                tRkReceivingGoodsMapper.batchTRkReceivingGoodsTab(insertGoodsTabs);
            }
        }

        // 入库通知单及明细数据 移到 bak表
        if (allReceive) {
            // 查询入库通知单明细
            tRkWareNotice = tRkWareNoticeMapper.selectTRkWareNoticeByNoticeId(tRkWareNotice.getNoticeId());
            TRkWareNoticeBak tRkWareNoticeBak = new TRkWareNoticeBak();
            BeanUtils.copyProperties(tRkWareNotice, tRkWareNoticeBak);
//            String tRkWareNoticeBakId = OrderCodeFactory.getOrderCode("TRKBAK", "");
//            tRkWareNoticeBak.setId(tRkWareNoticeBakId);
            tRkWareNoticeBakMapper.insertTRkWareNoticeBak(tRkWareNoticeBak);

            List<TRkWareNoticeTabBak> tRkWareNoticeTabBaks = new ArrayList<TRkWareNoticeTabBak>();
            for (TRkWareNoticeTab trWareNoticeTab : tRkWareNotice.getTRkWareNoticeTabList()) {
                TRkWareNoticeTabBak tRkWareNoticeTabBak = new TRkWareNoticeTabBak();
//                trWareNoticeTab.setId(OrderCodeFactory.getOrderCode("TRKTABBAK", ""));
//                trWareNoticeTab.setNoticeId(tRkWareNoticeBakId);
                BeanUtils.copyProperties(trWareNoticeTab, tRkWareNoticeTabBak);
                tRkWareNoticeTabBak.setPurchaser(tRkWareNotice.getPurchaser());
                tRkWareNoticeTabBak.setSendeDate(tRkWareNotice.getSendeDate());
                tRkWareNoticeTabBak.setProviderName(tRkWareNotice.getProviderName());
                tRkWareNoticeBak.setRecPerson(tRkWareNotice.getRecPerson());
                tRkWareNoticeTabBaks.add(tRkWareNoticeTabBak);
            }
            if (tRkWareNoticeTabBaks.size() > 0) {
                tRkWareNoticeBakMapper.batchTRkWareNoticeTabBak(tRkWareNoticeTabBaks);
            }

            // 删除入库通知单和明细
            tRkWareNoticeMapper.deleteTRkWareNoticeById(tRkWareNotice.getId());
            tRkWareNoticeMapper.deleteNoticeTabByNoticeId(tRkWareNotice.getId());

            // 关闭入库通知单任务消息
            TCallNoticeOrder tCallNotice = new TCallNoticeOrder();
            tCallNotice.setTaskId(tRkWareNotice.getId());
            tCallNotice.setTaskType("0");
            tCallNotice.setUpdateBy(params.getUserName());
            tCallNotice.setUpdateTime(new Date());
            tNoticeOrderService.updateTaskStatus(tCallNotice);
        }

        resultMap.put("success", "上架成功");
        resultMap.put("error", "");

        return resultMap;
    }


    /**
     * 导入入库通知单数据
     *
     * @param dataList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public String importData(List<TRkWareNoticeTab> dataList, boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(dataList) || dataList.size() == 0) {
            throw new ServiceException("导入入库通知单数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        TRkWareNoticeTab tRkWareNoticeTab1 = dataList.get(0);
        TRkWareNotice tRkWareNotice = new TRkWareNotice();

        //来源单号生成
        Random random = new Random();

        // 生成一个1000到9999之间的随机数
//        int randomFourDigit = 1000 + random.nextInt(9000);

        tRkWareNotice.setDeliveryId(tRkWareNoticeTab1.getDeliveryId());
        List<TRkWareNotice> tRkWareNotices = tRkWareNoticeMapper.selectTRkWareNoticeList(tRkWareNotice);
        if (tRkWareNotices.size() == 0) {
            setTrkNotice(tRkWareNotice, tRkWareNoticeTab1, operName);
            tRkWareNotice.setReceivingStatus("0");
            tRkWareNotice.setStorageMode("1");
            tRkWareNoticeMapper.insertTRkWareNotice(tRkWareNotice);

        } else if (isUpdateSupport) {
            List<String> collect = tRkWareNotices.stream().map(TRkWareNotice::getId).collect(Collectors.toList());
            tRkWareNoticeMapper.deleteTRkWareNoticeByIds(collect.toArray(new String[collect.size()]));
            setTrkNotice(tRkWareNotice, tRkWareNoticeTab1, operName);
            tRkWareNoticeMapper.insertTRkWareNotice(tRkWareNotice);

        } else {
            throw new ServiceException("来源单号 " + tRkWareNoticeTab1.getDeliveryId() + " 重复导入异常！");
        }

        for (int i = 0; i < dataList.size(); i++) {
            try {

                //校验必输字段
                TRkWareNoticeTab tab = dataList.get(i);
                checkData(i, tab);
                // 验证是否存在该明细
//                tab.setDeliveryId(tab.getDeliveryId());
                TRkWareNoticeTab tRkWareNoticeTab = new TRkWareNoticeTab();
                tRkWareNoticeTab.setSalesOrderNumber(tab.getSalesOrderNumber());
                tRkWareNoticeTab.setGoodsId(tab.getGoodsId());
                tRkWareNoticeTab.setReceivingStatus("0");
                tRkWareNoticeTab.setInStatus("0");
                tab.setDataSource("二级库");
                tRkWareNoticeTab.setDataSource("二级库");

                tab.setLevelType("2");

                List<TRkWareNoticeTab> tRkWareNoticeTabs = tRkWareNoticeTabMapper.selectTRkWareNoticeTabList(tRkWareNoticeTab);

                if (tRkWareNoticeTabs.size() == 0) {
                    setTab(tab, tRkWareNotice.getId(), operName);
                    tab.setDeliveryId(tRkWareNoticeTab1.getDeliveryId());
                    tab.setSourceNum(tRkWareNoticeTab1.getDeliveryId());
                    tab.setRecNumNow(null);
                    tab.setRecNum(null);
                    tab.setReceivingNum(tab.getArraMount());
                    tRkWareNoticeTabMapper.insertTRkWareNoticeTab(tab);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、物料编号 " + tab.getGoodsId() + " 导入成功");
                } else if (isUpdateSupport) {
                    List<String> collect = tRkWareNoticeTabs.stream().map(TRkWareNoticeTab::getId).collect(Collectors.toList());
                    tRkWareNoticeTabMapper.deleteTRkWareNoticeTabByIds(collect.toArray(new String[collect.size()]));
                    setTab(tab, tRkWareNotice.getId(), operName);
                    tab.setDeliveryId(tRkWareNoticeTab1.getDeliveryId());
                    tab.setSourceNum(tRkWareNoticeTab1.getDeliveryId());
                    tab.setRecNumNow(null);
                    tab.setRecNum(null);
                    tab.setReceivingNum(tab.getArraMount());
                    tRkWareNoticeTabMapper.insertTRkWareNoticeTab(tab);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、物料编号 " + tab.getGoodsId() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、物料编号 " + tab.getGoodsId() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、来源单号 " + tRkWareNoticeTab1.getDeliveryId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 导入一级库入库通知单数据
     *
     * @param dataList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public String importExcelData(List<TRkWareNoticeTabExcel> dataList, boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(dataList) || dataList.size() == 0) {
            throw new ServiceException("导入入库通知单数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        TRkWareNoticeTabExcel tRkWareNoticeTab1 = dataList.get(0);
        TRkWareNotice tRkWareNotice = new TRkWareNotice();

        //来源单号生成
        Random random = new Random();

        // 生成一个1000到9999之间的随机数
//        int randomFourDigit = 1000 + random.nextInt(9000);
        //一级库发货单号唯一
        tRkWareNotice.setDeliveryId(tRkWareNoticeTab1.getPurchaseId());
        List<TRkWareNotice> tRkWareNotices = tRkWareNoticeMapper.selectTRkWareNoticeList(tRkWareNotice);
        if (tRkWareNotices.size() == 0) {
            setExcelTrkNotice(tRkWareNotice, tRkWareNoticeTab1, operName);
            tRkWareNotice.setReceivingStatus("0");
            tRkWareNotice.setStorageMode("1");
            tRkWareNoticeMapper.insertTRkWareNotice(tRkWareNotice);

//            TRkWareNotice notice2 = new TRkWareNotice();
//            notice2.setId(tRkWareNotice.getId());
//            notice2.setCreateBy(operName);
//            tRkWareNoticeMapper.updateTRkWareNotice(notice2);

        } else if (isUpdateSupport) {
            List<String> collect = tRkWareNotices.stream().map(TRkWareNotice::getId).collect(Collectors.toList());
            tRkWareNoticeMapper.deleteTRkWareNoticeByIds(collect.toArray(new String[collect.size()]));
            setExcelTrkNotice(tRkWareNotice, tRkWareNoticeTab1, operName);
            tRkWareNotice.setReceivingStatus("0");
            tRkWareNotice.setStorageMode("1");
            tRkWareNoticeMapper.insertTRkWareNotice(tRkWareNotice);

        } else {
            throw new ServiceException("来源单号 " + tRkWareNoticeTab1.getDeliveryId() + " 重复导入异常！");
        }

        for (int i = 0; i < dataList.size(); i++) {
            try {

                //校验必输字段
                TRkWareNoticeTabExcel tab = dataList.get(i);
//                checkData(i, tab);
                // 验证是否存在该明细
                tab.setDeliveryId(tab.getPurchaseId());
                TRkWareNoticeTab tRkWareNoticeTab = new TRkWareNoticeTab();
                tRkWareNoticeTab.setSalesOrderNumber(tab.getSalesOrderNumber());
                tRkWareNoticeTab.setGoodsId(tab.getGoodsId());
                tRkWareNoticeTab.setReceivingStatus("0");
                tRkWareNoticeTab.setInStatus("0");
                tRkWareNoticeTab.setDataSource("一级库");

                tab.setDataSource("一级库");
                tab.setLevelType("1");

                SimpleDateFormat originalFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
                SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    if (StringUtils.isNotBlank(tab.getExpiryDate())) {
                        Date date = originalFormat.parse(tab.getExpiryDate());
                        Date date1 = originalFormat.parse(tab.getPlanDate());
                        String formattedDate = targetFormat.format(date);
                        String formattedDate1 = targetFormat.format(date1);
                        System.out.println(formattedDate);
                        tab.setExpiryDate(formattedDate);
                        tab.setPlanDate(formattedDate1);
                    }
                } catch (ParseException e) {

//                    e.printStackTrace();
                }


                TRkWareNoticeTab tab1 = new TRkWareNoticeTab();
                BeanUtils.copyProperties(tab, tab1);
                List<TRkWareNoticeTab> tRkWareNoticeTabs = tRkWareNoticeTabMapper.selectTRkWareNoticeTabList(tRkWareNoticeTab);
                tab1.setDeliveryId(tRkWareNoticeTab1.getDeliveryId());
                tab1.setSourceNum(tRkWareNoticeTab1.getDeliveryId());
                if (tRkWareNoticeTabs.size() == 0) {
                    logger.info("createBy:{}", tab1.getCreateBy());
                    setTab(tab1, tRkWareNotice.getId(), operName);
                    tab1.setReceivingNum(tab.getArraMount());
                    logger.info("createBy:{}", tab1.getCreateBy());
                    tRkWareNoticeTabMapper.insertTRkWareNoticeTab(tab1);
//                    TRkWareNoticeTab tab2 = new TRkWareNoticeTab();
//                    tab2.setId(tab1.getId());
//                    tab2.setCreateBy(operName);
//                    tRkWareNoticeTabMapper.updateTRkWareNoticeTab(tab2);
//                    logger.info("createBy:{}",tab1.getCreateBy());
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、物料编号 " + tab.getGoodsId() + " 导入成功");
                } else if (isUpdateSupport) {
                    List<String> collect = tRkWareNoticeTabs.stream().map(TRkWareNoticeTab::getId).collect(Collectors.toList());
                    tRkWareNoticeTabMapper.deleteTRkWareNoticeTabByIds(collect.toArray(new String[collect.size()]));
                    setTab(tab1, tRkWareNotice.getId(), operName);
                    tab1.setReceivingNum(tab.getArraMount());
                    tRkWareNoticeTabMapper.insertTRkWareNoticeTab(tab1);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、物料编号 " + tab.getGoodsId() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、物料编号 " + tab.getGoodsId() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、来源单号 " + tRkWareNoticeTab1.getDeliveryId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    private void setTab(TRkWareNoticeTab tab, String id, String operName) {
        tab.setId(OrderCodeFactory.getOrderCode("", ""));
        tab.setNoticeId(id);
        tab.setCreateBy(operName);
        tab.setInStatus("0");
        tab.setStatus("0");
        tab.setCreateTime(DateUtils.getNowDate());


    }

    private void setExcelTrkNotice(TRkWareNotice tRkWareNotice, TRkWareNoticeTabExcel tRkWareNoticeTab1, String operName) {
        tRkWareNotice.setId(OrderCodeFactory.getOrderCode("", ""));
        tRkWareNotice.setNoticeId(OrderCodeFactory.getOrderCode("TWO", ""));
        tRkWareNotice.setDeptId(SecurityUtils.getLoginUser().getDeptId());
        if (StringUtils.isBlank(tRkWareNoticeTab1.getApplicant())) {
            tRkWareNotice.setApplicant(tRkWareNoticeTab1.getPurchaser());
        } else {
            tRkWareNotice.setApplicant(tRkWareNoticeTab1.getApplicant());
        }
        tRkWareNotice.setOperatorId(SecurityUtils.getUserNick());
        tRkWareNotice.setOrderType(tRkWareNoticeTab1.getOrderType());
        tRkWareNotice.setReceiveAddr(tRkWareNoticeTab1.getReceiveAddr());
        tRkWareNotice.setReceiver(tRkWareNoticeTab1.getReceiver());
        tRkWareNotice.setReceiverDept(tRkWareNoticeTab1.getReceiverDept());
        tRkWareNotice.setProviderId(tRkWareNoticeTab1.getProviderId());
        tRkWareNotice.setProviderName(tRkWareNoticeTab1.getProviderName());
        tRkWareNotice.setShippingDept(tRkWareNoticeTab1.getShippingDept());
        tRkWareNotice.setContact(tRkWareNoticeTab1.getContact());
        tRkWareNotice.setTelephone(tRkWareNoticeTab1.getNeedTel());
        tRkWareNotice.setSendeDate(tRkWareNoticeTab1.getSendeDate());
        tRkWareNotice.setPurchaseDept(tRkWareNoticeTab1.getPurchaseDept());
        tRkWareNotice.setUseReceiver(tRkWareNoticeTab1.getUseReceiver());
        tRkWareNotice.setUseCustodian(tRkWareNoticeTab1.getUseCustodian());
        tRkWareNotice.setUseLeader(tRkWareNoticeTab1.getUseLeader());
        tRkWareNotice.setReceiverDept(tRkWareNoticeTab1.getReceiverDept());
        tRkWareNotice.setTenderer(tRkWareNoticeTab1.getTenderer());
        tRkWareNotice.setCreateBy(operName);
        tRkWareNotice.setCreateTime(DateUtils.getNowDate());
        tRkWareNotice.setRecPerson(tRkWareNoticeTab1.getRecPerson());
        tRkWareNotice.setPurchaser(tRkWareNoticeTab1.getPurchaser());
        tRkWareNotice.setArraDate(tRkWareNoticeTab1.getArraDate());
        tRkWareNotice.setDocumentStatus(tRkWareNoticeTab1.getDocumentStatus());
        tRkWareNotice.setDeliveryId(tRkWareNoticeTab1.getPurchaseId());
    }

    private void setTrkNotice(TRkWareNotice tRkWareNotice, TRkWareNoticeTab tRkWareNoticeTab1, String operName) {
        tRkWareNotice.setId(OrderCodeFactory.getOrderCode("", ""));
        tRkWareNotice.setNoticeId(OrderCodeFactory.getOrderCode("TWO", ""));
        tRkWareNotice.setDeptId(SecurityUtils.getLoginUser().getDeptId());
        tRkWareNotice.setApplicant(tRkWareNoticeTab1.getApplicant());
        tRkWareNotice.setOrderType(tRkWareNoticeTab1.getOrderType());
        tRkWareNotice.setReceiveAddr(tRkWareNoticeTab1.getReceiveAddr());
        tRkWareNotice.setReceiver(tRkWareNoticeTab1.getReceiver());
        tRkWareNotice.setReceiverDept(tRkWareNoticeTab1.getReceiverDept());
        tRkWareNotice.setProviderId(tRkWareNoticeTab1.getProviderId());
        tRkWareNotice.setProviderName(tRkWareNoticeTab1.getProviderName());
        tRkWareNotice.setShippingDept(tRkWareNoticeTab1.getShippingDept());
        tRkWareNotice.setContact(tRkWareNoticeTab1.getContact());
        tRkWareNotice.setTelephone(tRkWareNoticeTab1.getTelephone());
        tRkWareNotice.setSendeDate(tRkWareNoticeTab1.getSendeDate());
        tRkWareNotice.setPurchaseDept(tRkWareNoticeTab1.getPurchaseDept());
        tRkWareNotice.setUseReceiver(tRkWareNoticeTab1.getUseReceiver());
        tRkWareNotice.setUseCustodian(tRkWareNoticeTab1.getUseCustodian());
        tRkWareNotice.setUseLeader(tRkWareNoticeTab1.getUseLeader());
        tRkWareNotice.setReceiverDept(tRkWareNoticeTab1.getReceiverDept());
        tRkWareNotice.setTenderer(tRkWareNoticeTab1.getTenderer());
        tRkWareNotice.setCreateBy(operName);
        tRkWareNotice.setCreateTime(DateUtils.getNowDate());
        tRkWareNotice.setRecPerson(tRkWareNoticeTab1.getRecPerson());
        tRkWareNotice.setPurchaser(tRkWareNoticeTab1.getPurchaser());
        tRkWareNotice.setArraDate(tRkWareNoticeTab1.getArraDate());
        tRkWareNotice.setDocumentStatus(tRkWareNoticeTab1.getDocumentStatus());
    }

    private void checkData(int index, TRkWareNoticeTab trdata) {
        //来源单号
        if (StringUtils.isBlank(trdata.getDeliveryId())) {
            throw new RuntimeException("导入明细第" + (index + 1) + "条来源单号为空");
        }

        if (StringUtils.isBlank(trdata.getDeliveryId())) {
            throw new RuntimeException("导入明细第" + (index + 1) + "条来源单号为空");
        }


        if (StringUtils.isBlank(trdata.getGoodsId())) {
            throw new RuntimeException("导入明细第" + (index + 1) + "条物料编码为空");
        }
        if (StringUtils.isBlank(trdata.getGoodsName())) {
            throw new RuntimeException("导入明细第" + (index + 1) + "条物料名称为空");
        }
        if (StringUtils.isBlank(trdata.getUnit())) {
            throw new RuntimeException("导入明细第" + (index + 1) + "条物料单位为空");
        }

        if (trdata.getArraMount() == null) {
            throw new RuntimeException("导入明细第" + (index + 1) + "条到货数量为空");
        }
        /*if (StringUtils.isBlank(trdata.getApplicant())) {
            throw new RuntimeException("导入明细第" + (index + 1) + "条申请人为空");
        }*/
        /*if (StringUtils.isBlank(trdata.getSupplier())) {
            throw new RuntimeException("导入明细第" + (index + 1) + "条申请部门为空");
        }*/
    }

    @Override
    @Transactional
    public Map<String, String> sendOrderNotice(TRkWareNoticeTabUpdate update) {
        Map<String, String> resultMap = new HashMap<>();

        LambdaQueryWrapper<TCallNoticeOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TCallNoticeOrder::getTaskId, update.getId());
        wrapper.eq(TCallNoticeOrder::getStatus, "0");
        TCallNoticeOrder tCallNoticeOrder = callNoticeOrderMapper.selectOne(wrapper);
        if (tCallNoticeOrder != null) {
            resultMap.put("error", "已经推送手持设备，请相关人员查看");
            return resultMap;
        }


        // 获取通知单信息
        TRkWareNotice tRkWareNotice = tRkWareNoticeMapper.selectTRkWareNoticeById(update.getId());

        if (ObjectUtils.isEmpty(tRkWareNotice)) {
            resultMap.put("error", "待发送消息的入库通知单不存在");
            return resultMap;
        }

        if (tRkWareNotice.getTRkWareNoticeTabList() == null || tRkWareNotice.getTRkWareNoticeTabList().isEmpty()) {
            resultMap.put("error", "待发送消息的入库通知单没有物料明细数据");
            return resultMap;
        }

        // 发送呼叫任务
        TCallNoticeOrder tCallNotice = new TCallNoticeOrder();
        // 通知单编号
        tCallNotice.setTaskId(tRkWareNotice.getId());
        // 任务类型 0:通知单入库
        tCallNotice.setTaskType("0");
        // 状态
        tCallNotice.setStatus("0");
        // 创建者
        tCallNotice.setCreateBy(update.getCreateBy());
        tCallNotice.setCreateTime(new Date());
        tCallNotice.setUpdateBy(update.getCreateBy());
        tCallNotice.setUpdateTime(new Date());

        // 0:正常任务
        tCallNotice.setFictitious("0");
        // 来源单号
        tCallNotice.setDeliveryId(tRkWareNotice.getDeliveryId());
        // 供应商名
        tCallNotice.setProviderName(tRkWareNotice.getProviderName());
        // 部门ID
        tCallNotice.setDeptId(update.getDeptId());
        // 订单类型
        String storageMode = sysDictDataMapper.selectDictLabel("warehouse_type", tRkWareNotice.getStorageMode());
        tCallNotice.setOrderType(storageMode);
        tNoticeOrderService.sendNotice(tCallNotice);

        resultMap.put("success", "消息发送成功");
        resultMap.put("error", "");
        return resultMap;
    }

    @Override
    @Transactional
    public Map<String, String> handAddGoodsTab(TRkWareNoticeTabUpdate update) {

//        List<TRkWareNoticeTab> noticeTabList = update.getTrkWareNoticeTabList();
        /*noticeTabList.forEach(e->{
            String ctl = e.getCtl();
            String goodsId = e.getGoodsId();
            TOngoodsshelf ongoodsshelf = new TOngoodsshelf();
            ongoodsshelf.setCtl(ctl);
            ongoodsshelf.setGoodsId(goodsId);
            List<TOngoodsshelf> tOngoodsshelves = tOgoodsshelfMapper.selectTOngoodsshelfList(ongoodsshelf);
            if (tOngoodsshelves.isEmpty()){
                throw new RuntimeException(ctl+"已经创建入库任务不允许重复收货");
            }
        });*/
        // 生成一个以"AGV"开头的12位数字字符串
        String prefix = "AGV";
        int numberLength = 6; // 需要生成的数字长度
        StringBuilder numberBuilder = new StringBuilder();
        for (int i = 0; i < numberLength; i++) {
            numberBuilder.append(random.nextInt(10)); // 生成一个0到9的随机数
        }
        String rfid = prefix + numberBuilder.toString();

        Map<String, String> resultMap = new HashMap<>();

        String isAgvByStorageId = tBaseStorageMapper.getIsAgvByStorageId(update.getStorageId());


        if (isAgvByStorageId.equals("1")) {
            TRkWareNotice tRkWareNotice = createTRkWareNotice(update);
            List<TRkWareNoticeTab> updateNoticeTabs = new ArrayList<>();
            for (TRkWareNoticeTab tabNew : update.getTrkWareNoticeTabList()) {
                updateNoticeTabs.add(createTRkWareNoticeTab(tabNew, rfid, update));
            }
            tRkWareNoticeMapper.insertTRkWareNotice(tRkWareNotice);
            if (!updateNoticeTabs.isEmpty()) {
                tRkWareNoticeMapper.batchTRkWareNoticeTab(updateNoticeTabs);
            }
            Map<String, String> map = sendIwmsUnified(update);


            if (map.containsKey("success")) {
                resultMap.put("success", map.get("success"));
            } else {
                resultMap.put("error", map.get("error"));
            }

            return resultMap;
        } else {
            //绑定库位直接上架
            if (StringUtils.isNotBlank(update.getLocationId())) {

                LambdaQueryWrapper<TBaseStorageAreaLocation> locWrapper = new LambdaQueryWrapper<>();
                locWrapper.eq(TBaseStorageAreaLocation::getLocationId, update.getLocationId());
                List<TBaseStorageAreaLocation> areaLocations = service.selectList(locWrapper);
                if (!areaLocations.isEmpty()) {
                    TBaseStorageAreaLocation locationCheck = areaLocations.get(0);
                    if ("1".equals(locationCheck.getIsLock())) {
                        resultMap.put("error", "库位【" + update.getLocationId() + "】已禁用");
                        log.error("库位【" + update.getLocationId() + "】已禁用");
                        return resultMap;
                    }
                }

                if (!ObjectUtils.isEmpty(update.getCtlNo())) {

                    //校验托盘容器是否正确
                    LambdaQueryWrapper<TBasePallet> ctlWrapper = new LambdaQueryWrapper<>();
                    ctlWrapper.eq(TBasePallet::getPalletId, update.getCtlNo());
                    List<TBasePallet> plcs = palletMapper.selectList(ctlWrapper);
                    if (!plcs.isEmpty()) {
                        TBasePallet palletChk = plcs.get(0);
                        if ("1".equals(palletChk.getIsLock())) {
                            resultMap.put("error", "托盘号【" + update.getCtlNo() + "】已禁用");
                            log.error("托盘号【" + update.getCtlNo() + "】已禁用");
                            return resultMap;
                        }
                    }
                }

                List<TRkWareNoticeTab> tabList = update.getTrkWareNoticeTabList();
                for (TRkWareNoticeTab tab : tabList) {

                    LambdaQueryWrapper<TBaseGoods> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(TBaseGoods::getGoodsId, tab.getGoodsId());
                    //物料信息
                    TBaseGoods tBaseGoods = tBaseGoodsMapper.selectOne(wrapper);

                    if (tBaseGoods == null) {
                        resultMap.put("error", "暂无物料信息");
                        return resultMap;
                    }

                    TMiStock tMiStock = new TMiStock();
                    tMiStock.setId(OrderCodeFactory.getOrderCode("TMI", ""));

                    // 上架数量
                    tMiStock.setShelvesNum(tab.getRecNum());
                    // 中标供应商
                    tMiStock.setProviderId(tab.getProviderId());
                    // 单位
                    tMiStock.setUnit(tab.getUnit());
                    // 子需求编号
                    tMiStock.setSalesOrderNumber(OrderCodeFactory.getOrderCode("SJ", ""));
                    // 物料名称
                    tMiStock.setGoodsName(tBaseGoods.getGoodsName());
                    // 规格型号
                    tMiStock.setSpecification(tBaseGoods.getSpecification());
                    // 物料描述
                    tMiStock.setRecoil(tBaseGoods.getRecoil());
                    // 招标员
                    tMiStock.setCustomerId("");
                    // 需求组织
                    tMiStock.setOperatorId(SecurityUtils.getUserNick());
                    // 申请部门
                    tMiStock.setSupplier(SecurityUtils.getDeptName());
                    // 创建时间
                    tMiStock.setOperateDate(new Date());
                    // 上报时间
                    tMiStock.setReportTime(DateUtils.getDate());
                    // 申请单号 设置为来源单号 发货单号 TODO
                    tMiStock.setLotId(OrderCodeFactory.getOrderCode("RK", ""));
                    // 申请人
                    tMiStock.setApplicant(SecurityUtils.getUserNick());
                    // 计划日期
                    tMiStock.setPlanDate("");
                    // 计划期间
                    tMiStock.setPlanTime("");
                    // 需求周期
                    tMiStock.setNeedCycle(tab.getNeedCycle());
                    // 需求类型
                    tMiStock.setNeedType(tab.getNeedType());
                    // 物料编码
                    tMiStock.setGoodsId(tab.getGoodsId());
                    // 物料分类
                    tMiStock.setGoodsTypeId(tab.getGoodsTypeId());
                    // 品牌
                    tMiStock.setBrand(tab.getBrand());
                    // 计划单价（含税）
                    tMiStock.setPrice(tab.getPrice() != null ? tab.getPrice().toString() : null);
                    // 计划金额

                    BigDecimal shelvesNum = tab.getRecNum();
                    BigDecimal price = tBaseGoods.getPrice();
                    if (price == null || price.compareTo(BigDecimal.ZERO) == 0) {
                        price = BigDecimal.ZERO; // 默认值为 1
                    }


                    tMiStock.setTotalMoney(price.multiply(shelvesNum));
                    // 需求时间
                    tMiStock.setExpiryDate(tab.getExpiryDate());
                    // 建议供应商名称 TODO
                    tMiStock.setProviderName(tab.getProviderName());
                    // 收货人
                    tMiStock.setReceiver(SecurityUtils.getUserNick());
                    // 需求部门
                    tMiStock.setNeedDept(SecurityUtils.getDeptName());
                    // 采购组织
                    tMiStock.setPurchaseDept(SecurityUtils.getDeptName());
                    // 收货组织
                    tMiStock.setProduclotId(SecurityUtils.getDeptName());
                    // 收货人部门
                    tMiStock.setReceiverDept(SecurityUtils.getDeptName());
                    // 送货区域
                    tMiStock.setReceivingArea(tab.getReceivingArea());
                    // 技术需求附件
                    tMiStock.setPackageId(tab.getPackageId());
                    // 物资计划明细备注
                    tMiStock.setRemark(tab.getRemark());
                    // 用途
                    tMiStock.setUseType(tab.getUseType());
                    // 中标供应商联系方式
                    tMiStock.setTelephone(tab.getTelephone());
                    // wms订单号 入库通知单号
                    tMiStock.setNoticeId(tab.getNoticeId());
                    // 生产日期
                    tMiStock.setProductionDate(tab.getProductionDate());
                    // 入库类型
                    tMiStock.setStorageMode("1");
                    // 仓库编号
                    tMiStock.setStorageId(update.getStorageId());
                    TBaseStorage agvByStorageId = tBaseStorageMapper.getName(update.getStorageId());

                    tMiStock.setStorageShortName(agvByStorageId.getStorageShortName());
                    // 库位
                    tMiStock.setLocationId(update.getStorageLocation());
                    // 增加外部批次号
                    tMiStock.setBatchNo(tab.getBatchNo());
                    // 条码
                    tMiStock.setBarcode(tab.getBarcode());
                    // 入库级别

                    tMiStock.setLevelType(update.getTypes());

                    tMiStock.setStandard("180");

                    // 托盘
                    tMiStock.setCtl(update.getCtlNo());
                    tMiStock.setOriginal(tBaseGoods.getStorageId());

                    tMiStock.setCreateBy(SecurityUtils.getUserNick());
                    tMiStock.setCreateTime(new Date());
                    tMiStock.setRecordPerson("");
                    tMiStock.setLocationId(update.getLocationId());

                    // 入库时间
                    tMiStock.setWareDate(DateUtils.getTime());

                    tMiStock.setDeptId(SecurityUtils.getDeptId());
                    tMiStock.setNeedPerson(tab.getNeedPerson());
                    tMiStock.setNeedTel(tab.getNeedTel());
                    tMiStockMapper.insertTMiStock(tMiStock);
                }
                resultMap.put("success", "入库成功");
                return resultMap;
            }

            //原来的逻辑
            handleOtherStorage(update, resultMap);
        }
        return resultMap;
    }

    private TRkWareNotice createTRkWareNotice(TRkWareNoticeTabUpdate update) {
        TRkWareNotice tRkWareNotice = new TRkWareNotice();
        tRkWareNotice.setId(update.getId());
        tRkWareNotice.setNoticeId(update.getNoticeId());
        tRkWareNotice.setUpdateBy(update.getRecordPerson());
        tRkWareNotice.setUpdateTime(new Date());
        tRkWareNotice.setCreateBy(update.getRecordPerson());
        tRkWareNotice.setCreateTime(new Date());
        tRkWareNotice.setStorageMode("3");
        tRkWareNotice.setReceivingStatus("3");
        tRkWareNotice.setDeptId(update.getDeptId());
        return tRkWareNotice;
    }

    private TRkWareNoticeTab createTRkWareNoticeTab(TRkWareNoticeTab tabNew, String rfid, TRkWareNoticeTabUpdate update) {
        tabNew.setSalesOrderNumber(rfid);
        tabNew.setReceivingStatus("3");
        tabNew.setInStatus("1");
        tabNew.setRecNumNow(tabNew.getRecNum());
        tabNew.setArraMount(tabNew.getRecNum());
        tabNew.setReceivingNum(tabNew.getRecNum());
        tabNew.setUpdateBy(update.getRecordPerson());
        tabNew.setUpdateTime(new Date());
        tabNew.setCreateBy(update.getRecordPerson());
        tabNew.setCreateTime(new Date());
        tabNew.setNoticeId(update.getId());
        tabNew.setId(OrderCodeFactory.getOrderCode("TRKTAB", ""));
        tabNew.setLevelType("2");
        return tabNew;
    }

    private void handleOtherStorage(TRkWareNoticeTabUpdate update, Map<String, String> resultMap) {
        if (ObjectUtils.isEmpty(update.getCtlNo())) {
            List<Plc> plcSList = plcService.selectPlcList();
            Plc plc = plcSList.get(0);
            if (plc.getPlcid() == 9999999) {
                plc.setPlcid(0L);
            } else {
                plc.setPlcid(plc.getPlcid() + 1);
            }
            plc.setId(1);
            plcService.updatePlc(plc);
            update.getParams().put("plcId", plc.getPlcid());
        } else {
            LambdaQueryWrapper<TBasePallet> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TBasePallet::getPalletId, update.getCtlNo());
            List<TBasePallet> plcs = palletMapper.selectList(wrapper);
            if (plcs.isEmpty()) {
                resultMap.put("error", "托盘不存在");
                return;
            }

            TBasePallet palletChk = plcs.get(0);
            if ("1".equals(palletChk.getIsLock())) {
                resultMap.put("error", "托盘号【" + update.getCtlNo() + "】已禁用");
                log.error("托盘号【" + update.getCtlNo() + "】已禁用");
                throw new RuntimeException("托盘号【" + update.getCtlNo() + "】已禁用");
            }
        }

        TCallNotice tCallNotice = new TCallNotice();
        tCallNotice.setId(IdUtils.randomUUID());
        update.getParams().put("callNoticeId", tCallNotice.getId());

        TRkWareNotice tRkWareNotice = new TRkWareNotice();
        tRkWareNotice.setId(update.getId());
        tRkWareNotice.setNoticeId(update.getNoticeId());
        tRkWareNotice.setUpdateBy(update.getRecordPerson());
        tRkWareNotice.setUpdateTime(new Date());
        tRkWareNotice.setCreateBy(update.getRecordPerson());
        tRkWareNotice.setCreateTime(new Date());
        tRkWareNotice.setStorageMode("3");
        tRkWareNotice.setReceivingStatus("0");
        tRkWareNoticeMapper.insertTRkWareNotice(tRkWareNotice);

        List<TRkWareNoticeTab> updateNoticeTabs = new ArrayList<TRkWareNoticeTab>();
        List<TOngoodsshelf> insertTOngoodsshelfs = new ArrayList<TOngoodsshelf>();

        // 遍历提交的物料数据明细
        int ziNeedNo = 0;
        TBaseStorage tBaseStorage = new TBaseStorage();
        // 获取仓库信息
        if (!ObjectUtils.isEmpty(update.getStorageId())) {
            tBaseStorage.setStorageId(update.getStorageId());
            List<TBaseStorage> sTBaseStorages = tBaseStorageMapper.selectTBaseStorageList(tBaseStorage);

            if (sTBaseStorages.size() > 0) {
                tBaseStorage = sTBaseStorages.get(0);
            }
        }

        for (TRkWareNoticeTab tabNew : update.getTrkWareNoticeTabList()) {
            // 仓库名称
            tabNew.setStorageShortName(tBaseStorage.getStorageShortName());

            // 子需求编号
            tabNew.setSalesOrderNumber(String.valueOf(ziNeedNo));
            ziNeedNo++;
            // 在途
            tabNew.setReceivingStatus("0");
            // 冻结
            tabNew.setInStatus("1");
            tabNew.setRecNumNow(tabNew.getRecNum());
            tabNew.setUpdateBy(update.getRecordPerson());
            tabNew.setUpdateTime(new Date());
            tabNew.setCreateBy(update.getRecordPerson());
            tabNew.setCreateTime(new Date());
            tabNew.setNoticeId(update.getId());
            tabNew.setStorageId(update.getStorageId());
            tabNew.setId(OrderCodeFactory.getOrderCode("TRKTAB", ""));
            tabNew.setLevelType(update.getTypes());
            updateNoticeTabs.add(tabNew);
            insertTOngoodsshelfs.add(makeTOngoodsshelf(tRkWareNotice, tabNew, update));
        }

        // 生成入库任务
        if (insertTOngoodsshelfs.size() > 0) {
            for (TOngoodsshelf tOngoodsshelf : insertTOngoodsshelfs) {
                tOngoodsshelf.setStorageId(update.getStorageId());
                tOngoodsshelfMapper.insertTOngoodsshelf(tOngoodsshelf);
            }
            tCallNotice.setStorageId(update.getStorageId());
            tCallNotice.setStorageShortName(update.getStorageShortName());
            tCallNotice.setCtl(update.getCtlNo());
            if (StringUtils.isEmpty(update.getCtlNo())) {
                // pLCID
                tCallNotice.setPlcid((Long) update.getParams().get("plcId"));
            }
            tCallNotice.setTaskType("0");
            tCallNotice.setCreateBy(update.getRecordPerson());
            tCallNotice.setCreateTime(new Date());
            tCallNotice.setStatus("0");
            tCallNotice.setFictitious("0");
            tCallNotice.setTaskId(tRkWareNotice.getNoticeId());
            tNoticeService.sendNotice(tCallNotice);
        }

        if (updateNoticeTabs.size() > 0) {
            // 入库通知单明细批量插入
            tRkWareNoticeMapper.batchTRkWareNoticeTab(updateNoticeTabs);
        }
        resultMap.put("success", "收货成功");
        resultMap.put("error", "");
    }


    @Override
    @Transactional
    @Log(title = "入库推送")
    public Map<String, String> sendIwmsUnified(TRkWareNoticeTabUpdate update) {
        Map<String, String> resultMap = new HashMap<>();
        List<TRkWareNoticeTab> noticeTabList = update.getTrkWareNoticeTabList();

        if (noticeTabList != null) {
            for (TRkWareNoticeTab tRkWareNoticeTab : noticeTabList) {
                // 获取推送过来的数量
                BigDecimal recNumNow = tRkWareNoticeTab.getRecNumNow();
                String id = tRkWareNoticeTab.getId();

                // 查询数据库中的当前数量
                TRkWareNoticeTab tab = tRkWareNoticeTabMapper.selectTRkWareNoticeTabById(id);
                BigDecimal recNum = tab.getReceivingNum();
                if (recNum == null) {
                    recNum = tab.getArraMount();
                }

                TRkWareNoticeTab tRkWareNoticeTab1 = new TRkWareNoticeTab();
                // 检查数量是否不一致
                if (recNumNow.compareTo(recNum) < 0) { // 使用 compareTo 进行 BigDecimal 比较
                    // 计算差值
                    BigDecimal difference = recNum.subtract(recNumNow); // 计算剩余数量

                    // 创建新的入库单记录剩余数量
                    if (difference.compareTo(BigDecimal.ZERO) > 0) { // 如果剩余数量大于 0
                        TRkWareNoticeTab newTab = new TRkWareNoticeTab();
                        BeanUtils.copyProperties(tab, newTab);
                        newTab.setRecNum(null); // 设置剩余数量
                        newTab.setReceivingNum(difference);
                        newTab.setArraMount(difference); // 设置剩余数量
                        // 这里可以设置其他必要的字段，例如物料编号、入库单号等
                        newTab.setId(OrderCodeFactory.getOrderCode("TRKTAB", ""));
                        tRkWareNoticeTabMapper.insertTRkWareNoticeTab(newTab); // 插入新的入库单
//                        tRkWareNoticeTab1.setReceivingStatus("1");
                    }
                }
                // 更新当前入库单的数量
                tRkWareNoticeTab1.setId(id);
                tRkWareNoticeTab1.setRecNum(recNumNow);
                tRkWareNoticeTab1.setInStatus("1");
                tRkWareNoticeTabMapper.updateNum(tRkWareNoticeTab1);
            }
        } else {
            resultMap.put("error", "收货明细为空异常");
            return resultMap;
        }

        // 获取通知单信息
        if (StringUtils.isBlank(update.getCtlNo())) {
            resultMap.put("error", "推送机器人请扫描托盘号");
            return resultMap;
        }
        TRkWareNotice tRkWareNotice = tRkWareNoticeMapper.selectTRkWareNoticeById(update.getId());
        if (ObjectUtils.isEmpty(tRkWareNotice)) {
            resultMap.put("error", "待发送消息的入库通知单不存在");
            return resultMap;
        }
        if (tRkWareNotice.getTRkWareNoticeTabList() == null || tRkWareNotice.getTRkWareNoticeTabList().isEmpty()) {
            resultMap.put("error", "待发送消息的入库通知单没有物料明细数据");
            return resultMap;
        }

        // 根据 ctl 判断使用哪个 URL
        /*final String url = update.getCtlNo() != null && update.getCtlNo().startsWith("A1") ?
                "https://172.18.29.101/wms/api/RestJsonService/pushIntoOrder" :
                "http://172.18.29.101:32130/wms/api/flow/3c/pushIntoOrderBox";*/

        String url = "https://172.18.29.101/wms/api/RestJsonService/pushIntoOrder";
        ObjectMapper objectMapper = new ObjectMapper();
        String reqCode = generateRandomHexCode(20);

        // 请求主体
        Map<String, Object> requestData = new HashMap<>();
        requestData.put("reqCode", reqCode);
        List<TRkWareNoticeTab> tabList = update.getTrkWareNoticeTabList();
        List<TRkWareNoticeTab> updatedTabs = new ArrayList<>();
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (TRkWareNoticeTab tab : tabList) {
            Map<String, Object> dataObject = new HashMap<>();
            populateDataObject(dataObject, tab, update);
            dataList.add(dataObject);
            // Update tab status
//            tab.setInStatus("1");
//            tab.setRecNum(tab.getRe);
//            updatedTabs.add(tab);
        }

        requestData.put("data", dataList); // 循环结束后，将列表赋值给requestData的data键
        //测试 不用就关闭注释
//        updateNoticeAndOrderStatus(tRkWareNotice, update, updatedTabs);
        String requestBody = "";
        try {
            requestBody = objectMapper.writeValueAsString(requestData);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        try (CloseableHttpClient httpClient = createHttpClient()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(new StringEntity(requestBody));
            HttpResponse response = httpClient.execute(httpPost);
            String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");

            // Parse the JSON response
            JsonNode responseJson = objectMapper.readTree(responseString);
            if (responseJson.get("code").asInt() == 0) {
                resultMap.put("success", "消息发送成功");
                updateNoticeAndOrderStatus(tRkWareNotice, update, updatedTabs);
            } else {
                resultMap.put("error", "消息发送失败: " + responseJson.get("message").asText());
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("error", "系统异常: " + e.getMessage());
        }
//                resultMap.put("success", "消息发送成功");
        return resultMap;
    }

    private String generateRandomHexCode(int length) {
        // 生成一个以"rfid"开头的12位数字字符串
        String prefix = "rfid";
        int numberLength = length; // 需要生成的数字长度
        StringBuilder numberBuilder = new StringBuilder();
        for (int i = 0; i < numberLength; i++) {
            numberBuilder.append(random.nextInt(10)); // 生成一个0到9的随机数
        }
        String rfid = prefix + numberBuilder.toString();
        return rfid;
    }

    private void populateDataObject(Map<String, Object> dataObject, TRkWareNoticeTab tab, TRkWareNoticeTabUpdate update) {
        dataObject.put("operType", "A");
        dataObject.put("orderType", update.getCtlNo() != null && update.getCtlNo().startsWith("A1") ? "4" : "1");
        dataObject.put("orderNum", update.getId());
        dataObject.put("orderItem", tab.getId());
        dataObject.put("orderKeyThird", tab.getSalesOrderNumber());
        dataObject.put("whCode", "RZ01");
        dataObject.put("ownerCode", "8000");
        dataObject.put("matCode", tab.getGoodsId());
        dataObject.put("matQty", tab.getRecNumNow());
        dataObject.put("traceCode", update.getCtlNo() == null ? tab.getCtl() : update.getCtlNo());
        dataObject.put("intoOrderStr2", update.getCtlNo() != null && update.getCtlNo().startsWith("A1") ? "KQTRAY" : "KQ2LBOX");

        if (update.getCtlNo() != null && update.getCtlNo().startsWith("A1")) {
            dataObject.put("batchAttr07", "1");
            dataObject.put("intoOrderStr2", "KQTRAY");
        } else {
            dataObject.put("intoOrderBox2", "KQ2LBOX");
            dataObject.put("boxAttr07", "2");
            dataObject.put("boxCode", generateRandomHexCode(8));
            dataObject.put("boxQty", tab.getArraMount());
        }
/*
        dataObject.put("createUser", tab.getApplicant());
*/


    }

    private void updateNoticeAndOrderStatus(TRkWareNotice tRkWareNotice, TRkWareNoticeTabUpdate update, List<TRkWareNoticeTab> updatedTabs) {
        tRkWareNotice.setReceiver(SecurityUtils.getUserNick());
//        List<TRkWareNoticeTab> tabs = updatedTabs;
//        for (TRkWareNoticeTab tab : tabs) {
//            if(tab.getRecNum() == null)
//                tab.setRecNum(BigDecimal.ZERO);
//            tab.setRecNum(tab.getRecNum().add(tab.getRecNumNow()));
//            tRkWareNoticeTabMapper.updateTRkWareNoticeTab(tab);
//        }
//        tRkWareNoticeMapper.updateForeach(updatedTabs);
        //获取最新的通知单
        TRkWareNotice notice = selectTRkWareNoticeById(update.getId());
        List<TRkWareNoticeTab> list = notice.getTRkWareNoticeTabList();
        int count = (int) list.stream().filter(c -> c.getInStatus().equals("0")).count();

        if (count == 0) {
            tRkWareNotice.setReceivingStatus("1");
        }
        if (update.getTrkWareNoticeTabList() == null) {
            tRkWareNotice.setReceivingStatus("3");
            LambdaQueryWrapper<TCallNoticeOrder> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TCallNoticeOrder::getTaskId, update.getNoticeId());
        }
        tRkWareNoticeMapper.updateTRkWareNotice(tRkWareNotice);


    }


    private SSLContext createTrustAllSslContext() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }


                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };

        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        return sslContext;
    }

    private CloseableHttpClient createHttpClient() throws Exception {
        return HttpClients.custom()
                .setSslcontext(createTrustAllSslContext())
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();
    }

    private static HashSet<Integer> usedNumbers = new HashSet<>();
    private static Random random = new Random();

    public static String generateUniqueSalesOrderNumber() {
        int uniqueNumber;
        do {
            uniqueNumber = 1000 + random.nextInt(9000); // 生成1000到9999之间的随机数
        } while (usedNumbers.contains(uniqueNumber));
        usedNumbers.add(uniqueNumber);
        return "AGV" + uniqueNumber;
    }


    /**
     * 虚拟库位上架
     *
     * @param
     * @return
     */
    @Override
    public Map<String, String> virtualListing(TCkOrders orders) {
        Map<String, String> resultMap = new HashMap<>();

        TRkWareNotice wareNotice = new TRkWareNotice();
        wareNotice.setId(OrderCodeFactory.getOrderCode("", ""));
        wareNotice.setNoticeId(OrderCodeFactory.getOrderCode("TWO", ""));
        wareNotice.setDeptId(SecurityUtils.getLoginUser().getDeptId());
        wareNotice.setApplicant(SecurityUtils.getUserNick());
        wareNotice.setOrderType("3");
        wareNotice.setCreateBy(SecurityUtils.getUserNick());
        wareNotice.setCreateTime(DateUtils.getNowDate());
        wareNotice.setIsAvgExec("1");
        int i = insertTRkWareNotice(wareNotice);
        TMiStock tMiStock = new TMiStock();
        for (TCkOrderdetail ckOrderdetail : orders.getTckOrderdetailList()) {

            if (!ObjectUtils.isEmpty(ckOrderdetail.getLocationId())) {
                LambdaQueryWrapper<TBaseStorageAreaLocation> locWrapper = new LambdaQueryWrapper<>();
                locWrapper.eq(TBaseStorageAreaLocation::getLocationId, ckOrderdetail.getLocationId());
                List<TBaseStorageAreaLocation> areaLocations = service.selectList(locWrapper);
                if (!areaLocations.isEmpty()) {
                    TBaseStorageAreaLocation locationCheck = areaLocations.get(0);
                    if ("1".equals(locationCheck.getIsLock())) {
                        resultMap.put("error", "库位【" + ckOrderdetail.getLocationId() + "】已禁用");
                        log.error("库位【" + ckOrderdetail.getLocationId() + "】已禁用");
                        return resultMap;
                    }
                }
            }

            if (!ObjectUtils.isEmpty(ckOrderdetail.getCtl())) {

                //校验托盘容器是否正确
                LambdaQueryWrapper<TBasePallet> ctlWrapper = new LambdaQueryWrapper<>();
                ctlWrapper.eq(TBasePallet::getPalletId, ckOrderdetail.getCtl());
                List<TBasePallet> plcs = palletMapper.selectList(ctlWrapper);
                if (!plcs.isEmpty()) {
                    TBasePallet palletChk = plcs.get(0);
                    if ("1".equals(palletChk.getIsLock())) {
                        resultMap.put("error", "托盘号【" + ckOrderdetail.getCtl() + "】已禁用");
                        log.error("托盘号【" + ckOrderdetail.getCtl() + "】已禁用");
                        return resultMap;
                    }
                }
            }

            List<TRkWareNoticeTab> tabs = new ArrayList<>();
            LambdaQueryWrapper<TMiStock> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TMiStock::getCtl, ckOrderdetail.getCtl());
            queryWrapper.eq(TMiStock::getGoodsId, ckOrderdetail.getGoodsId());
            queryWrapper.eq(TMiStock::getGoodsName, ckOrderdetail.getGoodsName());
            queryWrapper.eq(TMiStock::getLocationId, ckOrderdetail.getLocationId());
            queryWrapper.eq(TMiStock::getStorageId, ckOrderdetail.getStorageId());
            queryWrapper.eq(TMiStock::getShelvesNum, ckOrderdetail.getShelvesNum());
            tMiStock = tMiStockMapper.selectOne(queryWrapper);
            if (tMiStock != null) {
                TRkWareNoticeTab noticeTab = new TRkWareNoticeTab();
                noticeTab.setStorageId(orders.getStorageId());
                noticeTab.setStorageShortName(orders.getStorageShortName());
                noticeTab.setRecNum(ckOrderdetail.getShelvesNum());
                noticeTab.setArraMount(tMiStock.getShelvesNum());
                noticeTab.setRecNumNow(ckOrderdetail.getShelvesNum());
                noticeTab.setId(OrderCodeFactory.getOrderCode("TR", ""));
                noticeTab.setNoticeId(wareNotice.getId());
                noticeTab.setGoodsId(ckOrderdetail.getGoodsId());
                noticeTab.setGoodsName(ckOrderdetail.getGoodsName());
                noticeTab.setUnit(ckOrderdetail.getUnit());
                noticeTab.setSpecification(ckOrderdetail.getSpecification());
                noticeTab.setAbc(ckOrderdetail.getAbc());
                noticeTab.setApplicant(SecurityUtils.getUserNick());
                noticeTab.setCreateBy(SecurityUtils.getUserNick());
                noticeTab.setLevelType("1");
                noticeTab.setCtl(ckOrderdetail.getCtl());
                noticeTab.setCreateTime(new Date());
                //已经收货
                noticeTab.setInStatus("2");
                //来源单号
                noticeTab.setSalesOrderNumber(generateUniqueSalesOrderNumber());
                tabs.add(noticeTab);

                //通知明显
                if (i >= 1) {
                    tRkWareNoticeMapper.batchTRkWareNoticeTab(tabs);
                }
                tMiStockMapper.deleteById(tMiStock.getId());
                //删除 库存等待过账
            } else {
                resultMap.put("error", "暂无库存信息");
                return resultMap;
            }
        }
        // 所有明细单插入完成后调用
        TRkWareNoticeTabUpdate update = new TRkWareNoticeTabUpdate();
        update.setId(wareNotice.getId());

        /*Map<String, String> map = sendIwmsUnified(update);
        if (map.get("code").equals("0")) {
            //删除库存 过账
            if (tMiStock != null) {
                tMiStockMapper.deleteById(tMiStock);
            }
            resultMap.put("success", "机器人收货成功");
        } else {
            resultMap.put("error", "操作失败请联系管理员");
        }*/


        resultMap.put("success", "机器人上架");
        return resultMap;
    }

    @Override
    public Map<String, String> workshopReturn(TckOrdersBak orders) {
        Map<String, String> result = new HashMap<String, String>();

        if (ObjectUtils.isEmpty(orders.getTckOrderdetailBakList())) {
            result.put("error", "物料列表为空");
            return result;
        }

        // 生成入库通知单
        TRkWareNotice tRkWareNotice = new TRkWareNotice();
        tRkWareNotice.setId(OrderCodeFactory.getOrderCode("", ""));
        tRkWareNotice.setNoticeId(OrderCodeFactory.getOrderCode("TWO", ""));
        tRkWareNotice.setUpdateBy(orders.getApplicant());
        tRkWareNotice.setUpdateTime(new Date());
        tRkWareNotice.setCreateBy(orders.getApplicant());
        tRkWareNotice.setCreateTime(new Date());
        tRkWareNotice.setStorageMode("2");
        tRkWareNotice.setReceivingStatus("0");
        tRkWareNotice.setApplicant(SecurityUtils.getUserNick());
        tRkWareNotice.setSendeDate(DateUtils.getDate());
        tRkWareNotice.setDeptId(orders.getDeptId());

        String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Date date = new Date();
        String uniqueId = String.valueOf(date.getTime());
        SimpleDateFormat df = new SimpleDateFormat("HHmmss");
        String timeString = df.format(date);
        String randomLetter = String.valueOf(letters.charAt(random.nextInt(25)));

        // String deliveryId = String.valueOf(Math.floor(1000 + Math.random() * 9000));
        String deliveryId = uniqueId + timeString + randomLetter;
        tRkWareNotice.setDeliveryId(deliveryId);
        tRkWareNoticeMapper.insertTRkWareNotice(tRkWareNotice);

        // 入库通知单明细
        List<TRkWareNoticeTab> updateNoticeTabs = new ArrayList<TRkWareNoticeTab>();

        // 遍历提交的物料数据明细
        int ziNeedNo = 0;
        for (TckOrderdetailBak tBak : orders.getTckOrderdetailBakList()) {

            if (tBak.getTrNum().compareTo(tBak.getRecNumNow()) < 0) {
                result.put("error", "退库数量不能大于出库数量，物料【" + tBak.getGoodsName() + "】");
                return result;
            }

            TRkWareNoticeTab tabNew = new TRkWareNoticeTab();

            // 物料编码
            tabNew.setGoodsId(tBak.getGoodsId());
            tabNew.setGoodsName(tBak.getGoodsName());
            tabNew.setSpecification(tBak.getSpecification());
            tabNew.setUnit(tBak.getUnit());
            tabNew.setRecoil(tBak.getRecoil());
            tabNew.setArraMount(tBak.getRecNumNow());
            tabNew.setStorageId(tBak.getStorageId());
            tabNew.setStorageShortName(tBak.getStorageShortName());
            tabNew.setStorageLocation(tBak.getLocationId());
            tabNew.setGoodsTypeId(tBak.getGoodsTypeId());
            tabNew.setApplicant(orders.getApplicant());
            tabNew.setBarcode(tBak.getBarcode());

            // 子需求编号
            tabNew.setSalesOrderNumber(String.valueOf(ziNeedNo));
            ziNeedNo++;
            // 在途
            tabNew.setReceivingStatus("0");
            // 冻结
            tabNew.setInStatus("0");
            tabNew.setRecNumNow(tabNew.getRecNum());
            tabNew.setUpdateBy(orders.getRecordPerson());
            tabNew.setUpdateTime(new Date());
            tabNew.setCreateBy(orders.getRecordPerson());
            tabNew.setCreateTime(new Date());
            tabNew.setNoticeId(tRkWareNotice.getId());
            tabNew.setId(OrderCodeFactory.getOrderCode("TRKTAB", ""));
            tabNew.setLevelType("1");
            updateNoticeTabs.add(tabNew);
        }

        if (updateNoticeTabs.size() > 0) {
            // 入库通知单明细批量插入
            tRkWareNoticeMapper.batchTRkWareNoticeTab(updateNoticeTabs);
        }

        result.put("deliveryId", deliveryId);
        result.put("noticeId", tRkWareNotice.getNoticeId());
        result.put("id", tRkWareNotice.getId());
        result.put("success", "车间退货入库");
        result.put("error", "");

        return result;
    }
}
