package com.sunda.spmsweb.wmscontroller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sunda.spmscommon.Constans;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsweb.util.JWTUtil;
import com.sunda.spmswms.entity.PositionMoveRequest;
import com.sunda.spmswms.entity.WhsStorage;
import com.sunda.spmswms.entity.WhsStorageInventory;
import com.sunda.spmswms.service.IWhsOperateLogService;
import com.sunda.spmswms.service.IWhsStorageInventoryService;
import com.sunda.spmswms.service.IWhsStorageService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.sunda.spmscommon.Constans.WhsOperateLog_DocumentType_NanShaStorageLog;
import static com.sunda.spmscommon.Constans.WhsOperateLog_DocumentType_OverSeaStorageLog;

/**
 * @description:
 * @author: Johnny Zhao
 * @time: 2021/5/14 12:42
 */
@RestController
@RequestMapping("/WhsPositionMove")
@Api(tags = "库房移位信息", description = "库房移位信息")
public class WhsPositionMoveController {

    @Autowired
    IWhsStorageInventoryService iWhsStorageInventoryService;
    
    @Autowired
    IWhsStorageService iWhsStorageService;
    
    @Autowired
    IWhsOperateLogService iWhsOperateLogService;

    @RequestMapping("/whsPositionMove")
    @ApiOperation(value = "获得移位信息", httpMethod = "POST")
    public ResponseResult getPositionList(@RequestBody JSONObject searchCriteria) {
        List<String> boxNoteList = searchCriteria.containsKey("boxNoteList") ? (List) searchCriteria.getJSONArray("boxNoteList") : null;
        System.out.println(boxNoteList);
        List<WhsStorageInventory> whsStorageInventoryList = iWhsStorageInventoryService.getStorageListByBoxNoteList(boxNoteList);

        return ResponseResult.success().add("key", whsStorageInventoryList.toString());
    }


