package com.cim.idm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cim.idm.exception.GlobalException;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.data.EventInfo;
import com.cim.idm.framework.util.time.TimeUtils;
import com.cim.idm.model.AutoLibraryDetailDto;
import com.cim.idm.model.AutoLibraryDto;
import com.cim.idm.service.Impl.AutoLibraryServiceImpl;
import com.cim.idm.service.impl.WCSServiceImpl;
import com.cim.idm.utils.AjaxResult;
import com.cim.idm.utils.EventInfoUtil;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
import com.cim.idm.wmspackage.materialpacking.MaterialPackingServiceProxy;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingKey;
import com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 立体库管理
 * @author 10539622
 *
 */
@Slf4j
@RestController
@EnableAutoConfiguration
@RequestMapping("/api/MaturationLibrary")
@Api(tags = "立体库接口", description = "立体库接口")
public class AutoLibraryController {

	@Autowired 
	private WCSServiceImpl WCSServiceImpl = new WCSServiceImpl();

	@Autowired 
	private AutoLibraryServiceImpl autoLibraryServiceImpl;
	

	/**
	 * 熟化库出库
	 * @param in
	 * @return
	 * @throws JsonProcessingException 
	 * @throws JsonMappingException 
	 * @throws CustomException 
	 */
	@ApiOperation("通过物料条码查询条码信息(获取完成后绑定出库")
	@ApiResponses(value = {
			@ApiResponse(code = 200, message = "成功响应", response = ApiResponse.class),
			@ApiResponse(code = 400, message = "请求参数错误"),
			@ApiResponse(code = 500, message = "服务器内部错误")
	})
	@RequestMapping(value = "/MatuStockOut", method = RequestMethod.POST)
	@Transactional
	public AjaxResult MatuStockOut(@RequestBody JSONObject in ) throws JsonMappingException, JsonProcessingException, CustomException {

		AutoLibraryDto m = JSON.toJavaObject(in, AutoLibraryDto.class);
		String userId = m.getUserId(); // 获取用户
		String sitename = m.getSITENAME();
		EventInfo makeEventInfo = new EventInfoUtil().makeEventInfo("MatuStockOut",userId, "MatuStockOut");
		List<MaterialPackingKey> list = new ArrayList<MaterialPackingKey>();
		String transportCommand = "TRANS"+new TimeUtils().getCurrentEventTimeKey();
		for(AutoLibraryDetailDto detail : m.getMATERIALPACKINGNAME())
		{
			//修改Materialpacking  信息
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("stockState","StockOut");
			bindMap.put("areaName","");
			bindMap.put("shipTime",new Timestamp(System.currentTimeMillis()));
			SetEventInfo setEventInfo = new SetEventInfo();
			setEventInfo.setUserColumns(bindMap);
			MaterialPackingKey mp=new MaterialPackingKey(sitename,detail.getMATERIALPACKINGNAME());
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mp, makeEventInfo, setEventInfo);
			list.add(mp);
			//熟化库出库-》下发WCS
			transportCommand = autoLibraryServiceImpl.createCommand(makeEventInfo,detail,"",transportCommand);
			String transportCommandRequest = WCSServiceImpl.transportCommandRequest(transportCommand,userId);
			org.json.JSONObject jsonObject = new org.json.JSONObject(transportCommandRequest);
			String returnCode = jsonObject.get("RETURNCODE").toString();
			if ("1".equals(returnCode)) {
				String message = jsonObject.get("RETURNMESSAGE").toString();
				return AjaxResult.me().setSuccess(false) .setMessage(message);
			}
		}

		return null ;
	}



	@ApiOperation("通过物料条码查询条码信息(获取完成后绑定出库")
	@ApiResponses(value = {
			@ApiResponse(code = 200, message = "成功响应", response = ApiResponse.class),
			@ApiResponse(code = 400, message = "请求参数错误"),
			@ApiResponse(code = 500, message = "服务器内部错误")
	})
	@RequestMapping(value = "/MatuMove", method = RequestMethod.POST)
	@Transactional
	public AjaxResult MatuMove(@RequestBody JSONObject in ) throws JsonMappingException, JsonProcessingException, CustomException{		
		AutoLibraryDto m = JSON.toJavaObject(in, AutoLibraryDto.class);
		String userId = m.getUserId(); // 获取用户
		String sitename = m.getSITENAME();
		EventInfo makeEventInfo = new EventInfoUtil().makeEventInfo("MatuMove",userId, "MatuMove");
		List<MaterialPackingKey> list = new ArrayList<MaterialPackingKey>();
		String transportCommand = "TRANS"+new TimeUtils().getCurrentEventTimeKey();
		for(AutoLibraryDetailDto detail : m.getMATERIALPACKINGNAME())
		{
			//修改Materialpacking  信息
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("areaName",m.getAREANAME());
			bindMap.put("shipTime",new Timestamp(System.currentTimeMillis()));
			SetEventInfo setEventInfo = new SetEventInfo();
			setEventInfo.setUserColumns(bindMap);
			MaterialPackingKey mp=new MaterialPackingKey(sitename,detail.getMATERIALPACKINGNAME());
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mp, makeEventInfo, setEventInfo);
			list.add(mp);
			//熟化库出库-》下发WCS
			transportCommand = autoLibraryServiceImpl.createCommand(makeEventInfo,detail,m.getAREANAME(),transportCommand);
			String transportCommandRequest = WCSServiceImpl.transportCommandRequest(transportCommand,userId);
		}

		List<MaterialPacking> selectByKey = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(list); 
		//熟化库出库-》NC过账
