package com.huaheng.api.mes.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaheng.api.mes.dto.Detail;
import com.huaheng.api.mes.dto.GetOrderHistoryDTO;
import com.huaheng.api.mes.dto.Header;
import com.huaheng.api.mes.dto.ReceiptDTO;
import com.huaheng.api.mes.utils.CallaMOM;
import com.huaheng.api.mes.utils.SqlServer;
import com.huaheng.api.mes.vo.InventoryVO;
import com.huaheng.api.mes.vo.InventoryTransactionVO;
import com.huaheng.common.constant.QuantityConstant;
import com.huaheng.common.utils.StringUtils;
import com.huaheng.common.utils.reflect.ReflectUtils;
import com.huaheng.framework.aspectj.lang.annotation.ApiLogger;
import com.huaheng.framework.aspectj.lang.annotation.Log;
import com.huaheng.framework.aspectj.lang.constant.BusinessType;
import com.huaheng.framework.web.controller.BaseController;
import com.huaheng.framework.web.domain.AjaxResult;
import com.huaheng.framework.web.domain.RetCode;
import com.huaheng.pc.config.material.domain.Material;
import com.huaheng.pc.config.material.service.MaterialService;
import com.huaheng.pc.inventory.inventoryDetail.domain.InventoryDetail;
import com.huaheng.pc.inventory.inventoryDetail.service.InventoryDetailService;
import com.huaheng.pc.inventory.inventoryTransaction.domain.InventoryTransaction;
import com.huaheng.pc.inventory.inventoryTransaction.service.InventoryTransactionService;
import com.huaheng.pc.momLog.domain.MomLog;
import com.huaheng.pc.momLog.mapper.MomLogMapper;
import com.huaheng.pc.momLog.service.IMomLogService;
import com.huaheng.pc.receipt.receiptDetail.domain.ReceiptDetail;
import com.huaheng.pc.receipt.receiptDetail.service.ReceiptDetailService;
import com.huaheng.pc.receipt.receiptHeader.domain.ReceiptHeader;
import com.huaheng.pc.receipt.receiptHeader.service.ReceiptHeaderService;
import com.huaheng.pc.shipment.shipmentDetail.domain.ShipmentDetail;
import com.huaheng.pc.shipment.shipmentDetail.service.ShipmentDetailService;
import com.huaheng.pc.shipment.shipmentHeader.domain.ShipmentHeader;
import com.huaheng.pc.shipment.shipmentHeader.service.ShipmentHeaderService;
import com.huaheng.pc.task.taskDetail.domain.TaskDetail;
import com.huaheng.pc.task.taskDetail.service.TaskDetailService;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


@RestController
@RequestMapping("/API/WMS/v2")
public class MesReceiptController extends BaseController {

    @Resource
    private ReceiptHeaderService receiptHeaderService;

    @Resource
    private ReceiptDetailService receiptDetailService;

    @Resource
    private ShipmentHeaderService shipmentHeaderService;

    @Resource
    private ShipmentDetailService shipmentDetailService;

    @Resource
    private InventoryDetailService inventoryDetailService;

    @Resource
    private TaskDetailService taskDetailService;

    @Resource
    private InventoryTransactionService inventoryTransactionService;

    @Resource
    private MaterialService materialService;

    @Resource
    private IMomLogService momLogService;

    private static Logger logger = LoggerFactory.getLogger(ReflectUtils.class);