    @RequestMapping("/whsPositionMoveRequest")
    @ApiOperation(value = "上传移位信息", httpMethod = "POST", notes = "每行错误代码（RowCode）含义：\n\t2000：PDA提交数据时间格式正常，且晚于SPMS系统记录时间，代表为最新记录，写入数据库\n" +
            "\t1500: SPMS系统已有箱码储位记录，时间格式正确，且时间晚于PDA提交时间，证明非最新库位状态，该条PDA提交记录丢弃\n" +
            "\t1000: PDA提交系统的记录日期格式有问题，SPMS系统直接修改为正确格式且录入结果\n" +
            "\t3000: SPMS系统没有此箱号的操作记录，直接采用该PDA操作记录新建该箱号上架记录，数量为1,\n" +
            "\t提交信息格式为：\n" + "{\n" +
            "\t\"data\": [{\n" +
            "\t\t\t\"boxNo\": \"ZX-10215800004-0303\",\n" +
            "\t\t\t\"uuid\": \"b95946ac1dab42b79ade3438acb0b513\",\n" +
            "\t\t\t\"operateTime\": \"2021-04-22 14:08:29\",\n" +
            "                        \"comments\":\"\"\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"boxNo\": \"TEST-1001-0101\",\n" +
            "\t\t\t\"uuid\": \"b95946ac1dab42b79ade3438acb0b53i\",\n" +
            "\t\t\t\"operateTime\": \"2021-04-20 12:09:28\",\n" +
            "                        \"comments\":\"\"\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"boxNo\": \"ZF-10fff-ff0101\",\n" +
            "\t\t\t\"uuid\": \"b95946ac1dab42b79ade3438acb0b512\",\n" +
            "\t\t\t\"operateTime\": \"2021-04-22 12:08:29\",\n" +
            "                        \"comments\":\"\"\n" +
            "\t\t}\n" +
            "\n" +
            "\t]\n" +
            "}")
    public ResponseResult positionMoveResult(@RequestBody JSONObject storageList) {
        JSONArray prListJson = storageList.containsKey("data") ? storageList.getJSONArray("data") : null;
        List<PositionMoveRequest> prList = (List<PositionMoveRequest>) JSONArray.parseArray(prListJson.toJSONString(), PositionMoveRequest.class);
        Iterator it = prList.iterator();
        List<PositionMoveRequest> prResult = new ArrayList<>();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        while (it.hasNext()) {
            PositionMoveRequest pmr = (PositionMoveRequest) it.next();
            System.out.println("提交箱码录入的储位为" + pmr.getUuid());
            if (pmr.getOperateTime() != null && pmr.getOperateTime().matches("^[1-3]\\d+-\\d+-\\d+ \\d+:\\d+:\\d+")) {
                try {
                    Optional<WhsStorageInventory> wsi = iWhsStorageInventoryService.getStorageInventoryByBoxNo(pmr.getBoxNo());
                    if (wsi.isPresent()) {
                        String opt = wsi.get().getOperateTime();
                        System.out.println("系统时间为" + opt);
                        if (opt != null && opt.matches("^[1-3]\\d+-\\d+-\\d+ \\d+:\\d+:\\d+")) {
                            if (df.parse(pmr.getOperateTime()).after(df.parse(opt))) {
                                PositionMoveRequest prResultEl = new PositionMoveRequest();
                                iWhsStorageInventoryService.updateStorageInventoryX(pmr.getUuid(), pmr.getOperateTime(), pmr.getBoxNo());
                                prResultEl.setUuid(pmr.getUuid());
                                prResultEl.setBoxNo(pmr.getBoxNo());
                                prResultEl.setOperateTime(pmr.getOperateTime());
                                String s = String.format("提交日期%S晚于系统日期%S，已完成更新", pmr.getOperateTime(), opt);
                                prResultEl.setComments(s);
                                prResultEl.setRowCode(2000);
                                prResult.add(prResultEl);
                                System.out.println("已完成更新");
                            } else {
                                PositionMoveRequest prResultEl = new PositionMoveRequest();
                                prResultEl.setUuid(pmr.getUuid());
                                prResultEl.setBoxNo(pmr.getBoxNo());
                                prResultEl.setOperateTime(pmr.getOperateTime());
                                String s = String.format("提交日期%S早于或等于系统日期%S，已放弃更新", pmr.getOperateTime(), opt);
                                prResultEl.setComments(s);
                                prResultEl.setRowCode(1500);
                                prResult.add(prResultEl);
                                System.out.println("不需要更新");
                            }
                        } else {
                            PositionMoveRequest prResultEl = new PositionMoveRequest();
                            iWhsStorageInventoryService.updateStorageInventoryX(pmr.getUuid(), pmr.getOperateTime(), pmr.getBoxNo());
                            prResultEl.setUuid(pmr.getUuid());
                            prResultEl.setBoxNo(pmr.getBoxNo());
                            prResultEl.setOperateTime(pmr.getOperateTime());
                            String s = String.format("原时间%S不正确，已修改为正确时间%S", opt, pmr.getOperateTime());
                            prResultEl.setComments(s);
                            prResultEl.setRowCode(1000);
                            prResult.add(prResultEl);
                            System.out.println("系统更新为提交的时间并纠正格式");
                        }
                    } else {
                        PositionMoveRequest prResultEl = new PositionMoveRequest();
                        System.out.println("系统未查找到此项");
                        iWhsStorageInventoryService.insertStorageInventory(pmr.getUuid(), pmr.getOperateTime(), pmr.getBoxNo());
                        prResultEl.setUuid(pmr.getUuid());
                        prResultEl.setBoxNo(pmr.getBoxNo());
                        prResultEl.setOperateTime(pmr.getOperateTime());
                        prResultEl.setComments("此行为新建");
                        prResultEl.setRowCode(3000);
                        prResult.add(prResultEl);
                        System.out.println("此行在系统内新建");
                    }
                } catch (Exception e) {
                    return ResponseResult.error(e.getMessage());
                }
            } else {
                PositionMoveRequest prResultEl = new PositionMoveRequest();
                prResultEl.setUuid(pmr.getUuid());
                prResultEl.setBoxNo(pmr.getBoxNo());
                prResultEl.setOperateTime(pmr.getOperateTime());
                String s = String.format("上架提交项时间%S不正确，此项未提交成功！", pmr.getOperateTime());
                prResultEl.setComments(s);
                prResultEl.setRowCode(4000);
                prResult.add(prResultEl);
                System.out.println("发生错误，此行提交未成功");
            }
        }
        return ResponseResult.success().add("返回结果列表", prResult);
    }