//		String result=ncServiceImpl.qtcNoInvoice(selectByKey,userId);
//		if(!result.equals("1"))
//		{
//			throw new CustomException(result); 
//		}

		return null ;
	}


	/*******************************************************************************************************************/
	/*******************************************************************************************************************/
	/*************************************立体库更新20240727****************************************************/
	/*******************************************************************************************************************/
	/**
	 * 立库入库
	 * @param in
	 * @return
	 */
	@ApiOperation("立体库入库")
	@ApiResponses(value = {
			@ApiResponse(code = 200, message = "成功响应", response = ApiResponse.class),
			@ApiResponse(code = 400, message = "请求参数错误"),
			@ApiResponse(code = 500, message = "服务器内部错误")
	})
	@RequestMapping(value = "/AutoStockIn", method = RequestMethod.POST)
	@Transactional
	public AjaxResult AutoStockIn(@RequestBody JSONObject in ){		
		AutoLibraryDto m = JSON.toJavaObject(in, AutoLibraryDto.class);
		String userId = m.getUserId(); // 获取用户
		String sitename = m.getSITENAME() == null ? "SDK" : m.getSITENAME();
		String areaname = m.getAREANAME();//入库货区
//		B			线边库
//		C			熟化库
//		E			包材库
//		F			小卷库
//		G			大卷库
//		String barCode = m.getBarCode();//扫描条码
		String erpFactory = m.getErpFactory();//组织
		String erpLocation = m.getErpLocation();//仓库
		String locationName = m.getLocationName();//货位
//		String durableName = m.getDurableName();//管芯，托盘
		String temperature = m.getTEMPERATURE();//烘烤温度
		String bakingdays = m.getBAKINGDAYS();//烘烤小时
		String width = m.getWIDTH();//宽幅
		String diameter = m.getDIAMETER();//直径
		String deviation = m.getDEVIATION();//偏移量
		String weight = m.getWEIGHT();//重量
		String productline = m.getPRODUCTLINE();//生产线
		String commitDate = m.getCommitDate();
		String opCode = m.getOpCode();
		EventInfo makeEventInfo = new EventInfoUtil().makeEventInfo("AutoStockIn",userId, "AutoStockIn");
		String transportCommand = "TRANS"+new  TimeUtils().getCurrentEventTimeKey();
		List<AutoLibraryDetailDto> materialpackingname2 = m.getMATERIALPACKINGNAME();
		boolean bZK = false;
		boolean bBQ = false;
		//创建搬送任务
		for(AutoLibraryDetailDto detail : m.getMATERIALPACKINGNAME())
		{
			String materialpackingname = detail.getMATERIALPACKINGNAME();
			String durablename = detail.getDURABLENAME();
			if (durablename == null || "".equals(durablename)) {
				
				detail.setDURABLENAME(detail.getTRAYNAME());
			}
			//判断标签是否已在库
			String judgeZKSql = "SELECT * FROM MATERIALPACKING m WHERE m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME";
			String judgeBQSql = "SELECT LOTNAME,REQUESTNAME,PRODUCTSPECNAME FROM BS_MES_SHIPPED bms WHERE bms.LOTNAME = :MATERIALPACKINGNAME";
			Map<String, Object> hashMap = new HashMap<String,Object> ();
			hashMap.put("MATERIALPACKINGNAME", materialpackingname);
			hashMap.put("ERPFACTORY", erpFactory);
			hashMap.put("ERPLOCATION", erpLocation);
			hashMap.put("LOCATIONNAME", locationName);
			List<Map<String, Object>> judgeZK = IDMFrameServiceProxy.getSqlTemplate().queryForList(judgeZKSql, hashMap);
			List<Map<String, Object>> judgeBQ = IDMFrameServiceProxy.getSqlTemplate().queryForList(judgeBQSql, hashMap);
			bZK = (judgeZK != null && judgeZK.size() >= 1);  //在库
			bBQ = (judgeBQ != null && judgeBQ.size() >= 1);  //在标签
			if ( !bZK && !bBQ) {
				return AjaxResult.me().setSuccess(false).setMessage("目标条码不在库也未在标签系统打印");
			}
			//根据库区判断是否参与NC过账
			boolean ncFlag = "E".equals(areaname) || "F".equals(areaname) || "G".equals(areaname); //检查是否完成生产入库报告
			
			if (!bZK && bBQ) {//标签写入库存表
				if (ncFlag) {
					String sql2 = "SELECT\r\n" + 
							"	BMS.LOTNAME MATERIALPACKINGNAME,\r\n" + 
							"	BMS.PRODUCTSPECNAME MATERIALSPECNAME,\r\n" + 
							"	BMS.PHASE ,BMS.SDK_ID,\r\n" + 
							"	SS.SPECNAME ,\r\n" + 
							"	m.DESC_CN ,\r\n" + 
							"	BMS.QTY MATERIALQUANTITY ,\r\n" + 
							"	BMS.REQUESTNAME RECEIVEREQUESTNAME ,\r\n" + 
							"	BMS.CHARGE, :ERPFACTORY ERPFACTORY, :ERPLOCATION ERPLOCATION, :LOCATIONNAME LOCATIONNAME\r\n" + 
							"FROM\r\n" + 
							"	BS_MES_SHIPPED BMS LEFT JOIN MATERIALSPEC m ON m.MATERIALSPECNAME = BMS.PRODUCTSPECNAME \r\n" + 
							"	LEFT JOIN SDK_SPEC SS ON SS.SDK_ID = BMS.SDK_ID \r\n" + 
							"WHERE\r\n" + 
							"	BMS.LOTNAME = :MATERIALPACKINGNAME\r\n" + 
							"	AND (BMS.RECEIVE_FLAG IS NULL\r\n" + 
							"		OR BMS.RECEIVE_FLAG <> 'Y')";
					List<Map<String,Object>> list2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql2, hashMap);
					if(list2.size() != 1) {
						return AjaxResult.me().setSuccess(false).setMessage("生产未完成入库,请联系IT处理！");
					}
					String sdk_id = list2.get(0).get("SDK_ID").toString();
					String phase = list2.get(0).get("PHASE").toString();
					//根据入库信息获取完工报告
					StringBuffer sql3 = new StringBuffer();
					sql3.append(" ");
					sql3.append(" SELECT ");
					sql3.append(" M.RECEIVEREQUESTNAME, ");
					sql3.append(" M.RECEIVEREQUESTDETAILNAME ");
					sql3.append(" FROM ");
					sql3.append(" MATERIALRECEIVEREQUESTDETAIL M ");
					sql3.append(" WHERE ");
					sql3.append(" (M.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME ");
					sql3.append(" OR M.PRODUCTORDER = :RECEIVEREQUESTNAME ");
					sql3.append(" OR M.PLANORDER = :RECEIVEREQUESTNAME) ");
					sql3.append(" AND M.MATERIALSPECNAME = :MATERIALSPECNAME ");
					if (!"".equals(sdk_id) && !"~".equals(sdk_id)) {
						sql3.append(" AND SDK_ID = :SDK_ID "); 
					} else  {
						sql3.append(" AND SDK_ID is null  "); 
					}
					if (!"".equals(phase)) {
						sql3.append(" AND PHASE = :PHASE ");
					} else {
						sql3.append(" AND PHASE  is null ");
					}
					sql3.append(" AND M.REQUESTQUANTITY   - M.RECEIVEDQUANTITY  > 0 ");

					hashMap.put("RECEIVEREQUESTNAME",list2.get(0).get("REQUESTNAME"));
					hashMap.put("MATERIALSPECNAME",list2.get(0).get("PRODUCTSPECNAME"));
					hashMap.put("PHASE",phase);
					hashMap.put("SDK_ID",sdk_id);
					List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql3.toString(), hashMap);
					if (queryForList == null || queryForList.size() < 1) {
						throw new GlobalException("生产报告未完成,请联系IT处理！");
					}
					try {
//						ProductIntoServiceImpl.receiveMesShippInfo(makeEventInfo, "SDK", materialpackingname, "", userId,
//								materialpackingname, "", erpLocation, erpFactory, locationName,queryForList.get(0).get("RECEIVEREQUESTNAME").toString(), queryForList.get(0).get("RECEIVEREQUESTDETAILNAME").toString(),"");
					} catch (Exception e) {
						e.printStackTrace();
						return AjaxResult.me().setSuccess(false).setMessage(e.toString());
					}
				}
				String pc = "('" + materialpackingname + "')";
				if (ncFlag) {
					try {
//						boolean fgStockIn = ProductIntoServiceImpl.fgStockInBySplitCharge(pc, userId,commitDate,opCode);
					} catch (Exception e) {
						return AjaxResult.me().setSuccess(false). setMessage(e.toString());
					}
				} 
			}
			//创建搬送任务
			detail.setTEMPERATURE(temperature);
			detail.setBAKINGDAYS(bakingdays);
			detail.setWEIGHT(width);
			detail.setDIAMETER(diameter);
			detail.setDEVIATION(deviation);
			detail.setWIDTH(width);
			detail.setPRODUCTLINE(productline);
			try {
				transportCommand = autoLibraryServiceImpl.createCommand(makeEventInfo,detail,"",transportCommand);
			} catch (CustomException e) {
				e.printStackTrace();
				return AjaxResult.me().setSuccess(false). setMessage(e.toString());
			}
			
		}
		
		if (bZK) {//标签在库
			String transportCommandRequest = WCSServiceImpl.transportCommandRequest(transportCommand,userId);
			org.json.JSONObject jsonObject = new org.json.JSONObject(transportCommandRequest);
			String returnCode = jsonObject.get("RETURNCODE").toString();
			if ("1".equals(returnCode)) {
				String message = jsonObject.get("RETURNMESSAGE").toString();
				return AjaxResult.me().setSuccess(false). setMessage(message);
			} else {
				Map<String, Object> hashMap1 = new HashMap<String,Object> ();
				//循环更新库存表
				String updateSql = "SELECT t.DURABLENAME ,t.PACKINGNAME,t.INDESTINATION, t.WIDTH,t.WEIGHT,t.DIAMETER,t.DEVIATION,t.PRODUCTLINE"
						+ " FROM TRANSPORTCOMMANDDETAIL t WHERE t.TRANSPORTCOMMANDID = :TRANSPORTCOMMANDID";
				Map<String, Object> hashMap = new HashMap<String,Object> ();
				hashMap.put("TRANSPORTCOMMANDID", transportCommand);
				List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(updateSql, hashMap);
				for (Map<String, Object> map : queryForList) {
					String durablename = map.get("DURABLENAME") == null ? "" : map.get("DURABLENAME").toString();
					String materialpackingname = map.get("PACKINGNAME") == null ? "" : map.get("PACKINGNAME").toString();
					String areaname2 = map.get("INDESTINATION") == null ? "" : map.get("INDESTINATION").toString();
					String width2 = map.get("WIDTH") == null ? "" : map.get("WIDTH").toString();
					String weight2 = map.get("WEIGHT") == null ? "" : map.get("WEIGHT").toString();
					String diameter2 = map.get("DIAMETER") == null ? "" : map.get("DIAMETER").toString();
					String PRODUCTLINE = map.get("PRODUCTLINE") == null ? "" : map.get("PRODUCTLINE").toString();
					hashMap1.put("durableName", durablename);
					hashMap1.put("areaName", areaname2);
					if (!"".equals(width2)) {
						hashMap1.put("WIDTH", width2);
					}
					if (!"".equals(deviation)) {
						hashMap1.put("DEVIATION", deviation);
					}
					if (!"".equals(weight2)) {
						hashMap1.put("WEIGHT", weight2);
					}
					if (!"".equals(diameter2)) {
						hashMap1.put("DIAMETER", diameter2);
					}
					if (!"".equals(PRODUCTLINE)) {
						hashMap1.put("PRODUCTLINE", PRODUCTLINE);
					}
					MaterialPackingKey materialPackingKey = new MaterialPackingKey("SDK",materialpackingname);
					SetEventInfo setEventInfo = new SetEventInfo();
					setEventInfo.setUserColumns(hashMap1);
					MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey, makeEventInfo, setEventInfo);
				}
			}
		} else {
			autoLibraryServiceImpl.bqTransportRequest(transportCommand, userId, makeEventInfo);
		}
		return AjaxResult.me().setSuccess(true).setMessage("入立库成功");
	}

	@ApiOperation("立体库出库")
	@ApiResponses(value = {
			@ApiResponse(code = 200, message = "成功响应", response = ApiResponse.class),
			@ApiResponse(code = 400, message = "请求参数错误"),
			@ApiResponse(code = 500, message = "服务器内部错误")
	})
	@RequestMapping(value = "/AutoStockOut", method = RequestMethod.POST)
	@Transactional
	public AjaxResult AutoStockOut(@RequestBody JSONObject in ){	
		AutoLibraryDto m = JSON.toJavaObject(in, AutoLibraryDto.class);
		String userId = m.getUserId(); // 获取用户
		String sitename = m.getSITENAME();
		String areaname = m.getAREANAME();
		String aimAreaName = m.getAimAreaName();
//		String commitDate = m.getCommitDate();
		EventInfo makeEventInfo = new EventInfoUtil().makeEventInfo("AutoStockOut",userId, "AutoStockOut");
		String transportCommand = "TRANS"+new TimeUtils().getCurrentEventTimeKey();
		List<MaterialPackingKey> list = new ArrayList<MaterialPackingKey>();
		for(AutoLibraryDetailDto detail : m.getMATERIALPACKINGNAME())
		{
//			detail.setDURABLENAME(m.getDurableName());
//			String materialpackingname = detail.getMATERIALPACKINGNAME();
//			String areaname2 = detail.getAREANAME();
			String trayname = detail.getTRAYNAME();
			String durablename = detail.getDURABLENAME();
			if (trayname == null || "".equals(trayname)) {
				detail.setTRAYNAME(durablename);
			}
//			detail.setTRAYNAME(durablename);
			//修改Materialpacking  信息
			MaterialPackingKey mp=new MaterialPackingKey(sitename,detail.getMATERIALPACKINGNAME());
			
			list.add(mp);
			//熟化库出库-》下发WCS
			try {
				transportCommand = autoLibraryServiceImpl.createCommand(makeEventInfo,detail,m.getAREANAME(),transportCommand);
			} catch (CustomException e) {
				e.printStackTrace();
			}
		}
		String transportCommandRequest = WCSServiceImpl.transportCommandRequest(transportCommand,userId);
		org.json.JSONObject jsonObject = new org.json.JSONObject(transportCommandRequest);
		String returnCode = jsonObject.get("RETURNCODE").toString();
		if ("1".equals(returnCode)) {
			String message = jsonObject.get("RETURNMESSAGE").toString();
			return AjaxResult.me().setSuccess(false). setMessage(message);
		} else {
			Map<String, Object> hashMap1 = new HashMap<String,Object> ();
			//循环更新库存表
			String updateSql = "SELECT t.DURABLENAME ,t.PACKINGNAME,t.OUTDESTINATION, t.WIDTH,t.WEIGHT,t.DIAMETER,t.DEVIATION,t.PRODUCTLINE"
					+ " FROM TRANSPORTCOMMANDDETAIL t WHERE t.TRANSPORTCOMMANDID = :TRANSPORTCOMMANDID";
			Map<String, Object> hashMap = new HashMap<String,Object> ();
			hashMap.put("TRANSPORTCOMMANDID", transportCommand);
			List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(updateSql, hashMap);
			for (Map<String, Object> map : queryForList) {
				String durablename = map.get("DURABLENAME") == null ? "" : map.get("DURABLENAME").toString();
				String materialpackingname = map.get("PACKINGNAME") == null ? "" : map.get("PACKINGNAME").toString();
				String areaname2 = map.get("OUTDESTINATION") == null ? "" : map.get("OUTDESTINATION").toString();
				hashMap1.put("durableName", durablename);
				hashMap1.put("areaName", areaname2);
				MaterialPackingKey materialPackingKey = new MaterialPackingKey("SDK",materialpackingname);
				SetEventInfo setEventInfo = new SetEventInfo();
				setEventInfo.setUserColumns(hashMap1);
				MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey, makeEventInfo, setEventInfo);
			}

		}