    @PostMapping("/receipt")
    @ApiLogger(apiName = "添加入库单及其明细", from="ROBOT")
    @ApiOperation("添加入库单及其明细")
    public AjaxResult receipt(@RequestBody ReceiptDTO receiptDTO) {
        Header header = receiptDTO.getShipmentHeader();
        List<Detail> details = receiptDTO.getShipemtnDetails();

        AjaxResult ajaxResult = new AjaxResult();
        boolean isNull = enterIsNull(ajaxResult, header, details);
        if (isNull){
            return ajaxResult;
        }

        ReceiptHeader receiptHeader = new ReceiptHeader();
        if(StringUtils.isNotEmpty(header.getMOMID()))
            receiptHeader.setMOMID(header.getMOMID());
        receiptHeader.setCode(header.getReferCode());
        // 入库类型--需要保持一致
        receiptHeader.setReceiptType(header.getRefeCodeType());
        // receiptHeader.setReceiptType("CS");
        receiptHeader.setTotalQty(header.getTotalQty());
        receiptHeader.setTotalLines(details.size());
        // TAID MOM目标类型 // FAID MOM来源类型
        receiptHeader.setTAID(header.getTAID());
        receiptHeader.setFAID(header.getFAID());
        receiptHeader.setProductionWorker(header.getProductionWorker());
        receiptHeader.setWarehouse(header.getWarehouse());
        receiptHeader.setFirstStatus(QuantityConstant.RECEIPT_HEADER_BUILD);
        receiptHeader.setLastStatus(QuantityConstant.RECEIPT_HEADER_BUILD);
        receiptHeader.setWarehouseCode("CS0001");
        receiptHeader.setCompanyCode("BHF");
        receiptHeader.setCreatedBy("MOM");

        receiptHeaderService.save(receiptHeader);

        List<ReceiptDetail> shipemtnDetailList = new ArrayList<>();
        for(Detail detail : details) {
            ReceiptDetail receiptDetail = new ReceiptDetail();
            // 查询入库单据表头
            LambdaQueryWrapper<Material> materialQueryWrapper = Wrappers.lambdaQuery();
            materialQueryWrapper.eq(Material::getCode, detail.getMaterialCode());
            Material material = materialService.getOne(materialQueryWrapper);
            if(StringUtils.isNotEmpty(detail.getDetailID()))
                receiptDetail.setMOMID(detail.getDetailID());
            receiptDetail.setIsVirtualBom(detail.getIsVirtual());
            receiptDetail.setMaterialCode(detail.getMaterialCode());
            receiptDetail.setMaterialName(detail.getMaterialName());
            receiptDetail.setMaterialSpec(material.getSpec());
            receiptDetail.setQty(detail.getQty());
            receiptDetail.setIsUrgent(detail.getIsUrgent());
            receiptDetail.setNoticeNo(detail.getNoticeNo());
            receiptDetail.setSNNO(detail.getSNNO());
            receiptDetail.setReceiptBarcode(detail.getReceiptBarcode());
            receiptDetail.setReceiptId(receiptHeader.getId());
            receiptDetail.setReceiptCode(receiptHeader.getCode());
            receiptDetail.setStatusFlowCode("2");
            receiptDetail.setWarehouseCode("CS0001");
            receiptDetail.setCompanyCode("BHF");
            receiptDetail.setInventorySts("good");
            receiptDetail.setCreatedBy("MOM");
            shipemtnDetailList.add(receiptDetail);
        }
        receiptDetailService.saveBatch(shipemtnDetailList);

        return AjaxResult.success(receiptDTO);
    }


    /**
     * 添加出库单及其明细
     * @param receiptDTO
     * @return
     */
    @PostMapping("/shipment")
    @ApiLogger(apiName = "添加出库单及其明细", from="ROBOT")
    @ApiOperation("添加出库单及其明细")
    public AjaxResult shipment(@RequestBody ReceiptDTO receiptDTO) {
        Header header = receiptDTO.getShipmentHeader();
        List<Detail> details = receiptDTO.getShipemtnDetails();

        AjaxResult ajaxResult = new AjaxResult();
        boolean inNull = enterIsNull(ajaxResult, header, details);
        if (inNull)  return ajaxResult;

        ShipmentHeader shipmentHeader = new ShipmentHeader();
        // shipmentHeader.setId(header.getId());
        if(StringUtils.isNotEmpty(header.getMOMID()))
            shipmentHeader.setMOMID(header.getMOMID());
        shipmentHeader.setCode(header.getReferCode());
        // 出库类型--需要保持一致
        shipmentHeader.setShipmentType(header.getRefeCodeType());
        shipmentHeader.setTotalQty(header.getTotalQty());
        // TAID MOM目标类型 // FAID MOM来源类型
        shipmentHeader.setTAID(header.getTAID());
        shipmentHeader.setFAID(header.getFAID());
        shipmentHeader.setNoticeNo(details.get(0).getNoticeNo());
        shipmentHeader.setWorkshop(header.getWorkshop());
        shipmentHeader.setWarehouse(header.getWarehouse());
        shipmentHeader.setSuperiorCode(header.getSuperiorCode());
        shipmentHeader.setSuperiorName(header.getSuperiorName());
        shipmentHeader.setRequestedDeliveryDate(header.getRequestedDeliveryDate());
        shipmentHeader.setFirstStatus(QuantityConstant.SHIPMENT_CONTAINER_BUILD);
        shipmentHeader.setLastStatus(QuantityConstant.SHIPMENT_CONTAINER_BUILD);
        shipmentHeader.setTotalLines(details.size());
        shipmentHeader.setWarehouseCode("CS0001");
        shipmentHeader.setCompanyCode("BHF");
        shipmentHeader.setCreatedBy("MOM");
        shipmentHeaderService.save(shipmentHeader);

        List<ShipmentDetail> shipmentDetailList = new ArrayList<>();
        details.forEach(detail->{
            ShipmentDetail shipmentDetail = new ShipmentDetail();
            if(StringUtils.isNotEmpty(detail.getDetailID()))
                shipmentDetail.setMOMID(detail.getDetailID());
            shipmentDetail.setMaterialCode(detail.getMaterialCode());
            shipmentDetail.setMaterialName(detail.getMaterialName());
            shipmentDetail.setPort(detail.getEndSation());
            shipmentDetail.setQty(detail.getQty());
            shipmentDetail.setIsUrgent(detail.getIsUrgent());
            shipmentDetail.setNoticeNo(detail.getNoticeNo());
            shipmentDetail.setSNNO(detail.getSNNO());

            shipmentDetail.setShipmentId(shipmentHeader.getId());
            shipmentDetail.setShipmentCode(shipmentHeader.getCode());
            shipmentDetail.setCompanyCode("BHF");
            shipmentDetail.setWarehouseCode("CS0001");
            shipmentDetail.setInventorySts("good");
            shipmentDetail.setStatus(QuantityConstant.TASK_STATUS_BUILD);
            shipmentDetail.setCreatedBy("MOM");
            shipmentDetailList.add(shipmentDetail);
        });
        shipmentDetailService.saveBatch(shipmentDetailList);

        return AjaxResult.success(receiptDTO);
    }