    @SuppressWarnings("unchecked")
	@RequestMapping("/whsPositionMoveX")
    @ApiOperation(value = "备件货仓库内移位", httpMethod = "POST", notes = "备件货仓库内移位\n" +
            "{\n" +
            "  \"werks\":\"CN01\",\n" +
            "  \"whsLocationCode\":\"1061\",\n" +
            "  \"boxNote\":\"BJ-9485738922\",\n" +
            "  \"sourceStorageUuid\":\"sources storage uuid\",\n" +
            "  \"targetStorageUuid\":\"target storage uuid\",\n" +
            "  \"boxNoteInfo\":\"[{\"boxNote\":\"BJ-20231000782-0115\",\"operateQty\":1},{\"boxNote\":\"BJ-20231000782-0215\",\"operateQty\":1}]\",\n" +
            "  \"operateQty\":1\n" +
            "}")
    @RequiresPermissions("WhsPositionMove-whsPositionMoveX")
    public ResponseResult whsPositionMoveX(@RequestBody JSONObject posMoveObj) {
        try {
            String werks = posMoveObj.getString("werks");
            String whsLocationCode = posMoveObj.getString("whsLocationCode");
//            String boxNote = posMoveObj.getString("boxNote");
            String sourceStorageUuid = posMoveObj.getString("sourceStorageUuid");
            String targetStorageUuid = posMoveObj.getString("targetStorageUuid");
//            double operateQty = posMoveObj.containsKey("operateQty") ? posMoveObj.getDouble("operateQty") : -1;
            // 新增批量库内移位 2023-12-29 xzp add 
            JSONArray boxNoteArray = posMoveObj.getJSONArray("boxNoteInfo");

//            if (StringUtils.isEmpty(werks) || StringUtils.isEmpty(whsLocationCode) ||
//                    StringUtils.isEmpty(boxNote) || StringUtils.isEmpty(sourceStorageUuid) || StringUtils.isEmpty(targetStorageUuid) || operateQty <= 0) {
//                return ResponseResult.error("Please check your paramaters");
//            }
            if (StringUtils.isEmpty(werks) || StringUtils.isEmpty(whsLocationCode) || StringUtils.isEmpty(sourceStorageUuid) || 
            		StringUtils.isEmpty(targetStorageUuid) || boxNoteArray == null || boxNoteArray.size() == 0) {
            	return ResponseResult.error("Please check your paramaters");
            }

            String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
            for (int i = 0; i < boxNoteArray.size(); i++) {
            	Map<String, Object> boxNoteMap = (Map<String, Object>) boxNoteArray.get(i);
            	if (boxNoteMap.get("operateQty") == null || BigDecimal.ZERO.compareTo(new BigDecimal(boxNoteMap.get("operateQty").toString())) >= 0) {
            		return ResponseResult.error("箱码："+boxNoteMap.get("boxNote").toString()+"移出数量必须大于0");
            	}
            	WhsStorageInventory whsStorageInventory = iWhsStorageInventoryService.getStorageBoxNote(sourceStorageUuid, boxNoteMap.get("boxNote").toString());
            	if (null == whsStorageInventory) {
            		return ResponseResult.error("The given boxNote: " + boxNoteMap.get("boxNote").toString() + " does not exist on storage: " + sourceStorageUuid);
            	}
            }
            // 检查储位间是否在相同的工厂跟仓库
            WhsStorage outWhsStorage = iWhsStorageService.getWhsStorageByUuid(sourceStorageUuid);
            WhsStorage inWhsStorage = iWhsStorageService.getWhsStorageByUuid(targetStorageUuid);
            if (!outWhsStorage.getWerks().equals(inWhsStorage.getWerks()) || !outWhsStorage.getWhsLocationCode().equals(inWhsStorage.getWhsLocationCode())) {
            	return ResponseResult.error("库内移位只能在相同工厂、仓库下进行");
            }
            for (int i = 0; i < boxNoteArray.size(); i++) {
            	Map<String, Object> boxNoteMap = (Map<String, Object>) boxNoteArray.get(i);
            	String boxNote = boxNoteMap.get("boxNote").toString();
            	// 从原储位下加，并加日志
            	if (iWhsStorageInventoryService.deleteStorageByBoxNoteStorageId(sourceStorageUuid, boxNote) < 0) {
            		return ResponseResult.error("error for " + boxNote + " on storage, storageUuid: " + sourceStorageUuid);
            	}
            	iWhsOperateLogService.insertWhsOperateLog(
            			WhsOperateLog_DocumentType_NanShaStorageLog,
            			sourceStorageUuid,
            			"",
            			boxNote,
            			1,
            			Constans.WhsOperateLog_OperationType_ShelfOff,
            			"",
            			Constans.WHS_PositionMove_ShelfOff,
            			userId,
            			Constans.WHS_PositionMove,
            			werks,
            			whsLocationCode, "");
            	
            	//在目标储位上架，并加日志
            	iWhsStorageInventoryService.insertStorageInventory(targetStorageUuid, "", boxNote);
            	iWhsOperateLogService.insertWhsOperateLog(
            			WhsOperateLog_DocumentType_NanShaStorageLog,
            			targetStorageUuid,
            			"",
            			boxNote,
            			1,
            			Constans.WhsOperateLog_OperationType_ShelfOn,
            			"",
            			Constans.WHS_PositionMove_ShelfOn,
            			userId,
            			Constans.WHS_PositionMove,
            			werks,
            			whsLocationCode, "");
            }
            return ResponseResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error(e.getMessage());
        }

    }
    
