package com.sunda.spmsweb.wmscontroller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmscommon.feign.IFeignServiceCommon;
import com.sunda.spmsweb.util.JWTUtil;
import com.sunda.spmswms.entity.*;
import com.sunda.spmswms.mapper.SapBoxNoteDtlMapper;
import com.sunda.spmswms.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @description:
 * @author: Johnny Zhao
 * @time: 2021/6/17 18:38
 */
@RestController
@RequestMapping("/repackage")
@Api(tags = "拆箱接口", description = "拆箱接口")
public class RepackageController {

    @Autowired
    ISapBoxNoteService iSapBoxNoteService;

    @Autowired
    ISapBoxNoteDtlService iSapBoxNoteDtlService;

    @Autowired
    SapBoxNoteDtlMapper sapBoxNoteDtlMapper;

    @Autowired
    IWhsStorageInventoryService iWhsStorageInventoryService;

    @Autowired
    IWhsStorageService iWhsStorageService;

    @Autowired
    IWhsRepackageService iWhsRepackageService;

    @Autowired
    ISapPackageBoxService iSapPackageBoxService;

    @Autowired
    ISapPackageNoteService iSapPackageNoteService;

    @Autowired
    IFeignServiceCommon iFeignServiceCommon;

    @Autowired
    IWhsRepackageNoteService iWhsRepackageNoteService;

    @Autowired
    IWhsInventoryInfoService iWhsInventoryInfoService;

    @Autowired
    ISapDeliveryNoteLogService iSapDeliveryNoteLogService;