    private JSONObject getJsonObject(Header header, List<Detail> details) {
        JSONObject data = new JSONObject();
        JSONObject Rd_In_M = new JSONObject();
        Rd_In_M.put("MGPK", header.getId());
        Rd_In_M.put("cCode", header.getReferCode());
        JSONArray Rd_In_S = new JSONArray();
        details.forEach(detail -> {
            JSONObject json = new JSONObject();
            json.put("MGPK", header.getId());
            json.put("SGPK", detail.getId());
            json.put("cInvCode", detail.getMaterialCode());
            Rd_In_S.add(json);
        });
        data.put("Requester", "WMS");
        data.put("Rd_In_M", Rd_In_M);
        data.put("Rd_In_S", Rd_In_S);
        return data;
    }


    /**
     * 入库单参数_判空处理
     * @param ajaxResult
     * @param shipmentHeader
     * @param shipemtnDetails
     */
    private boolean enterIsNull(AjaxResult ajaxResult, Header shipmentHeader, List<Detail> shipemtnDetails){

        if (isNullData(ajaxResult, shipmentHeader, shipemtnDetails)) return true;

        if (StringUtils.isEmpty(shipmentHeader.getRefeCodeType())) {
            ajaxResult.setCode(RetCode.FAIL).setMsg("单据类型不能为空!!!");
            return true;
        } else if (StringUtils.isEmpty(shipmentHeader.getReferCode())) {
            ajaxResult.setCode(RetCode.FAIL).setMsg("单据单号不能为空!!!");
            return true;
        }else if (shipmentHeader.getTotalQty() == null || shipmentHeader.getTotalQty().intValue() <= 0) {
            ajaxResult.setCode(RetCode.FAIL).setMsg("数量不能为空!!!");
        }

        shipemtnDetails.forEach(shipemtnDetail->{
            if (StringUtils.isEmpty(shipemtnDetail.getMaterialCode())) {
                ajaxResult.setCode(RetCode.FAIL).setMsg("物料编码不能为空!!!");
            } else if (shipemtnDetail.getTotalQty() == null || shipemtnDetail.getQty().intValue() <= 0) {
                ajaxResult.setCode(RetCode.FAIL).setMsg("数量不能为空!!!");
            }
        });
        return StringUtils.isNotEmpty(ajaxResult.getMsg());
    }

    /**
     * 出库单参数_判空处理
     * @param ajaxResult
     * @param shipmentHeader
     * @param shipemtnDetails
     */
    private boolean outIsNull (AjaxResult ajaxResult, Header shipmentHeader, List<Detail> shipemtnDetails){
        if (isNullData(ajaxResult, shipmentHeader, shipemtnDetails)) return true;

        if (StringUtils.isEmpty(shipmentHeader.getReferCode())) {
            ajaxResult.setCode(RetCode.FAIL).setMsg("单据单号不能为空!!!");
            return true;
        }

        shipemtnDetails.forEach(shipemtnDetail->{
            if (StringUtils.isEmpty(shipemtnDetail.getMaterialCode())) {
                ajaxResult.setCode(RetCode.FAIL).setMsg("物料编码不能为空!!!");
            }
        });
        return StringUtils.isNotEmpty(ajaxResult.getMsg());
    }