//		//熟化库出库-》NC过账
//		if ("C".equals(areaname)) {
//			List<MaterialPacking> MaterialPackingList = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(list);
////			noInvoiceManagerServiceImpl.QTC(MaterialPackingList, userId,"SDK");
//		}
		return AjaxResult.me().setSuccess(true).setMessage("出立库成功");
	}
	/**
	 * 查询待出立库明细
	 * @param in
	 * @return
	 */
	@ApiOperation("查询待出立库明细")
	@ApiResponses(value = {
			@ApiResponse(code = 200, message = "成功响应", response = ApiResponse.class),
			@ApiResponse(code = 400, message = "请求参数错误"),
			@ApiResponse(code = 500, message = "服务器内部错误")
	})
	@RequestMapping(value = "/getPreStockOutByAuto", method = RequestMethod.POST)
	public AjaxResult getPreStockOutByAuto(@RequestBody JSONObject in ){
		AutoLibraryDto m = JSON.toJavaObject(in, AutoLibraryDto.class);
		String areaname = m.getAREANAME();
		String shipRequestName = m.getShipRequestName();
		String materialSpecName = m.getMaterialSpecName();
		String sdk_id = m.getSDK_ID();
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append(" ");
		stringBuffer.append(" SELECT ");
		stringBuffer.append(" m.MATERIALPACKINGNAME ,m.MATERIALSPECNAME,m.SHELFNAME, m2.DESC_CN,a.DESCRIPTION,m.AREANAME,m.DURABLENAME TRAYNAME,");
		stringBuffer.append(" m.CHARGE ,  m.WIDTH ,m.PRODUCTLINE,m.WEIGHT,m.DIAMETER,m.DEVIATION ,m.STOCKSTATE,");
		stringBuffer.append(" m.MATERIALQUANTITY , ");
		stringBuffer.append(" m2.DESCRIPTION , ");
		stringBuffer.append(" ss.SPECNAME , ");
		stringBuffer.append(" be.DESCRIPTION ERPLOCATION , ");
		stringBuffer.append(" s.DESCRIPTION LOCATIONNAME, ");
		stringBuffer.append(" m.SHIPREQUESTNAME  ");
		stringBuffer.append(" FROM ");
		stringBuffer.append(" MATERIALPACKING m ");
		stringBuffer.append(" LEFT JOIN SDK_SPEC ss ON ");
		stringBuffer.append(" m.SDK_ID = ss.SDK_ID ");
		stringBuffer.append(" LEFT JOIN MATERIALSPEC m2 ON ");
		stringBuffer.append(" m.MATERIALSPECNAME = m2.MATERIALSPECNAME ");
		stringBuffer.append(" LEFT JOIN BS_ERPLOCATION be ON ");
		stringBuffer.append(" m.ERPLOCATION = be.ERPLOCATIONNAME ");
		stringBuffer.append(" LEFT JOIN STORAGESPEC s ON ");
		stringBuffer.append(" s.ERPLOCATION = m.ERPLOCATION AND s.ERPFACTORY = m.ERPFACTORY ");
		stringBuffer.append(" AND m.LOCATIONNAME = s.STORAGENAME ");
		stringBuffer.append(" LEFT JOIN AREA a ON m.AREANAME = a.AREANAME");
		stringBuffer.append(" WHERE 1 = 1  ");
		if (!"".equals(shipRequestName) && shipRequestName != null) {
			stringBuffer.append(" AND SHIPREQUESTNAME IS NOT NULL ");
		}
		stringBuffer.append(" AND (:MATERIALSPECNAME IS NULL OR m.MATERIALSPECNAME  = :MATERIALSPECNAME) ");
		stringBuffer.append(" AND (:SDK_ID IS NULL OR m.SDK_ID  = :SDK_ID) ");
		stringBuffer.append(" AND m.AREANAME  = :AREANAME ");
		stringBuffer.append(" AND m.DURABLENAME IS NOT NULL");
		stringBuffer.append(" AND m.SHELFNAME IS NOT NULL AND (m.StockState = 'Stocked' OR  m.StockState = 'StockOut') ");
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("AREANAME", areaname);
		hashMap.put("MATERIALSPECNAME", materialSpecName);
		hashMap.put("SDK_ID", sdk_id);
		List<Map<String, Object>> queryForList = null;
		queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(stringBuffer.toString(), hashMap);
		if (queryForList == null || queryForList.size() < 1) {
			StringBuffer stringBuffer2 = new StringBuffer();
			stringBuffer2.append(" ");
			stringBuffer2.append(" SELECT  ");
			stringBuffer2.append("  m.LOTNAME MATERIALPACKINGNAME , ");
			stringBuffer2.append(" m.PRODUCTSPECNAME MATERIALSPECNAME, ");
			stringBuffer2.append(" m.LK_SHELFNAME SHELFNAME, ");
			stringBuffer2.append(" m2.DESC_CN, ");
			stringBuffer2.append(" a.DESCRIPTION, ");
			stringBuffer2.append(" m.LK_AREANAME AREANAME, ");
			stringBuffer2.append(" m.LK_DURABLENAME TRAYNAME, ");
			stringBuffer2.append(" m.CHARGE , ");
			stringBuffer2.append(" m.LK_WIDTH , ");
			stringBuffer2.append(" m.LK_PRODUCTLINE PRODUCTLINE, ");
			stringBuffer2.append(" m.LK_WEIGHT WEIGHT, ");
			stringBuffer2.append(" m.LK_DIAMETER DIAMETER, ");
			stringBuffer2.append(" m.LK_DEVIATION DEVIATION , ");
			stringBuffer2.append(" 'StockOut' STOCKSTATE, ");
			stringBuffer2.append("  m.QTY MATERIALQUANTITY ,  ");
			stringBuffer2.append("  m2.DESCRIPTION ,  ");
			stringBuffer2.append(" ss.SPECNAME ,  ");
			stringBuffer2.append(" '' ERPLOCATION ,  ");
			stringBuffer2.append("  '' LOCATIONNAME ");
			stringBuffer2.append(" FROM  ");
			stringBuffer2.append(" BS_MES_SHIPPED m ");
			stringBuffer2.append(" LEFT JOIN SDK_SPEC ss ON  ");
			stringBuffer2.append(" m.SDK_ID = ss.SDK_ID ");
			stringBuffer2.append(" LEFT JOIN MATERIALSPEC m2 ON  ");
			stringBuffer2.append(" m.PRODUCTSPECNAME = m2.MATERIALSPECNAME ");
			stringBuffer2.append(" LEFT JOIN AREA a ON ");
			stringBuffer2.append(" m.LK_AREANAME = a.AREANAME ");
			stringBuffer2.append(" WHERE ");
			stringBuffer2.append(" 1 = 1 ");
			stringBuffer2.append(" AND (:MATERIALSPECNAME IS NULL ");
			stringBuffer2.append(" OR m.PRODUCTSPECNAME = :MATERIALSPECNAME) ");
			stringBuffer2.append(" AND (:SDK_ID IS NULL ");
			stringBuffer2.append(" OR m.SDK_ID = :SDK_ID) ");
			stringBuffer2.append(" AND m.LK_AREANAME = :AREANAME ");
			stringBuffer2.append(" AND m.LK_DURABLENAME IS NOT NULL ");
			stringBuffer2.append(" AND m.LK_SHELFNAME IS NOT NULL ");
			queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(stringBuffer2.toString(), hashMap);
		} 
		return AjaxResult.me().setResultObj(queryForList);
	}
	
	/**
	 * 获取出货Port口
	 * @param in
	 * @return
	 */
	@ApiOperation("获取port口")
	@ApiResponses(value = {
			@ApiResponse(code = 200, message = "成功响应", response = ApiResponse.class),
			@ApiResponse(code = 400, message = "请求参数错误"),
			@ApiResponse(code = 500, message = "服务器内部错误")
	})
	@RequestMapping(value = "/getPort", method = RequestMethod.POST)
	public AjaxResult getPort(@RequestBody JSONObject in ){		
		AutoLibraryDto m = JSON.toJavaObject(in, AutoLibraryDto.class);
		String areaname = m.getAREANAME();
		
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append(" SELECT PORTNO,PORTNAME FROM PORT WHERE AREANAME = :AREANAME ");
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("AREANAME", areaname);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(stringBuffer.toString(), hashMap);
		return AjaxResult.me().setResultObj(queryForList);
	}
	
	
	@ApiOperation("获取FG信息")
	@ApiResponses(value = {
			@ApiResponse(code = 200, message = "成功响应", response = ApiResponse.class),
			@ApiResponse(code = 400, message = "请求参数错误"),
			@ApiResponse(code = 500, message = "服务器内部错误")
	})
	@RequestMapping(value = "/getFGInfo", method = RequestMethod.POST)
	public AjaxResult getFGInfo(@RequestBody JSONObject in ){		
		AutoLibraryDto m = JSON.toJavaObject(in, AutoLibraryDto.class);
		String barCode = m.getBarCode();
		String durableName = m.getDurableName();
		String zkSql = "SELECT\r\n" + 
				"	m.MATERIALPACKINGNAME ,\r\n" + 
				"	m.CHARGE,\r\n" + 
				"	M2.MATURATIONTIME ,\r\n" + 
				"	:DURABLENAME DURABLENAME,\r\n" + 
				"	:DURABLENAME TRAYNAME\r\n" + 
				"FROM\r\n" + 
				"	MATERIALPACKING m\r\n" + 
				"LEFT JOIN MATERIALSPEC M2 ON\r\n" + 
				"	m.MATERIALSPECNAME = M2.MATERIALSPECNAME\r\n" + 
				"WHERE\r\n" + 
				"	AREANAME IS NULL\r\n" + 
				"	AND SHELFNAME IS NULL\r\n" + 
				"	AND m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME";
		
		String bqSql = "SELECT\r\n" + 
				"	bms.LOTNAME MATERIALPACKINGNAME,\r\n" + 
				"	bms.CHARGE,\r\n" + 
				"	M2.MATURATIONTIME ,\r\n" + 
				"	:DURABLENAME DURABLENAME,\r\n" + 
				"	:DURABLENAME TRAYNAME\r\n" + 
				"FROM\r\n" + 
				"	BS_MES_SHIPPED bms\r\n" + 
				"LEFT JOIN MATERIALSPEC M2 ON\r\n" + 
				"	bms.PRODUCTSPECNAME = M2.MATERIALSPECNAME\r\n" + 
				"WHERE\r\n" + 
				"	  bms.LOTNAME = :MATERIALPACKINGNAME";
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("MATERIALPACKINGNAME", barCode);
		hashMap.put("DURABLENAME", durableName);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(zkSql, hashMap);
		if (queryForList == null || queryForList.size() < 1) {
			queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(bqSql, hashMap);
			if (queryForList == null || queryForList.size() < 1) {
				return AjaxResult.me().setSuccess(false) .setMessage("批次不在库或未完成打标签");
			}
		}
		//判断管芯是否已在库绑定
		String sql = "SELECT M.MATERIALPACKINGNAME FROM MATERIALPACKING m WHERE DURABLENAME  = :DURABLENAME AND AREANAME <> 'E' ";
		List<Map<String, Object>> queryForList2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
		if (queryForList2 != null && queryForList2.size() > 0) {
			String string = queryForList2.get(0).get("MATERIALPACKINGNAME").toString();
			return AjaxResult.me().setSuccess(false) .setMessage("管芯已在" + string);
		}
		return AjaxResult.me().setResultObj(queryForList);
	}

	
	
	@ApiOperation("绑定Tray")
	@ApiResponses(value = {
			@ApiResponse(code = 200, message = "成功响应", response = ApiResponse.class),
			@ApiResponse(code = 400, message = "请求参数错误"),
			@ApiResponse(code = 500, message = "服务器内部错误")
	})
	@RequestMapping(value = "/assignTryByBox", method = RequestMethod.POST)
	public AjaxResult assignTryByBox(@RequestBody JSONObject in ){		
		AutoLibraryDto m = JSON.toJavaObject(in, AutoLibraryDto.class);
		String barCode = m.getBarCode();
		String durableName = m.getDurableName();
		 String userId = m.getUserId();
		 EventInfo makeEventInfo = new EventInfoUtil().makeEventInfo("AssignTryByBox", userId, "AssignTryByBox");
		try {
			autoLibraryServiceImpl.checkDurable(durableName);
			autoLibraryServiceImpl.assignTryByBox(makeEventInfo, durableName, "SDK", barCode);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return AjaxResult.me().setSuccess(false).setMessage("绑定失败");
		}
		return AjaxResult.me().setSuccess(true).setMessage("绑定成功");
	}
	
	@ApiOperation("解绑Tray")
	@ApiResponses(value = {
			@ApiResponse(code = 200, message = "成功响应", response = ApiResponse.class),
			@ApiResponse(code = 400, message = "请求参数错误"),
			@ApiResponse(code = 500, message = "服务器内部错误")
	})
	@RequestMapping(value = "/deassignTryByBox", method = RequestMethod.POST)
	public AjaxResult deassignTryByBox(@RequestBody JSONObject in ){
		AutoLibraryDto m = JSON.toJavaObject(in, AutoLibraryDto.class);
		String barCode = m.getBarCode();
		String durableName = m.getDurableName();
		 String userId = m.getUserId();
		 EventInfo makeEventInfo = new EventInfoUtil().makeEventInfo("DeassignTryByBox", userId, "DeassignTryByBox");
		try {
			autoLibraryServiceImpl.checkDurable(durableName);
			autoLibraryServiceImpl.deassignTryByBox(makeEventInfo, durableName, "SDK", barCode);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return AjaxResult.me().setSuccess(false).setMessage(e.toString());
		}
		return AjaxResult.me().setSuccess(true).setMessage("解绑成功");
	}
	
	@ApiOperation("获取搬送口")
	@ApiResponses(value = {
			@ApiResponse(code = 200, message = "成功响应", response = ApiResponse.class),
			@ApiResponse(code = 400, message = "请求参数错误"),
			@ApiResponse(code = 500, message = "服务器内部错误")
	})
	@RequestMapping(value = "/GetLiberaryBaeIn", method = RequestMethod.POST)
	public AjaxResult GetLiberaryBaeIn(@RequestBody JSONObject in ){
		String sqlString = "	SELECT ENUMVALUE AS value,DESCRIPTION AS label FROM ENUMDEFVALUE e WHERE ENUMNAME='LibraryBaseIn'";
		HashMap<String,Object> hashMap = new HashMap<String,Object>(); 
		List<Map<String,Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlString, hashMap);
		return AjaxResult.me().setSuccess(true).setMessage("查询成功").setResultObj(queryForList);
	}
	
}