    @RequestMapping("/updateBoxNoteDTL")
    @ApiOperation(value="修改箱单详情",notes="修改箱单详情",httpMethod = "POST")
    @Transactional(propagation = Propagation.REQUIRED)
    public ResponseResult updateBoxNoteDTL(@RequestBody JSONObject jsonObject){
        //旧料号
        String str = jsonObject.getString("oldBn");

        //找到旧箱的唛头
        QueryWrapper<SapBoxNote> qwSBN = new QueryWrapper<>();
        SapBoxNote box = iSapBoxNoteService.getOne(qwSBN.eq("BOX_NOTE", str));
        //获得箱的包装单号
        String packageNote = box.getPackageNote();

        //根据包装单号查到包装单详情
        SapPackageNote sapPackageNote = iSapPackageNoteService.getById(packageNote);
        //从前端request里得到新箱号
        String newStr = jsonObject.getString("newBn");

        QueryWrapper<SapBoxNote> qw = new QueryWrapper<>();

        //找到旧箱
//        SapBoxNote box_note = iSapBoxNoteService.getOne(qw.eq("BOX_NOTE", str));

        //修改为新箱内容
        SapBoxNote newBox = new SapBoxNote();
        newBox.setRemarks(box.getRemarks());
        newBox.setBoxNote(newStr);
        newBox.setBoxQtyReceived(box.getBoxQtyReceived());
        newBox.setItemStatus(box.getItemStatus());
        newBox.setArrivalDate(box.getItemStatus());
        newBox.setBoxColor(box.getBoxColor());
        newBox.setBoxGrossWeight(box.getBoxGrossWeight());
        newBox.setBoxHeight(box.getBoxHeight());
        newBox.setBoxLength(box.getBoxLength());
        //     box_note.setBoxNote(newStr);
        //     box_note.setBoxNote(newStr);
        //     iSapBoxNoteService.saveOrUpdate(box_note);
//        iSapBoxNoteService.saveOrUpdate(box_note);

        //放到新储位上
        //String storage = newBoxStorage(str,newStr);




        //旧箱的物料list
        try{
            //从前端获取旧箱内物料详情
            JSONArray jsonArray =jsonObject.getJSONArray("Dtllist");
            List<SapBoxNoteDtl> list = new ArrayList<>();

            for(int i =0;i<jsonArray.size();i++) {
                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                SapBoxNoteDtl sapBoxNoteDtl = jsonObject1.toJavaObject(SapBoxNoteDtl.class);
//                System.out.println(sapBoxNoteDtl);
                String boxNote = sapBoxNoteDtl.getBoxNote();
                Double domesticQtyReceived = sapBoxNoteDtl.getDomesticQtyReceived();
                Integer item = sapBoxNoteDtl.getItem();
                QueryWrapper<SapBoxNoteDtl> qwDtl = new QueryWrapper<>();
                //获得旧箱对应行号内容
                SapBoxNoteDtl oldItem = iSapBoxNoteDtlService.getOne(qwDtl.eq("BOX_NOTE",str).eq("ITEM",item));
                //修改旧箱内容
//                System.out.println("==========================================");
//                System.out.println(oldItem);
//                System.out.println("========================domesticQtyReceived"+domesticQtyReceived);
//                oldItem.setDomesticQtyReceived(domesticQtyReceived);
//                System.out.println("---+++"+oldItem.toString());

//                HashMap<String,Object> map = new HashMap<>();
//                map.put("boxNote",boxNote);
//                map.put("item",item);
//                map.put("domesticQtyReceived",domesticQtyReceived);
//                map.put("newStr",newStr);
//                buffer.add(map);
//                根据箱号,行号,修改数量和备注新箱号
//                iSapBoxNoteDtlService.updateSapBoxNoteDtlBeta(boxNote, item, domesticQtyReceived, newStr);
//箱码存的是前端转的实体,缺包装单号
                SapBoxNoteDtl oldItemClone = new SapBoxNoteDtl();
                oldItemClone.setDomesticQtyReceivable(oldItem.getDomesticQtyReceivable());
                oldItemClone.setDomesticQtyReceived(domesticQtyReceived);
                oldItemClone.setBoxNote(oldItem.getBoxNote());
                oldItemClone.setRemark(oldItem.getRemark());
                oldItemClone.setMaterialNo(oldItem.getMaterialNo());
                oldItemClone.setBasicUnit(oldItem.getBasicUnit());
                oldItemClone.setDeliveryNoteSap(oldItem.getDeliveryNoteSap());
                oldItemClone.setDeliveryNoteSapItem(oldItem.getDeliveryNoteSapItem());
                oldItemClone.setOverseaQtyReceived(oldItem.getOverseaQtyReceived());
                oldItemClone.setDemander(oldItem.getDemander());
                oldItemClone.setDemandNo(oldItem.getDemandNo());
                oldItemClone.setDemandNoItem(oldItem.getDemandNoItem());
                oldItemClone.setGrossWeight(oldItem.getGrossWeight());
                oldItemClone.setItem(oldItem.getItem());
                oldItemClone.setPackageNote(oldItem.getPackageNote());
                oldItemClone.setPurchaseNo(oldItem.getPurchaseNo());
                oldItemClone.setPackagePosnr(oldItem.getPackagePosnr());
                oldItemClone.setQuantity(oldItem.getQuantity());
                oldItemClone.setNetWeight(oldItem.getNetWeight());
                oldItemClone.setSrmContractNo(oldItem.getSrmContractNo());
                //旧箱信息修改完毕
                list.add(oldItemClone);
            }

            System.out.println("listlistlistlist"+list);

            //新箱的物料
            JSONArray newListJsonArray = jsonObject.getJSONArray("newList");
            List<SapBoxNoteDtl> newList = new ArrayList<>();

            for(int i = 0;i<newListJsonArray.size();i++) {
                JSONObject jsonObject2 = newListJsonArray.getJSONObject(i);
//              //前端数据转为行项目实体
                SapBoxNoteDtl sapBoxNoteDtl = jsonObject2.toJavaObject(SapBoxNoteDtl.class);
                System.out.println(sapBoxNoteDtl);
                //实体存到newlist
//                newList.add(sapBoxNoteDtl);
                Double domesticQtyReceived = sapBoxNoteDtl.getDomesticQtyReceived();
                Integer item = sapBoxNoteDtl.getItem();
                //更新行号，如果没有行号，就建新行
                QueryWrapper<SapBoxNoteDtl> newQw = new QueryWrapper<>();
                SapBoxNoteDtl mapOld = iSapBoxNoteDtlService.getOne(newQw.eq("BOX_NOTE",str).eq("ITEM",item));
//                mapOld.setBoxNote(newStr);
//                mapOld.setRemark(str);
//                mapOld.setDomesticQtyReceived(domesticQtyReceived);
//                mapOld.setDomesticQtyReceivable(domesticQtyReceived);

                SapBoxNoteDtl newItem = new SapBoxNoteDtl();
                newItem.setDomesticQtyReceivable(mapOld.getDomesticQtyReceivable());
                newItem.setDomesticQtyReceived(domesticQtyReceived);
                newItem.setBoxNote(mapOld.getBoxNote());
                newItem.setRemark(mapOld.getRemark());
                newItem.setMaterialNo(mapOld.getMaterialNo());
                newItem.setBasicUnit(mapOld.getBasicUnit());
                newItem.setDeliveryNoteSap(mapOld.getDeliveryNoteSap());
                newItem.setDeliveryNoteSapItem(mapOld.getDeliveryNoteSapItem());
                newItem.setOverseaQtyReceived(mapOld.getOverseaQtyReceived());
                newItem.setDemander(mapOld.getDemander());
                newItem.setDemandNo(mapOld.getDemandNo());
                newItem.setDemandNoItem(mapOld.getDemandNoItem());
                newItem.setGrossWeight(mapOld.getGrossWeight());
                newItem.setItem(item);
                newItem.setPackageNote(mapOld.getPackageNote());
                newItem.setPurchaseNo(mapOld.getPurchaseNo());
                newItem.setPackagePosnr(mapOld.getPackagePosnr());
                newItem.setQuantity(mapOld.getQuantity());
                newItem.setNetWeight(mapOld.getNetWeight());
                newItem.setSrmContractNo(mapOld.getSrmContractNo());

//                iSapBoxNoteDtlService.save(mapOld);
                newList.add(newItem);
                //根据前端的行号匹配对应行号,找到对应行
//                SapBoxNoteDtl one = iSapBoxNoteDtlService.getOne(newQw.eq("BOX_NOTE", newStr).eq("ITEM", item));
                //找到对应行不为空
//                if(one!=null){
//                    iSapBoxNoteDtlService.updateSapBoxNoteDtlBeta(newStr, item, domesticQtyReceived, str);
                //为空
//                }else {
//                    sapBoxNoteDtl.setBoxNote(newStr);
//                    sapBoxNoteDtl.setRemark(str);
//                    iSapBoxNoteDtlService.save(sapBoxNoteDtl);
//                }
            }

            List<SapBoxNote> arr = new ArrayList<>();
            arr.add(box);//加入旧箱箱单信息
            arr.add(newBox);//加入新箱信息
            //传入旧箱箱号,父子箱一起,旧箱物料,新箱物料
            JSONObject sapResult = formData(sapPackageNote,arr,list,newList);
            JSONObject message = JSONObject.parseObject(iFeignServiceCommon.sendRestToSapCommon(sapResult));
            if(message.getJSONObject("RESPONSE").getJSONObject("RETURN_DATA").getString("O_TYPE").equals("S")){
                System.out.println("-!-!-!-!-!-!-!");
                //修改旧箱
                //iSapBoxNoteService.saveOrUpdate(box);
                //存入新箱
                iSapBoxNoteService.saveOrUpdate(newBox);

                System.out.println("list22"+list.toString());
//旧箱修改
                for (int i = 0; i <list.size() ; i++) {
                    SapBoxNoteDtl item = list.get(i);
                    System.out.println("itemitemitem"+item.toString());
                    iSapBoxNoteDtlService.updateSapBoxNoteDtlBeta(item.getBoxNote(), item.getItem(), item.getDomesticQtyReceived(), newStr);
                }
//新箱增添
                for (int i= 0; i < newList.size() ; i++) {
                    SapBoxNoteDtl newItem = newList.get(i);
                    System.out.println("00000000000000000000000");
                    iSapBoxNoteDtlService.save(newItem);
                }
//上储位
                String storage = newBoxStorage(str,newStr);
            }
            String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
            iSapDeliveryNoteLogService.insertSapRequestRecord(newStr, userId,"拆箱",message.toJSONString(),sapResult.toJSONString());
            return ResponseResult.success(message.toJSONString()).add("sapResult",sapResult);
        }catch(TooManyResultsException e){
            e.printStackTrace();
            System.out.println(e.getMessage());
            return ResponseResult.error("物料共用序号错误",100);
        } catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
            return ResponseResult.error(e.getMessage(),100);
        }
    }

    private String newBoxStorage(String oldBox, String newBox){
        Date date= new Date();
        if(iWhsStorageInventoryService.getBoxNoteStorage(newBox)==null){
            WhsStorageInventory boxNoteStorage = iWhsStorageInventoryService.getBoxNoteStorage(oldBox);
            String uuid = boxNoteStorage.getUuid();
            WhsStorageInventory whsStorageInventory = new WhsStorageInventory();
            whsStorageInventory.setUuid(uuid);
            //修改储位库存
            whsStorageInventory.setBoxNote(newBox);
            whsStorageInventory.setQuantity(1.0);
            whsStorageInventory.setCreateTime(date);
            iWhsStorageInventoryService.save(whsStorageInventory);
            //修改仓库库存
            WhsInventoryInfo whsInventoryInfo = new WhsInventoryInfo();
            whsInventoryInfo.setBoxNote(newBox);
            whsInventoryInfo.setQuantity(1.0);
            iWhsInventoryInfoService.save(whsInventoryInfo);
            WhsStorage whsStorageByUuid = iWhsStorageService.getWhsStorageByUuid(uuid);
            return whsStorageByUuid.getWhsLocationCode();
        }else{
            WhsStorageInventory whsStorageInventory = iWhsStorageInventoryService.getBoxNoteStorage(newBox);
            String uuid = whsStorageInventory.getUuid();
            WhsStorage whsStorageByUuid = iWhsStorageService.getWhsStorageByUuid(uuid);
            return whsStorageByUuid.getWhsLocationCode();
        }
    }

    @RequestMapping("/getOldAndChildList")
    @ApiOperation(value="获得拆箱父子关系",notes="获得拆箱父子关系",httpMethod = "POST")
    public ResponseResult getRepackage(@RequestBody JSONObject searchCriteria){
//        Map<String, Object> pageMap = iWhsStorageInventoryService.getPageMap(doc);
//        int pageNo =1;
//        int pageSize = 20;
        try {
            int pageNo = (int)searchCriteria.get("pageNo");
            int pageSize = (int)searchCriteria.get("pageSize");;
            List<String> werks=searchCriteria.containsKey("werks")?(List)searchCriteria.getJSONArray("werks"):null;
            List<String> whsLocationCode=searchCriteria.containsKey("whsLocationCode")?(List)searchCriteria.getJSONArray("whsLocationCode"):null;
            List<String> storageArea=searchCriteria.containsKey("storageArea")?(List)searchCriteria.getJSONArray("storageArea"):null;
            List<String> shelfNo=searchCriteria.containsKey("shelfNo")?(List)searchCriteria.getJSONArray("shelfNo"):null;
            List<String> shelfLayer=searchCriteria.containsKey("shelfLayer")?(List)searchCriteria.getJSONArray("shelfLayer"):null;
            List<String> shelfCell=searchCriteria.containsKey("shelfCell")?(List)searchCriteria.getJSONArray("shelfCell"):null;
            List<String> storageNo=searchCriteria.containsKey("storageNo")?(List)searchCriteria.getJSONArray("storageNo"):null;
            List<String> materialNo=searchCriteria.containsKey("materialNo")?(List)searchCriteria.getJSONArray("materialNo"):null;
            List<String> boxNote=searchCriteria.containsKey("boxNote")?(List)searchCriteria.getJSONArray("boxNote"):null;
            String storageCategory=searchCriteria.containsKey("storageCategory")?searchCriteria.getString("storageCategory"):"";
            return ResponseResult.success().add("storageInventory", iWhsStorageInventoryService.getPageMap(werks,whsLocationCode,storageArea,shelfNo,shelfLayer,shelfCell,storageNo,materialNo,storageCategory,boxNote,pageNo, pageSize));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("获取指定的储位库存信息出错");
        }
    }

    @RequestMapping("/buildBill")
    @ApiOperation(value="拆箱任务", notes = "拆箱任务", httpMethod = "POST")
    public ResponseResult repackage(){
        long time = new Date().getTime();
        try{

            WhsRepackage whsRepackage =new WhsRepackage();
            whsRepackage.setBoxNote("1111");
            whsRepackage.setDomesticQtyReceived(100.0);
            whsRepackage.setStatus("0");
            whsRepackage.setMaterialNo("12341516");
            whsRepackage.setRepackageBillNo(Long.toString(time));
            JSONArray jsonArray = new JSONArray();
            jsonArray.set(0,whsRepackage);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("materialList",jsonArray);
//            iWhsRepackageService.updateInfo(jsonObject);
            iWhsRepackageService.updateStatus("1624867902639");
            return ResponseResult.success().add("materialList",jsonArray);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("error");
        }
    }

    //从详情获取去重的表单(不推荐)