    /**
     * 判空处理
     */
    private boolean isNullData(AjaxResult ajaxResult, Header shipmentHeader, List<Detail> shipemtnDetails) {
        if (shipmentHeader == null) {
            ajaxResult.setCode(RetCode.FAIL).setMsg("出库单头表不能为空!!!");
            return true;
        } else if (shipemtnDetails == null || shipemtnDetails.size() < 1) {
            ajaxResult.setCode(RetCode.FAIL).setMsg("出库单明细表集不能为空!!!");
            return true;
        }
        return false;
    }

    /**
     * 入库单单据取消
     */
    @PostMapping("/cancelEnterWarehouse")
    @ApiOperation("入库单单据取消")
    public AjaxResult cancelEnterWarehouse(@RequestBody ReceiptDTO receiptDTO) {
        Header header = receiptDTO.getShipmentHeader();
        List<Detail> details = receiptDTO.getShipemtnDetails();

        if (StringUtils.isEmpty(header.getReferCode())) return AjaxResult.error().setMsg("单据单号不能为空!!!");
        for (Detail detailIsNull:details){
            if(StringUtils.isEmpty(detailIsNull.getDetailID())){
                return AjaxResult.error().setMsg("单据明细ID不能为空!!!");
            }
        }

        // 查询入库单据表头
        LambdaQueryWrapper<ReceiptHeader> receiptHeaderWrapper = Wrappers.lambdaQuery();
        receiptHeaderWrapper.eq(ReceiptHeader::getId, header.getId());
        ReceiptHeader receiptHeader = receiptHeaderService.getById(receiptHeaderWrapper);
        if (receiptHeader == null)
            return AjaxResult.error().setMsg("没有找到对应单据!!!");
        // 查询入库单据明细
        LambdaQueryWrapper<ReceiptDetail> receiptDetailWrapper = Wrappers.lambdaQuery();
        receiptDetailWrapper.eq(ReceiptDetail::getReceiptId, receiptHeader.getId());

        List<ReceiptDetail> receiptDetailList = receiptDetailService.list(receiptDetailWrapper);
        if (receiptDetailList == null)
            return AjaxResult.error().setMsg("没有找到对应单据明细!!!");
        // 获取删除明细
        List<ReceiptDetail> removeReceiptDetails = new ArrayList<>();
        receiptDetailList.forEach(receiptDetail-> details.forEach(detail->{
            if (detail.getDetailID().equals(receiptDetail.getMOMID())){
                removeReceiptDetails.add(receiptDetail);
            }
        }));
        ArrayList<Integer> ids = new ArrayList<>();
        if (removeReceiptDetails.size() > 0){
            removeReceiptDetails.forEach(receiptDetail->{
                ids.add(receiptDetail.getId());
            });
        }
        if (ids.size() < 1 || removeReceiptDetails.size() < 1){
            return AjaxResult.error().setMsg("没有匹配到对应要取消的入库单单据明细!!!");
        }
        receiptDetailService.removeByIds(ids);

        // 出库单明细数量和要删除的明细数量一致,则删除主表
        boolean isRemove = removeReceiptDetails.size() == receiptDetailList.size();
        if (isRemove){
            shipmentHeaderService.removeById(receiptHeader);
        }
        return new AjaxResult<T>().setCode(RetCode.SUCCESS).setMsg("取消成功");
    }