    @SuppressWarnings("unchecked")
	@RequestMapping("/whsPositionMoveXPda")
    @ApiOperation(value = "PDA备件货仓库内移位", httpMethod = "POST", notes = "PDA备件货仓库内移位\n" +
    		"{\n" +
    		"  \"werks\":\"CN01\",\n" +
    		"  \"whsLocationCode\":\"1061\",\n" +
    		"  \"boxNoteInfo\":\"[{\"sourceStorageUuid\":\"sources storage uuid\",\"targetStorageUuid\":\"target storage uuid\",\"boxNote\":\"BJ-20231000782-0115\",\"operateQty\":1},{\"sourceStorageUuid\":\"sources storage uuid\",\"targetStorageUuid\":\"target storage uuid\",\"boxNote\":\"BJ-20231000782-0215\",\"operateQty\":1}]\"\n" +
    		"}")
    @RequiresPermissions("WhsPositionMove-whsPositionMoveXPda")
    public ResponseResult whsPositionMoveXPda(@RequestBody JSONObject posMoveObj) {
    	try {
//    		String werks = posMoveObj.getString("werks");
//    		String whsLocationCode = posMoveObj.getString("whsLocationCode");
    		JSONArray boxNoteArray = posMoveObj.getJSONArray("boxNoteInfo");
    		if (boxNoteArray == null || boxNoteArray.size() == 0) {
    			return ResponseResult.error("Please check your paramaters");
    		}
    		String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
    		for (int i = 0; i < boxNoteArray.size(); i++) {
    			Map<String, Object> boxNoteMap = (Map<String, Object>) boxNoteArray.get(i);
    			if (boxNoteMap.get("operateQty") == null || BigDecimal.ZERO.compareTo(new BigDecimal(boxNoteMap.get("operateQty").toString())) >= 0) {
    				return ResponseResult.error("箱码："+boxNoteMap.get("boxNote").toString()+"移出数量必须大于0");
    			}
    			if (boxNoteMap.get("sourceStorageUuid") == null) {
    				return ResponseResult.error("箱码："+boxNoteMap.get("boxNote").toString()+"的移出储位UUID不能为空");
    			}
    			if (boxNoteMap.get("targetStorageUuid") == null) {
    				return ResponseResult.error("箱码："+boxNoteMap.get("boxNote").toString()+"的移入储位UUID不能为空");
    			}
    			WhsStorageInventory whsStorageInventory = iWhsStorageInventoryService.getStorageBoxNote(boxNoteMap.get("sourceStorageUuid").toString(), boxNoteMap.get("boxNote").toString());
    			if (null == whsStorageInventory) {
    				return ResponseResult.error("The given boxNote: " + boxNoteMap.get("boxNote").toString() + " does not exist on storage: " + boxNoteMap.get("sourceStorageUuid").toString());
    			}
    		}
    		for (int i = 0; i < boxNoteArray.size(); i++) {
    			Map<String, Object> boxNoteMap = (Map<String, Object>) boxNoteArray.get(i);
    			String boxNote = boxNoteMap.get("boxNote").toString();
    			String sourceStorageUuid = boxNoteMap.get("sourceStorageUuid").toString();
    			String targetStorageUuid = boxNoteMap.get("targetStorageUuid").toString();
    			WhsStorage outWhsStorage = iWhsStorageService.getWhsStorageByUuid(sourceStorageUuid);
    			WhsStorage inWhsStorage = iWhsStorageService.getWhsStorageByUuid(targetStorageUuid);
    			// 从原储位下加，并加日志
    			if (iWhsStorageInventoryService.deleteStorageByBoxNoteStorageId(sourceStorageUuid, boxNote) < 0) {
    				return ResponseResult.error("error for " + boxNote + " on storage, storageUuid: " + sourceStorageUuid);
    			}
    			iWhsOperateLogService.insertWhsOperateLog(
    					WhsOperateLog_DocumentType_NanShaStorageLog,
    					sourceStorageUuid,
    					"",
    					boxNote,
    					1,
    					Constans.WhsOperateLog_OperationType_ShelfOff,
    					"",
    					Constans.WHS_PositionMove_ShelfOff,
    					userId,
    					Constans.WHS_PositionMove,
    					outWhsStorage.getWerks(),
    					outWhsStorage.getWhsLocationCode(), "");
    			
    			//在目标储位上架，并加日志
    			iWhsStorageInventoryService.insertStorageInventory(targetStorageUuid, "", boxNote);
    			iWhsOperateLogService.insertWhsOperateLog(
    					WhsOperateLog_DocumentType_NanShaStorageLog,
    					targetStorageUuid,
    					"",
    					boxNote,
    					1,
    					Constans.WhsOperateLog_OperationType_ShelfOn,
    					"",
    					Constans.WHS_PositionMove_ShelfOn,
    					userId,
    					Constans.WHS_PositionMove,
    					inWhsStorage.getWerks(),
    					inWhsStorage.getWhsLocationCode(), "");
    		}
    		return ResponseResult.success();
    	} catch (Exception e) {
    		e.printStackTrace();
    		return ResponseResult.error(e.getMessage());
    	}
    	
    }
    @SuppressWarnings("unchecked")
	@RequestMapping("/whsPositionMoveM")
    @ApiOperation(value = "贸易货仓库内移位", httpMethod = "POST", notes = "贸易货仓库内移位\n" +
            "{\n" +
            "  \"werks\":\"CN01\",\n" +
            "  \"whsLocationCode\":\"1061\",\n" +
            "  \"materialNo\":\"maerial no\",\n" +
            "  \"sourceStorageUuid\":\"sources storage uuid\",\n" +
            "  \"targetStorageUuid\":\"target storage uuid\",\n" +
            "  \"materialInfo\":\"[{\"materialNo\":\"210017211\",\"operateQty\":1},{\"materialNo\":\"170001298\",\"operateQty\":1}]\",\n" +
            "  \"operateQty\":12\n" +
            "}")
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions("WhsPositionMove-whsPositionMoveM")
    public synchronized ResponseResult whsPositionMoveM(@RequestBody JSONObject posMoveObj) throws Exception {
        //try {
            String werks = posMoveObj.getString("werks");
            String whsLocationCode = posMoveObj.getString("whsLocationCode");
//            String materialNo = posMoveObj.getString("materialNo");
            String sourceStorageUuid = posMoveObj.getString("sourceStorageUuid");
            String targetStorageUuid = posMoveObj.getString("targetStorageUuid");
//            double operateQty = posMoveObj.containsKey("operateQty") ? posMoveObj.getDouble("operateQty") : -1;
            // 新增批量库内移位 2023-12-29 xzp add 
            JSONArray materialArray = posMoveObj.getJSONArray("materialInfo");
//            if (StringUtils.isEmpty(werks) || StringUtils.isEmpty(whsLocationCode) ||
//                    StringUtils.isEmpty(materialNo) || StringUtils.isEmpty(sourceStorageUuid) || StringUtils.isEmpty(targetStorageUuid) || operateQty <= 0) {
//                return ResponseResult.error("Please check your paramaters");
//            }
            if (StringUtils.isEmpty(werks) || StringUtils.isEmpty(whsLocationCode) || 
            		StringUtils.isEmpty(sourceStorageUuid) || StringUtils.isEmpty(targetStorageUuid) || materialArray == null || materialArray.size() == 0) {
            	return ResponseResult.error("Please check your paramaters");
            }
            for (int i = 0; i < materialArray.size(); i++) {
            	Map<String, Object> materialMap = (Map<String, Object>) materialArray.get(i);
            	if (materialMap.get("operateQty") == null || BigDecimal.ZERO.compareTo(new BigDecimal(materialMap.get("operateQty").toString())) >= 0) {
            		return ResponseResult.error("物料编码："+materialMap.get("materialNo").toString()+"移出数量必须大于0");
            	}
            }

            String documentType = "CN01".equals(werks) ? WhsOperateLog_DocumentType_NanShaStorageLog : WhsOperateLog_DocumentType_OverSeaStorageLog;
            String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
            // 检查储位间是否在相同的工厂跟仓库
            WhsStorage outWhsStorage = iWhsStorageService.getWhsStorageByUuid(sourceStorageUuid);
            WhsStorage inWhsStorage = iWhsStorageService.getWhsStorageByUuid(targetStorageUuid);
            if (!outWhsStorage.getWerks().equals(inWhsStorage.getWerks()) || !outWhsStorage.getWhsLocationCode().equals(inWhsStorage.getWhsLocationCode())) {
            	return ResponseResult.error("库内移位只能在相同工厂、仓库下进行");
            }
            for (int i = 0; i < materialArray.size(); i++) {
            	Map<String, Object> materialMap = (Map<String, Object>) materialArray.get(i);
            	Double operateQty = Double.valueOf(materialMap.get("operateQty").toString());
            	String materialNo = materialMap.get("materialNo").toString();
            	JSONObject storageObj=new JSONObject();
            	storageObj.put("storageUuid",sourceStorageUuid);
            	storageObj.put("qty",operateQty);
            	JSONArray tempStorage=new JSONArray();
            	tempStorage.add(storageObj);
            	// 检查可出的库存
            	ResponseResult checkInvRes = iWhsStorageInventoryService.checkStorageInventory(tempStorage, materialNo);
            	if (checkInvRes.getCode() != 200) {
            		throw new Exception(checkInvRes.getMsg());
            	}
            	// 从原储位下加，并加日志
            	if (iWhsStorageInventoryService.updateWhsStorage(sourceStorageUuid, materialNo, operateQty) < 0) {
            		throw new Exception("Update Storage Inventory failed for " + materialNo + " on storage Info, storageUuid: " +
            				sourceStorageUuid +
            				", qty: " + operateQty);
            	}
            	iWhsOperateLogService.insertWhsOperateLog(
            			documentType,
            			sourceStorageUuid,
            			materialNo,
            			"",
            			operateQty,
            			Constans.WhsOperateLog_OperationType_ShelfOff,
            			"",
            			Constans.WHS_PositionMove_ShelfOff,
            			userId,
            			Constans.WHS_PositionMove,
            			werks,
            			whsLocationCode, "");
            	
            	//在目标储位上架，并加日志
            	if (iWhsStorageInventoryService.updateWhsStorageInventoryMOld(targetStorageUuid, materialNo, operateQty) < 0) {
            		throw new Exception("Update Storage Inventory failed for " + materialNo + " on storage Info, storageUuid: " +
            				targetStorageUuid +
            				", qty: " + operateQty);
            	}
            	iWhsOperateLogService.insertWhsOperateLog(
            			documentType,
            			targetStorageUuid,
            			materialNo,
            			"",
            			operateQty,
            			Constans.WhsOperateLog_OperationType_ShelfOn,
            			"",
            			Constans.WHS_PositionMove_ShelfOn,
            			userId,
            			Constans.WHS_PositionMove,
            			werks,
            			whsLocationCode, "");
            	
            }
            return ResponseResult.success();
//        } catch (Exception e) {
//            e.printStackTrace();
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return ResponseResult.error(e.getMessage());
//        }

    }
    