//    @RequestMapping("/repackList")
//    @ApiOperation(value="拆箱历史", notes = "拆箱历史", httpMethod = "GET")
//    public ResponseResult getRepackBillList(){
//        List<String> historyList = iWhsRepackageService.getHistoryList();
//        return ResponseResult.success("success").add("list",historyList);
//    }


    @RequestMapping("/getHistory")
    @ApiOperation(value="拆箱历史",notes = "拆箱历史", httpMethod = "GET")
    public ResponseResult getRepackHistory(){
        try{
            List<WhsRepackageNote> list = iWhsRepackageNoteService.list();
            return ResponseResult.success("success").add("list",list);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error(e.getMessage());
        }
    }

    @RequestMapping("/buildNewHistory")
    @ApiOperation(value="建立新箱",notes="建立新箱", httpMethod = "POST")
    public ResponseResult buildRepackHistory(@RequestBody JSONObject doc){
        WhsRepackageNote whsRepackageNote = new WhsRepackageNote();
        String billNo  = doc.getString("billNo");
        whsRepackageNote.setRepackageBillNo(billNo);
        boolean save = iWhsRepackageNoteService.save(whsRepackageNote);
        return ResponseResult.success().add("list",iWhsRepackageNoteService.list());
    }

    public JSONObject formData(SapPackageNote sapPackageNote, List<SapBoxNote> arr, List<SapBoxNoteDtl> oldSapBoxNoteDtl, List<SapBoxNoteDtl> newSapBoxNoteDtl) throws Exception{
        JSONObject doc = new JSONObject();
        JSONObject REQUEST = new JSONObject();
        JSONObject ESB_ATTRS = new JSONObject();
        JSONObject REQUEST_DATA = new JSONObject();

        ESB_ATTRS.put("App_ID", "SPMS");
        ESB_ATTRS.put("Application_ID", "00020000000002");
        ESB_ATTRS.put("Transaction_ID", UUID.randomUUID().toString());

//       从前端读取的箱子内容
//        JSONArray items = oldList.fluentAddAll(newList);

        try{
            JSONArray ithead = new JSONArray();
            for (int i = 0; i <arr.size() ; i++) {
                JSONObject map = new JSONObject();
                SapBoxNote sapBoxNote = arr.get(i);
                map.put("packageNo",StringUtils.isEmpty(sapBoxNote.getPackageNote())?"":sapBoxNote.getPackageNote());
                map.put("packageCode",StringUtils.isEmpty(sapBoxNote.getBoxNote())?"":sapBoxNote.getBoxNote());
                map.put("outerBoxTexture",StringUtils.isEmpty(sapBoxNote.getBoxMaterialName())?"":sapBoxNote.getBoxMaterialName());
//                map.put("totalQty",StringUtils.isEmpty(String.valueOf(sapBoxNote.getTotalQty()))?"":String.valueOf(sapBoxNote.getTotalQty()));
                map.put("totalQty",sapBoxNote.getTotalQty()==null?"":String.valueOf(sapBoxNote.getTotalQty()));
//                map.put("boxVolum",StringUtils.isEmpty(String.valueOf(sapBoxNote.getBoxVolume()))?"":String.valueOf(sapBoxNote.getBoxVolume()));
                map.put("boxVolum",sapBoxNote.getBoxVolume()==null?"":String.valueOf(sapBoxNote.getBoxVolume()));
//                map.put("length",StringUtils.isEmpty(String.valueOf(sapBoxNote.getBoxLength()))?"":String.valueOf(sapBoxNote.getBoxLength()));
                map.put("length",sapBoxNote.getBoxLength()==null?"":String.valueOf(sapBoxNote.getBoxLength()));
//                map.put("width",StringUtils.isEmpty(String.valueOf(sapBoxNote.getBoxWidth()))?"":String.valueOf(sapBoxNote.getBoxWidth()));
                map.put("width",sapBoxNote.getBoxWidth()==null?"":String.valueOf(sapBoxNote.getBoxWidth()));
//                map.put("height",StringUtils.isEmpty(String.valueOf(sapBoxNote.getBoxHeight()))?"":String.valueOf(sapBoxNote.getBoxHeight()));
                map.put("height",sapBoxNote.getBoxHeight()==null?"":String.valueOf(sapBoxNote.getBoxHeight()));
                map.put("color",StringUtils.isEmpty(sapBoxNote.getBoxColor())?"":sapBoxNote.getBoxColor());
//                map.put("boxBrgew",StringUtils.isEmpty(String.valueOf(sapBoxNote.getBoxGrossWeight()))?"":String.valueOf(sapBoxNote.getBoxGrossWeight()));
                map.put("boxBrgew",sapBoxNote.getBoxGrossWeight()==null?"":String.valueOf(sapBoxNote.getBoxGrossWeight()));
                ithead.add(map);
            }

            System.out.println(ithead);
//v1
//        REQUEST_DATA.put("Head", head);

            JSONArray items = new JSONArray();
            items.fluentAddAll(SapBoxNoteConvertToItems(oldSapBoxNoteDtl));
            items.fluentAddAll(SapBoxNoteConvertToItems(newSapBoxNoteDtl));

            JSONObject it = new JSONObject();
            it.put("IT_ITME", items);

//v2
//        it.put("IT_XHEAD",itHead);
            it.put("IT_XHEAD",ithead);
//            HashMap<String,Object> head = new HashMap<>();
            JSONObject head = new JSONObject();
            head.put("packageNo",StringUtils.isEmpty(sapPackageNote.getPackageNote())==true?"":String.valueOf(sapPackageNote.getPackageNote()));
            head.put("srmDn",StringUtils.isEmpty(sapPackageNote.getDeliveryNoteSrm())?"":sapPackageNote.getDeliveryNoteSrm());
            head.put("sapDn",StringUtils.isEmpty(sapPackageNote.getDeliveryNoteSap())?"":sapPackageNote.getDeliveryNoteSap());
            head.put("lifnr",StringUtils.isEmpty(sapPackageNote.getSupplierCode())?"":sapPackageNote.getSupplierCode());
//            head.put("volumT",StringUtils.isEmpty(String.valueOf(sapPackageNote.getTotalVolume()))?"":String.valueOf(sapPackageNote.getTotalVolume()));
            head.put("volumT",sapPackageNote.getTotalVolume()==null?"":String.valueOf(sapPackageNote.getTotalVolume()));
            head.put("brgewT",sapPackageNote.getTotalWeight()==null?"":String.valueOf(sapPackageNote.getTotalWeight()));

            head.put("zxdateF",StringUtils.isEmpty(sapPackageNote.getLoadBeginTime())?"":sapPackageNote.getLoadBeginTime());
            head.put("zxdateT",StringUtils.isEmpty(sapPackageNote.getLoadEndTime())?"":sapPackageNote.getLoadEndTime());
            head.put("ysr",StringUtils.isEmpty(sapPackageNote.getTransporter())?"":sapPackageNote.getTransporter());
            head.put("cyrlxfs",StringUtils.isEmpty(sapPackageNote.getContractorInfo())?"":sapPackageNote.getContractorInfo());
            head.put("shr",StringUtils.isEmpty(sapPackageNote.getReceiver())?"":sapPackageNote.getReceiver());
            head.put("shrlxfs",StringUtils.isEmpty(sapPackageNote.getReceiverInfo())?"":sapPackageNote.getReceiverInfo());
            head.put("shdz",StringUtils.isEmpty(sapPackageNote.getReceivingAddress())?"":sapPackageNote.getReceivingAddress());
            head.put("spmsContractNo",StringUtils.isEmpty(sapPackageNote.getSpmsContractNote())?"":sapPackageNote.getSpmsContractNote());
            head.put("spmsFlg",StringUtils.isEmpty(sapPackageNote.getSpmsMark())?"":sapPackageNote.getSpmsMark());

            REQUEST_DATA.put("Head",head);
            REQUEST_DATA.put("MapItems", it);
//        REQUEST_DATA.put("IT_XHEAD",itHead);
            REQUEST_DATA.put("Operation", "Z_SPMS_SETBOXCODE");
            REQUEST_DATA.put("Type", "SETBOXCODE");

            REQUEST.put("ESB_ATTRS", ESB_ATTRS);
            REQUEST.put("REQUEST_DATA", REQUEST_DATA);

            doc.put("REQUEST", REQUEST);

            System.out.println(doc);

            return doc;
        }catch (Exception e){
            JSONObject eobj = new JSONObject();
            eobj.put("err",e.getMessage());
            throw e;
        }

    }

    public JSONArray SapBoxNoteConvertToItems(List<SapBoxNoteDtl> sapBoxNoteDtlList){
        JSONArray jr = new JSONArray();
        for (int i = 0; i < sapBoxNoteDtlList.size(); i++) {
            JSONObject map = new JSONObject();
            map.put("packageNo",StringUtils.isEmpty(sapBoxNoteDtlList.get(i).getPackageNote())?"":sapBoxNoteDtlList.get(i).getPackageNote());
//            map.put("serial",StringUtils.isEmpty(String.valueOf(sapBoxNoteDtlList.get(i).getItem()))?"":sapBoxNoteDtlList.get(i).getItem());
            map.put("serial",sapBoxNoteDtlList.get(i).getItem()==null?"":String.valueOf(sapBoxNoteDtlList.get(i).getItem()));
            map.put("packageCode",StringUtils.isEmpty(sapBoxNoteDtlList.get(i).getBoxNote())?"":sapBoxNoteDtlList.get(i).getBoxNote());
//            map.put("packagePosnr",StringUtils.isEmpty(String.valueOf(sapBoxNoteDtlList.get(i).getPackagePosnr()))?"":String.valueOf(sapBoxNoteDtlList.get(i).getPackagePosnr()));
            map.put("packagePosnr",sapBoxNoteDtlList.get(i).getPackagePosnr()==null?"":String.valueOf(sapBoxNoteDtlList.get(i).getPackagePosnr()));
            map.put("matnr",StringUtils.isEmpty(sapBoxNoteDtlList.get(i).getMaterialNo())?"":sapBoxNoteDtlList.get(i).getMaterialNo());
            map.put("specs",sapBoxNoteDtlList.get(i).getSpecs());
//            map.put("menge", StringUtils.isEmpty(String.valueOf(sapBoxNoteDtlList.get(i).getDomesticQtyReceived()))==true?"":String.valueOf(sapBoxNoteDtlList.get(i).getDomesticQtyReceived()));
            map.put("menge", sapBoxNoteDtlList.get(i).getDomesticQtyReceived()==null?"":String.valueOf(sapBoxNoteDtlList.get(i).getDomesticQtyReceived()));
//            map.put("meins",StringUtils.isEmpty(String.valueOf(sapBoxNoteDtlList.get(i).getBasicUnit()))==true?"":String.valueOf(sapBoxNoteDtlList.get(i).getBasicUnit()));
            map.put("meins",sapBoxNoteDtlList.get(i).getBasicUnit()==null?"":String.valueOf(sapBoxNoteDtlList.get(i).getBasicUnit()));
            map.put("srmContractNo",StringUtils.isEmpty(sapBoxNoteDtlList.get(i).getSrmContractNo())?"":String.valueOf(sapBoxNoteDtlList.get(i).getSrmContractNo()));
            map.put("ebeln",StringUtils.isEmpty(sapBoxNoteDtlList.get(i).getPurchaseNo())?"":sapBoxNoteDtlList.get(i).getPurchaseNo());
//            map.put("ebelp",StringUtils.isEmpty(String.valueOf(sapBoxNoteDtlList.get(i).getPurchaseNoItem()))?"":sapBoxNoteDtlList.get(i).getPurchaseNoItem());
            map.put("ebelp",sapBoxNoteDtlList.get(i).getPurchaseNoItem()==null?"":String.valueOf(sapBoxNoteDtlList.get(i).getPurchaseNoItem()));
            map.put("vbeln",StringUtils.isEmpty(sapBoxNoteDtlList.get(i).getDeliveryNoteSap())?"":sapBoxNoteDtlList.get(i).getDeliveryNoteSap());
//            map.put("posnr",StringUtils.isEmpty(String.valueOf(sapBoxNoteDtlList.get(i).getDeliveryNoteSapItem()))?"":sapBoxNoteDtlList.get(i).getDeliveryNoteSapItem());
            map.put("posnr",sapBoxNoteDtlList.get(i).getDeliveryNoteSapItem()==null?"":String.valueOf(sapBoxNoteDtlList.get(i).getDeliveryNoteSapItem()));
            map.put("demandNo",StringUtils.isEmpty(sapBoxNoteDtlList.get(i).getDemandNo())?"":sapBoxNoteDtlList.get(i).getDemandNo());
//            map.put("demandPosnr",StringUtils.isEmpty(String.valueOf(sapBoxNoteDtlList.get(i).getDemandNoItem()))?"":String.valueOf(sapBoxNoteDtlList.get(i).getDemandNoItem()));
            map.put("demandPosnr",sapBoxNoteDtlList.get(i).getDemandNoItem()==null?"":String.valueOf(sapBoxNoteDtlList.get(i).getDemandNoItem()));
            map.put("demander",StringUtils.isEmpty(sapBoxNoteDtlList.get(i).getDemander())?"":sapBoxNoteDtlList.get(i).getDemander());
            map.put("mark",StringUtils.isEmpty(sapBoxNoteDtlList.get(i).getRemark())?"":sapBoxNoteDtlList.get(i).getRemark());
//            map.put("brgew",StringUtils.isEmpty(String.valueOf(sapBoxNoteDtlList.get(i).getGrossWeight()))?"":String.valueOf(sapBoxNoteDtlList.get(i).getGrossWeight()));
            map.put("brgew",sapBoxNoteDtlList.get(i).getGrossWeight()==null?"":String.valueOf(sapBoxNoteDtlList.get(i).getGrossWeight()));
//            map.put("ntgew",StringUtils.isEmpty(String.valueOf(sapBoxNoteDtlList.get(i).getNetWeight()))?"":String.valueOf(sapBoxNoteDtlList.get(i).getNetWeight()));
            map.put("ntgew",sapBoxNoteDtlList.get(i).getNetWeight()==null?"":String.valueOf(sapBoxNoteDtlList.get(i).getNetWeight()));
//            map.put("gnshsl",StringUtils.isEmpty(String.valueOf(sapBoxNoteDtlList.get(i).getDomesticQtyReceivable()))?"":String.valueOf(sapBoxNoteDtlList.get(i).getDomesticQtyReceivable()));
            map.put("gnshsl",sapBoxNoteDtlList.get(i).getDomesticQtyReceivable()==null?"":String.valueOf(sapBoxNoteDtlList.get(i).getDomesticQtyReceivable()));
//            map.put("gnsjsl",StringUtils.isEmpty(String.valueOf(sapBoxNoteDtlList.get(i).getDomesticQtyReceived()))?"":String.valueOf(sapBoxNoteDtlList.get(i).getDomesticQtyReceived()));
            map.put("gnsjsl",sapBoxNoteDtlList.get(i).getDomesticQtyReceived()==null?"":String.valueOf(sapBoxNoteDtlList.get(i).getDomesticQtyReceived()));
//            map.put("hwshhl",StringUtils.isEmpty(String.valueOf(sapBoxNoteDtlList.get(i).getOverseaQtyReceived()))?"":String.valueOf(sapBoxNoteDtlList.get(i).getOverseaQtyReceived()));
            map.put("hwshhl",sapBoxNoteDtlList.get(i).getOverseaQtyReceived()==null?"":String.valueOf(sapBoxNoteDtlList.get(i).getOverseaQtyReceived()));
            jr.add(map);
        }
        return jr;
    }

}