    /**
     * 出库单单据取消
     */
    @PostMapping("/cancelOutWarehouse")
    @ApiOperation("出库单单据取消")
    public AjaxResult cancelOutWarehouse(@RequestBody ReceiptDTO receiptDTO) {
        Header header = receiptDTO.getShipmentHeader();
        List<Detail> details = receiptDTO.getShipemtnDetails();

        AjaxResult ajaxResult = isNull(header, details);
        if (StringUtils.isNotEmpty(ajaxResult.getMsg())) return ajaxResult;

        // 查询出库单据表头
        LambdaQueryWrapper<ShipmentHeader> shipmentHeaderWrapper = Wrappers.lambdaQuery();
        shipmentHeaderWrapper.eq(ShipmentHeader::getCode, header.getSuperiorCode());
        ShipmentHeader shipmentHeader = shipmentHeaderService.getOne(shipmentHeaderWrapper);
        if (shipmentHeader == null)
            return ajaxResult.setCode(RetCode.FAIL).setMsg("没有找到对应单据!!!");
        // 查询出库单据明细
        LambdaQueryWrapper<ShipmentDetail> shipmentDetailWrapper = Wrappers.lambdaQuery();
        shipmentDetailWrapper.eq(ShipmentDetail::getShipmentId, header.getId());
        List<ShipmentDetail> shipmentDetailList = shipmentDetailService.list(shipmentDetailWrapper);
        if (shipmentDetailList == null)
            return ajaxResult.setCode(RetCode.FAIL).setMsg("没有找到对应单据明细!!!");
        // 获取删除明细
        List<ShipmentDetail> removeShipmentDetails = new ArrayList<>();
        shipmentDetailList.forEach(shipmentDetai-> details.forEach(detail->{
            if (detail.getMaterialCode().equals(shipmentDetai.getMaterialCode()) && detail.getTotalQty().intValue() == (shipmentDetai.getTaskQty().intValue())){
                removeShipmentDetails.add(shipmentDetai);
            }
        }));
        if (removeShipmentDetails.size() > 0){
            ArrayList<Integer> ids = new ArrayList<>();
            removeShipmentDetails.forEach(shipmentDetail-> ids.add(shipmentDetail.getId()));
            shipmentDetailService.removeByIds(ids);
        }else {
            return ajaxResult.setCode(RetCode.FAIL).setMsg("没有匹配到对应要取消的出库单单据明细!!!");
        }
        // 出库单明细数量和要删除的明细数量一致,则删除主表
        boolean isRemove = removeShipmentDetails.size() == shipmentDetailList.size();
        if (isRemove){
            shipmentHeaderService.removeById(shipmentHeader);
        }
        return new AjaxResult<T>().setCode(RetCode.SUCCESS).setMsg("取消成功");

    }

    private AjaxResult isNull(Header header, List<Detail> details) {
        AjaxResult ajaxResult = new AjaxResult();
        boolean isNull = outIsNull(ajaxResult, header, details);
        details.forEach(detail -> {
            if (detail.getTotalQty() == null || detail.getTotalQty().intValue() <= 0) {
                ajaxResult.setCode(RetCode.FAIL).setMsg("总数量不能为空!!!");
            }
        });
        if (isNull || StringUtils.isNotEmpty(ajaxResult.getMsg())) return ajaxResult;
        return ajaxResult;
    }

    /**
     * 查询库存
     */
    @PostMapping("/searchInventory")
    @ApiLogger(apiName = "查询库存", from="ROBOT")
    @ApiOperation("查询库存")
    public AjaxResult searchInventory(@RequestBody Detail detailed) {

        String materialName =  detailed.getMaterialName();
        String materialCode = detailed.getMaterialCode();
        String containerCode = detailed.getContainerCode();

        LambdaQueryWrapper<InventoryDetail> lambdaQueryWrapper = Wrappers.lambdaQuery();
        // 物料编码
        if (StringUtils.isNotEmpty(materialName)){
            lambdaQueryWrapper.eq(InventoryDetail::getMaterialName, materialName);
        }
        // 物料名称
        if (StringUtils.isNotEmpty(materialCode)){
            lambdaQueryWrapper.eq(InventoryDetail::getMaterialCode, materialCode);
        }
        // 托盘号
        if (StringUtils.isNotEmpty(containerCode)){
            lambdaQueryWrapper.eq(InventoryDetail::getContainerCode, containerCode);
        }

        if (StringUtils.isEmpty(materialName) && StringUtils.isEmpty(containerCode) && StringUtils.isEmpty(containerCode)){
            lambdaQueryWrapper.gt(InventoryDetail::getQty, 0);
        }
        List<InventoryDetail> detailList = inventoryDetailService.list(lambdaQueryWrapper);

        List<InventoryVO> inventoryVOList = new ArrayList<>();
        detailList.forEach(detail->{
            InventoryVO inventoryVO = new InventoryVO();
            BeanUtils.copyProperties(detail,inventoryVO);
            inventoryVO.setWarehouse("035");
            inventoryVOList.add(inventoryVO);
        });

        return AjaxResult.success(inventoryVOList);

    }

    /**
     * 获取出入库单明细记录
     * @return AjaxResult
     */
    @PostMapping("/getShipmentDetail")
    @ApiLogger(apiName = "获取出入库单明细记录", from="ROBOT")
    @ApiOperation("获取出入库单明细记录")
    public AjaxResult getShipmentDetail(@RequestBody GetOrderHistoryDTO getOrderHistoryDTO) {

        if(StringUtils.isEmpty(getOrderHistoryDTO.getEndTime()) || StringUtils.isEmpty(getOrderHistoryDTO.getStartTime())){
            return AjaxResult.error("开始时间和结束时间不能为空!!!");
        }
        LambdaQueryWrapper<InventoryTransaction> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper
                .ge(InventoryTransaction::getCreated, getOrderHistoryDTO.getStartTime())
                .le(InventoryTransaction::getCreated, getOrderHistoryDTO.getEndTime());
        List<InventoryTransaction> list = inventoryTransactionService.list(lambdaQueryWrapper);
        List<InventoryTransactionVO> inventoryTransactionVOList = new ArrayList<>();
        list.forEach(inventoryTransaction -> {
            InventoryTransactionVO inventoryTransactionVO = new InventoryTransactionVO();
            BeanUtils.copyProperties(inventoryTransaction, inventoryTransactionVO);
            inventoryTransactionVOList.add(inventoryTransactionVO);
        });
        return AjaxResult.success(inventoryTransactionVOList);
    }