    @SuppressWarnings("unchecked")
    @RequestMapping("/whsPositionMoveMPda")
    @ApiOperation(value = "PDA贸易货仓库内移位", httpMethod = "POST", notes = "PDA贸易货仓库内移位\n" +
    		"{\n" +
    		"  \"werks\":\"CN01\",\n" +
    		"  \"whsLocationCode\":\"1061\",\n" +
    		"  \"materialNo\":\"maerial no\",\n" +
    		"  \"sourceStorageUuid\":\"sources storage uuid\",\n" +
    		"  \"targetStorageUuid\":\"target storage uuid\",\n" +
    		"  \"materialInfo\":\"[{\"targetStorageUuid\":\"target storage uuid\",\"sourceStorageUuid\":\"sources storage uuid\",\"materialNo\":\"210017211\",\"operateQty\":1},{\"targetStorageUuid\":\"target storage uuid\",\"sourceStorageUuid\":\"sources storage uuid\",\"materialNo\":\"170001298\",\"operateQty\":1}]\",\n" +
    		"  \"operateQty\":12\n" +
    		"}")
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions("WhsPositionMove-whsPositionMoveMPda")
    public synchronized ResponseResult whsPositionMoveMPda(@RequestBody JSONObject posMoveObj) throws Exception {
    	JSONArray materialArray = posMoveObj.getJSONArray("materialInfo");
    	if (materialArray == null || materialArray.size() == 0) {
    		return ResponseResult.error("Please check your paramaters");
    	}
    	for (int i = 0; i < materialArray.size(); i++) {
    		Map<String, Object> materialMap = (Map<String, Object>) materialArray.get(i);
    		if (materialMap.get("operateQty") == null || BigDecimal.ZERO.compareTo(new BigDecimal(materialMap.get("operateQty").toString())) >= 0) {
    			return ResponseResult.error("物料编码："+materialMap.get("materialNo").toString()+"移出数量必须大于0");
    		}
			if (materialMap.get("sourceStorageUuid") == null) {
				return ResponseResult.error("物料："+materialMap.get("materialNo").toString()+"的移出储位UUID不能为空");
			}
			if (materialMap.get("targetStorageUuid") == null) {
				return ResponseResult.error("物料："+materialMap.get("materialNo").toString()+"的移入储位UUID不能为空");
			}
    	}
    	
    	String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
    	for (int i = 0; i < materialArray.size(); i++) {
    		Map<String, Object> materialMap = (Map<String, Object>) materialArray.get(i);
    		Double operateQty = Double.valueOf(materialMap.get("operateQty").toString());
    		String materialNo = materialMap.get("materialNo").toString();
    		String sourceStorageUuid = materialMap.get("sourceStorageUuid").toString();
    		String targetStorageUuid = materialMap.get("targetStorageUuid").toString();
    		WhsStorage outWhsStorage = iWhsStorageService.getWhsStorageByUuid(sourceStorageUuid);
    		WhsStorage inWhsStorage = iWhsStorageService.getWhsStorageByUuid(targetStorageUuid);
    		JSONObject storageObj=new JSONObject();
    		storageObj.put("storageUuid",sourceStorageUuid);
    		storageObj.put("qty",operateQty);
    		JSONArray tempStorage=new JSONArray();
    		tempStorage.add(storageObj);
    		// 检查可出的库存
    		ResponseResult checkInvRes = iWhsStorageInventoryService.checkStorageInventory(tempStorage, materialNo);
    		if (checkInvRes.getCode() != 200) {
    			throw new Exception(checkInvRes.getMsg());
    		}
    		String documentType = "CN01".equals(outWhsStorage.getWerks()) ? WhsOperateLog_DocumentType_NanShaStorageLog : WhsOperateLog_DocumentType_OverSeaStorageLog;
    		// 从原储位下加，并加日志
    		if (iWhsStorageInventoryService.updateWhsStorage(sourceStorageUuid, materialNo, operateQty) < 0) {
    			throw new Exception("Update Storage Inventory failed for " + materialNo + " on storage Info, storageUuid: " +
    					sourceStorageUuid +
    					", qty: " + operateQty);
    		}
    		iWhsOperateLogService.insertWhsOperateLog(
    				documentType,
    				sourceStorageUuid,
    				materialNo,
    				"",
    				operateQty,
    				Constans.WhsOperateLog_OperationType_ShelfOff,
    				"",
    				Constans.WHS_PositionMove_ShelfOff,
    				userId,
    				Constans.WHS_PositionMove,
    				outWhsStorage.getWerks(),
    				outWhsStorage.getWhsLocationCode(), "");
    		
    		//在目标储位上架，并加日志
    		String documentType2 = "CN01".equals(inWhsStorage.getWerks()) ? WhsOperateLog_DocumentType_NanShaStorageLog : WhsOperateLog_DocumentType_OverSeaStorageLog;
    		if (iWhsStorageInventoryService.updateWhsStorageInventoryMOld(targetStorageUuid, materialNo, operateQty) < 0) {
    			throw new Exception("Update Storage Inventory failed for " + materialNo + " on storage Info, storageUuid: " +
    					targetStorageUuid +
    					", qty: " + operateQty);
    		}
    		iWhsOperateLogService.insertWhsOperateLog(
    				documentType2,
    				targetStorageUuid,
    				materialNo,
    				"",
    				operateQty,
    				Constans.WhsOperateLog_OperationType_ShelfOn,
    				"",
    				Constans.WHS_PositionMove_ShelfOn,
    				userId,
    				Constans.WHS_PositionMove,
    				inWhsStorage.getWerks(),
    				inWhsStorage.getWhsLocationCode(), "");
    		
    	}
    	return ResponseResult.success();
    }


}