    /**
     * 获取sqlServer数据库中物料信息, 同步到本地数据库中
     */
    @PostMapping("/getMaterial")
    @ApiOperation("获取外部物料信息")
    public List<Material> getMaterial(){
        List<Material> materialList = new ArrayList<>();
        try {

            // String sql = "SELECT * FROM [dbo].[sys_user] WHERE createTime > (select DATEADD(HOUR,-3,getdate())) AND createTime <= (select GETDATE())";
            // String sql = "SELECT * FROM [dbo].[base_material]  WHERE MaterialName = 'SMLS Pipe'";
            // 获取新增一天以内和修改两个小时以内的物料数据
            String sql = "select a.cInvCode, a.cInvName, b.cidefine6, b.cidefine7, c.cComUnitName from [dbo].[Inventory] a left join [dbo].[Inventory_extradefine] b on a.cInvCode = b.cInvCode LEFT JOIN [dbo].[ComputationUnit] c ON a.cComUnitCode = c.cComunitCode WHERE (datediff(day,a.dSDate,getdate())=0 OR a.dModifyDate >=  DATEADD(HOUR, -4, GETDATE()))  and  a.cDefWareHouse in ('035','003')";
            ResultSet resultSet = SqlServer.find(sql);
            if (resultSet == null){
                return materialList;
            }
            while(resultSet.next()){
                // 字段要与海王表一致
                String code = resultSet.getString("cInvCode");
                String name = resultSet.getString("cInvName");
                String unit = resultSet.getString("cComUnitName");
                String spec = resultSet.getString("cidefine6");
                String high = resultSet.getString("cidefine7");
                int isHigh = "高托".equals(high) ? 1 : 0;

                Material material = new Material();
                material.setCode(code);
                material.setName(name);
                material.setUnit(unit);
                material.setSpec(spec);
                material.setIsHigh(isHigh);
                material.setWarehouseCode("CS0001");
                material.setCompanyCode("BHF");

                materialList.add(material);
            }
            // materialService.saveBatch(materialList);
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
        logger.debug("******************************同步海王物料档案" + materialList.size() + "条数据!!!");
        return materialList;
    }

    /** 当前时间向推几小时 */
    public String dateRoll(int ihour) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取当前时间
        LocalDateTime date = LocalDateTime.now();
        // 获取当前时间的前几小时时间
        LocalDateTime localDateTime = date.minusHours(ihour);

        return dateTimeFormatter.format(localDateTime);
    }

    /**
     * 查询站台任务明细列表
     */
    @ApiLogger(apiName = "查询站台任务明细列表", from="ROBOT")
    @PostMapping("/kanbanInfo")
    @CrossOrigin
    public AjaxResult kanbanInfo(@RequestBody TaskDetail taskDetail){
        String fromLocation = taskDetail.getFromLocation();
        if (StringUtils.isEmpty(fromLocation))
            return AjaxResult.error("站台不能为空!!!");
        LambdaQueryWrapper<TaskDetail> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(TaskDetail::getFromLocation, fromLocation)
                .lt(TaskDetail::getStatus,"100");
        List<TaskDetail> taskDetailList = taskDetailService.list(wrapper);
        return AjaxResult.success(taskDetailList);
    }

    /**
     * post调用E_Rd_In(MOM)入库成功接口
     */
    @ApiLogger(apiName = "post调用E_Rd_In(MOM)入库接口", from="ROBOT")
    @PostMapping("/postE_Rd_In")
    public Boolean postE_Rd_In(@RequestBody ReceiptDetail receiptDetail){
        // ReceiptHeader receiptHeader = receiptHeaderService.getById(receiptDetail.getId()); //59
        // 查询入库单据表头
        ReceiptHeader receiptHeader = receiptHeaderService.getById(receiptDetail.getReceiptId()); //59
        JSONObject Rd_In_M = new JSONObject();
        Rd_In_M.put("mno", receiptHeader.getCode());
        Rd_In_M.put("MGPK", receiptHeader.getMOMID());
        Rd_In_M.put("cBusType", receiptHeader.getReceiptType());
        Rd_In_M.put("TAID", receiptHeader.getTAID());
        Rd_In_M.put("FAID", receiptHeader.getFAID());
        Rd_In_M.put("UserNo",  receiptHeader.getLastUpdatedBy());
        Rd_In_M.put("warehouse",  receiptHeader.getWarehouse());

        // 查询入库单据明细
//        LambdaQueryWrapper<ReceiptDetail> receiptDetailWrapper = Wrappers.lambdaQuery();
//        receiptDetailWrapper.eq(ReceiptDetail::getReceiptId, receiptHeader.getId());
//        List<ReceiptDetail> receiptDetailList = receiptDetailService.list(receiptDetailWrapper);
        JSONArray jsonArray = new JSONArray();
            JSONObject Rd_In_S = new JSONObject();
            Rd_In_S.put("MGPK", receiptHeader.getMOMID());
            Rd_In_S.put("SGPK", receiptDetail.getMOMID());
            Rd_In_S.put("SNNO", receiptDetail.getSNNO());
            Rd_In_S.put("cInvCode", receiptDetail.getMaterialCode());
            Rd_In_S.put("Iquantity", receiptDetail.getQty());
            Rd_In_S.put("iFQuantity", receiptDetail.getTaskQty());
            Rd_In_S.put("cwhcode", receiptDetail.getWarehouseCode());
            Rd_In_S.put("MOCode", receiptDetail.getNoticeNo() == null ? null : getGB(receiptDetail.getNoticeNo()));
            Rd_In_S.put("ISUrgent", receiptDetail.getIsUrgent());
            Rd_In_S.put("receiptBarcode", receiptDetail.getReceiptBarcode());
            jsonArray.add(Rd_In_S);
        JSONObject data = new JSONObject();
        data.put("Rd_In_M", Rd_In_M);
        data.put("Rd_In_S", jsonArray);

        String action = "E_Rd_In";
        JSONObject json = new JSONObject();
        json.put("data", data);
        // 保存日志
        MomLog momLog = new MomLog();
        momLog.setType("1"); // (入:1  出:2)
        momLog.setMomData(json.toJSONString());
        momLog.setCreated(new Date());
        momLogService.save(momLog);

        return postMOM(action, json);
    }

    /**
     * post调用E_Rd_In(MOM)出库成功接口
     */
    @ApiLogger(apiName = "post调用E_Rd_Out(MOM)出库接口", from="ROBOT")
    @PostMapping("/postE_Rd_Out")
    public Boolean postE_Rd_Out(@RequestBody ShipmentHeader shipmentHeader){
        // ShipmentHeader shipmentHeader = shipmentHeaderService.getById(shipmentHeaderID.getId());
        JSONArray dataArray = new JSONArray();
        // 如果订单为合并类型
        if ("merge".equals(shipmentHeader.getShipmentType())){
            // 查询所有子表
            LambdaQueryWrapper<ShipmentDetail> shipmentDetailWrapper = Wrappers.lambdaQuery();
            shipmentDetailWrapper.eq(ShipmentDetail::getShipmentId, shipmentHeader.getId());
            List<ShipmentDetail> shipmentDetailList = shipmentDetailService.list(shipmentDetailWrapper);
            // 查询所有合并前的头表
            String ids = shipmentHeader.getRecordID();
            String [] headerIdArr = ids.split(",");
            LambdaQueryWrapper<ShipmentHeader> headerWrapper = Wrappers.lambdaQuery();
            headerWrapper.in(ShipmentHeader::getId, headerIdArr);
            List<ShipmentHeader> shipmentHeaderList = shipmentHeaderService.list(headerWrapper);
            // 根据合并前的头表id分组
            Map<Integer,List<ShipmentDetail>> map = new HashMap<>();
            for (ShipmentDetail detail : shipmentDetailList){
                    Integer key = detail.getRecordID();
                    if(map.containsKey(key)) {
                        map.get(key).add(detail);
                    }else {
                        List<ShipmentDetail> list = new ArrayList<>();
                        list.add(detail);
                        map.put(key, list);
                    }
            }

            for (Integer key : map.keySet()) {
                JSONObject data = new JSONObject();
                // 合并前的头表
                ShipmentHeader header = new ShipmentHeader();
                // 合并前头表对应的子表
                List<ShipmentDetail> detailList = new ArrayList<>();
                for(ShipmentHeader SH : shipmentHeaderList){
                    if (key.equals(SH.getId())){
                        header = SH;
                        detailList = map.get(key);
                    }
                }
                // 查询出库单据表头
                JSONObject Rd_Out_M = getRd_Out_M(header);
                JSONArray jsonArray = getRd_Out_S(header, detailList);
                data.put("Rd_Out_M", Rd_Out_M);
                data.put("Rd_Out_S", jsonArray);
                dataArray.add(data);
            }
        }else {
            // 查询出库单据表头
            JSONObject Rd_Out_M = getRd_Out_M(shipmentHeader);
            // 查询出库单据明细
            JSONArray jsonArray = getJsonArray(shipmentHeader);
            JSONObject data = new JSONObject();
            data.put("Rd_Out_M", Rd_Out_M);
            data.put("Rd_Out_S", jsonArray);
            dataArray.add(data);
        }

        String action = "E_Rd_Out";
        JSONObject json = new JSONObject();
        json.put("data", dataArray);

        MomLog momLog = new MomLog();
        momLog.setType("2"); // (入:1  出:2)
        momLog.setMomData(json.toJSONString());
        momLog.setCreated(new Date());
        momLogService.save(momLog);

        return postMOM(action, json);
    }

    private JSONArray getJsonArray(ShipmentHeader shipmentHeader) {
        LambdaQueryWrapper<ShipmentDetail> shipmentDetailWrapper = Wrappers.lambdaQuery();
        shipmentDetailWrapper.eq(ShipmentDetail::getShipmentId, shipmentHeader.getId());
        List<ShipmentDetail> shipmentDetailList = shipmentDetailService.list(shipmentDetailWrapper);
        return getRd_Out_S(shipmentHeader,shipmentDetailList);
    }

    public JSONArray getRd_Out_S(ShipmentHeader shipmentHeader, List<ShipmentDetail> shipmentDetailList) {
        JSONArray jsonArray = new JSONArray();
        shipmentDetailList.forEach(shipmentDetail->{
            JSONObject Rd_Out_S = new JSONObject();
            Rd_Out_S.put("MGPK", shipmentHeader.getMOMID());
            Rd_Out_S.put("SGPK",  shipmentDetail.getMOMID());
            Rd_Out_S.put("SNNO",  shipmentDetail.getSNNO());
            Rd_Out_S.put("cInvCode",  shipmentDetail.getMaterialCode());
            Rd_Out_S.put("Iquantity",  shipmentDetail.getQty());
            Rd_Out_S.put("iFQuantity",  shipmentDetail.getTaskQty());
            Rd_Out_S.put("cwhcode",  shipmentDetail.getWarehouseCode());
            Rd_Out_S.put("MOCode",  shipmentDetail.getNoticeNo() == null ? null : getGB(shipmentDetail.getNoticeNo()));
            Rd_Out_S.put("ISUrgent",  shipmentDetail.getIsUrgent());
            Rd_Out_S.put("updatedBy",  shipmentDetail.getLastUpdatedBy());
            jsonArray.add(Rd_Out_S);
        });
        return jsonArray;
    }

    public JSONObject getRd_Out_M(@RequestBody ShipmentHeader shipmentHeader) {
        JSONObject Rd_Out_M = new JSONObject();
        Rd_Out_M.put("mno", shipmentHeader.getCode());
        Rd_Out_M.put("MGPK", shipmentHeader.getMOMID());
        Rd_Out_M.put("cBusType", shipmentHeader.getShipmentType());
        Rd_Out_M.put("TAID", shipmentHeader.getTAID());
        Rd_Out_M.put("FAID", shipmentHeader.getFAID());
        Rd_Out_M.put("UserNo",  shipmentHeader.getLastUpdatedBy());
        Rd_Out_M.put("warehouse",  shipmentHeader.getWarehouse());
        return Rd_Out_M;
    }

    /**  utf-8 转 GB2312 */
    public String getGB(String action){
        byte [] Rd_Out; //中间用ISO-8859-1过渡
        String data = null;
        try {
            Rd_Out = action.getBytes("8859_1");
            data = new String(Rd_Out, "GB2312"); //转换成GB2312字符
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return data;
    }


        /**
         * @param action MOM行为
         * @param JObject 行为参数
         * @return
         */
    public Boolean postMOM(String action, JSONObject JObject){

        return CallaMOM.getMsg(action, JObject);
//        String url = "http://192.168.101.127:31055//Handler/H_DJ2J_10.ashx";
//        String param = "sptype=JSP_W2M&action=" + action + "&onlydata=1&params=" + JObject;;
//        CallaMOM callMOM = new CallaMOM();
//        String data = callMOM.sendPost(url, param);
//        return JSONObject.parseObject(data);
    }


}