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.model.*;
import com.cim.idm.model.dto.TrackOutBoDto;
import com.cim.idm.model.dto.StoragePrintDto;
import com.cim.idm.model.po.MaterialReceiveRequest;
import com.cim.idm.mwmsextend.materialpacking.service.MaterialPackingServiceImpl;
import com.cim.idm.response.BaseResponse;
import com.cim.idm.response.RespGenerator;
import com.cim.idm.service.LabelService;
import com.cim.idm.utils.AjaxResult;
import com.cim.idm.utils.EventInfoUtil;
import com.cim.idm.utils.JsonResponse;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
import com.cim.idm.wmspackage.material.management.info.SetSpecEventInfo;
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 org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author 10486880
 * @version 1.0
 * @description LabelController
 * @date 2023/11/15 9:54
 */
@RestController
@RequestMapping("/api/label")
@EnableAutoConfiguration
public class LabelController {

    @Resource
    private LabelService labelService;

//    @Resource
//    private LabelPrintInfoService labelPrintInfoService;

    private static final RestTemplate restTemplate = new RestTemplateBuilder().build();

    @PostMapping("labelAction")
    //@Operation(summary = "labelAction, 创建，修改，删除 标签， actionType 提交 Create | Modify | Delete ")
    public JsonResponse<String> labelAction(@RequestBody LabelDto data) {
        labelService.labelAction(data);
        return JsonResponse.success();
    }

    @PostMapping("labelAssignFGCodeAction")
    //@Operation(summary = "标签绑定 产品型号， actionType 提交 Create | Delete ")
    public JsonResponse<String> labelAssignFGCodeAction(@RequestBody LabelAssignFGCodeDto data) {
        labelService.labelAssignFGCodeAction(data);
        return JsonResponse.success();
    }

    @PostMapping("labelAssignParameterAction")
    //@Operation(summary = "标签绑定 标签参数")
    public JsonResponse<String> labelAssignParameterAction(@RequestBody LabelAssignParameterDto data) {
        labelService.labelAssignParameterAction(data);
        return JsonResponse.success();
    }

	@RequestMapping(value = "/storagePrint", method = RequestMethod.POST)
	public AjaxResult storagePrint(@RequestBody JSONObject in) throws CustomException {
		// 获取信息
		String printName = in.get("PRINTNAME").toString();
		// 数据
		List<Map<String,Object>> dataList = (List) in.get("LIST");
		// 打印
		List<String> resList = new ArrayList<>();
        for (Map<String, Object> data : dataList) {
            StoragePrintDto storagePrintDto = new StoragePrintDto();
            storagePrintDto.setPrinterName(printName);
            storagePrintDto.setSiteName(data.get("SITENAME").toString());
            storagePrintDto.setStorageName(data.get("STORAGENAME").toString());
            String urlInfo = labelService.storagePrint(storagePrintDto);
            resList.add(urlInfo);
        }
		return AjaxResult.me().setResultObj(resList);
	}

    @RequestMapping(value = "/labelPrintTest", method = RequestMethod.POST)
    //@Operation(summary = "标签打印测试， 测试只能打印 标签模板没有参数的标签. ")
    public AjaxResult labelPrintTest(@RequestBody JSONObject in) throws CustomException {
    	String user = in.get("USER").toString();
    	String PRINTNAME = in.get("PRINTNAME").toString();
    	List<Map<String,Object>> js = (List) in.get("LIST");
    	List<String> urlList = new ArrayList<>();
    	for (int i = 0; i < js.size(); i++) {
    		Map jb = js.get(i);
    		LabelPrintDto labelPrintDto = new LabelPrintDto();

    		labelPrintDto.setLotName(jb.get("MATERIALPACKINGNAME").toString());
    		labelPrintDto.setOpreater(user);
    		labelPrintDto.setPrinterName(PRINTNAME);
    		String urlInfo = labelService.labelPrintTest(labelPrintDto);
    		urlList.add(urlInfo);
    	}

    	return AjaxResult.me().setResultObj(urlList);
    }
    
    
    @RequestMapping(value = "/labelPrintTest1", method = RequestMethod.POST)
    //@Operation(summary = "标签打印测试， 测试只能打印 标签模板没有参数的标签. ")
    public JsonResponse<String> labelPrintTest1(@RequestBody JSONObject in) throws CustomException {
    	String user = in.get("USER").toString();
    	String PRINTNAME = in.get("PRINTNAME").toString();
    	List<Map<String,Object>> js = (List) in.get("LIST");
    	for (int i = 0; i < js.size(); i++) {
    		Map jb = js.get(i);
    		LabelPrintDto1 labelPrintDto = new LabelPrintDto1();
    		labelPrintDto.setLotName(jb.get("MATERIALPACKINGNAME").toString());
//    		labelPrintDto.setDESC_CN(jb.get("DESC_CN").toString());
    		labelPrintDto.setOpreater(user);
    		labelPrintDto.setPrinterName(PRINTNAME);
    		labelService.labelPrintTest1(labelPrintDto);
    	}

        return JsonResponse.success();
    }
    
//    太仓成品打印
    @RequestMapping(value = "/labelPrintTest2", method = RequestMethod.POST)
    //@Operation(summary = "标签打印测试， 测试只能打印 标签模板没有参数的标签. ")
    public JsonResponse<String> labelPrintTest2(@RequestBody JSONObject in) throws CustomException {
    	String user = in.get("USER").toString();
    	String PRINTNAME = in.get("PRINTNAME").toString();
    	String qty = in.get("QTY").toString();
    	List<Map<String,Object>> js = (List) in.get("LIST");
    	for (int i = 0; i < js.size(); i++) {
    		Map jb = js.get(i);
    		LabelPrintDto2 labelPrintDto = new LabelPrintDto2();

    		labelPrintDto.setLotName(jb.get("LOTNAME").toString());
    		labelPrintDto.setOpreater(user);
    		labelPrintDto.setPrinterName(PRINTNAME);
    		labelPrintDto.setQty(qty);
    		labelService.labelPrintTest2(labelPrintDto);
    	}

        return JsonResponse.success();
    }
    
	/*
	 * 现存量标签打印
	 * Existing Stock Label
	*/
    @RequestMapping(value = "/existingStockLabel", method = RequestMethod.POST)
    //@Operation(summary = "标签打印测试， 测试只能打印 标签模板没有参数的标签. ")
    public AjaxResult existingStockLabel(@RequestBody JSONObject in) throws CustomException {
    	String user = in.get("USER").toString();
    	String PRINTNAME = in.get("PRINTNAME").toString();
    	String LABELCODE = in.get("LABELCODE").toString();
    	List<Map<String,Object>> js = (List) in.get("LIST");
    	List<String> urlList = new ArrayList<>();
    	for (int i = 0; i < js.size(); i++) {
    		Map jb = js.get(i);
    		LabelPrintDto1 labelPrintDto = new LabelPrintDto1();
    		labelPrintDto.setLotName(jb.get("MATERIALPACKINGNAME").toString());
    		labelPrintDto.setDESC_CN(jb.get("DESC_CN").toString());
    		labelPrintDto.setOpreater(user);
    		labelPrintDto.setPrinterName(PRINTNAME);
    		labelPrintDto.setLabelType(LABELCODE);
    		String urlInfo = labelService.labelPrintTest3(labelPrintDto);
    		urlList.add(urlInfo);
    	}

    	return AjaxResult.me().setResultObj(urlList);
    }

    @PostMapping("labelPrint")
    //@Operation(summary = "标签打印.")
    public JsonResponse<String> labelPrint(@RequestBody LabelPrintDto data) {
        labelService.labelPrint(data);
        return JsonResponse.success();
    }

    @PostMapping("batchLabelPrint")
    //@Operation(summary = "批量标签打印.")
    public JsonResponse<String> batchLabelPrint(@RequestBody LabelPrintBatchDto data) {
        labelService.batchLabelPrint(data);
        return JsonResponse.success();
    }

    @PostMapping("getPrinters")
    //@Operation(summary = "打印机列表.")
    public JsonResponse<List<String>> getPrinters(@RequestBody LabelPrintDto dto) {
//        Object permList = restTemplate.getForObject(
//                "http://192.168.200.237/Bartender/api/v1/printers",Object.class);
        String url = dto.getLabelId();
        Object permList = restTemplate.getForObject(
                url,Object.class);
        return new JsonResponse(permList);
    }

    @PostMapping("labeParameterAction")
    //@Operation(summary = "标签参数创建，删除")
    public JsonResponse<String> labelParameterAction(@RequestBody LabelParameterDto data) {
        labelService.labelParameterAction(data);
        return JsonResponse.success();
    }

    @PostMapping("saveLabelPrintInfo")
    //@Operation(summary = "标签信息保存")
    public JsonResponse<String> saveLabelPrintInfo(@RequestBody LabelPrintInfoDto data) {
        labelService.saveLabelPrintInfo(data);
        return JsonResponse.success();
    }

    @PostMapping("updateLabelPrintInfo")
    //@Operation(summary = "标签信息修改")
    public JsonResponse<String> updateLabelPrintInfo(@RequestBody LabelPrintInfoDto data) {
        //labelService.updateLabelPrintInfo(data);
        return JsonResponse.success();
    }
    
	/**
	 * 单位打印
	 * lz
	 */
	@RequestMapping(value = "/getUnitData" , method = RequestMethod.POST)
	public AjaxResult getUnitData() {
		String sqlString = "SELECT FNUMBER,fname FROM MATERIALUNIT";
		Map<String, Object> bindMap = new HashMap<String, Object>();
		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlString, bindMap);
		if(Objects.isNull(list) || list.isEmpty()) {
			throw new GlobalException("未找到对应的单位！");
		}
		return AjaxResult.me().setResultObj(list);
	}
	
	
	/**
	 * 生成销售备货单号
	 * @param in
	 * @return
	 */
	@RequestMapping(value = "/getSDKSPEC", method = RequestMethod.POST)
	public AjaxResult getSDKSPEC(@RequestBody JSONObject in ){
		MaterialshipRequest materialShipRequest = JSON.toJavaObject(in, MaterialshipRequest.class);
		String materialSpecName = materialShipRequest.getMaterialSpecName();//料号
		//根据料号获取sdk规格信息
		if (materialSpecName == null || "".equals(materialSpecName)) {
			return AjaxResult.me().setSuccess(false).setMessage("料号获取sdk规格信息不能为空");
		}
		if (materialSpecName.startsWith("4")) {
			materialSpecName = "4";
		}
		String sql = " SELECT SDK_ID  as \"value\" ,SPECNAME  as \"text\" FROM SDK_SPEC ss WHERE ss.PARTNUMBER = :PARTNUMBER";
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("PARTNUMBER", materialSpecName);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
		return AjaxResult.me().setResultObj(queryForList);
	}
	
	/**
	 * 创建Box
	 * @param in
	 * @return
	 * @throws CustomException 
	 * @throws Exception
	 */
	@RequestMapping(value = "/TrackOutBox", method = RequestMethod.POST)
	public AjaxResult TrackOutBox(@RequestBody JSONObject in )  {
		TrackOutBoDto boxs = JSON.toJavaObject(in, TrackOutBoDto.class);
		MaterialreceiveActDto box = boxs.getMaterialreceiveAct();
		String user = boxs.getUser();
		String sdkid = box.getSdkid();
		String phase = box.getPhase();
		String makeDate = box.getMakeDate();
		String materialquantity = box.getMATERIALQUANTITY();
		String erpFactory = box.getErpFactory();
		String materialcreatequantity = box.getMATERIALCREATEQUANTITY();
		String unit = box.getUnit();
		String materialSpecName = box.getMaterialSpecName();
		String truegg = box.getTruegg();
		String remark = box.getRemark();
		String siteName = "SDK";
		EventInfo makeEventInfo = new EventInfoUtil().makeEventInfo("TrackOutBox", user, "TrackOutBox");
		//判断数量卡控是否正确
		BigDecimal fboxQuantity = new BigDecimal(materialquantity);//标签数量
		BigDecimal feveryBoxQuantity = new BigDecimal(materialcreatequantity);//标签个数
		if ((fboxQuantity.divide(feveryBoxQuantity)) .compareTo(BigDecimal.ZERO) == -1) {
			return AjaxResult.me().setSuccess(false).setMessage("标签个数不能小于0");
		}
		if (feveryBoxQuantity .compareTo(BigDecimal.ZERO) == -1) {
			return AjaxResult.me().setSuccess(false).setMessage("标签数量不能小于0");
		}
		String timeKey = null;
//		String.valueOf((int)Math.floor(fboxQuantity/feveryBoxQuantity)
		try {
			timeKey = MaterialPackingServiceImpl.PackingLoael(makeEventInfo, siteName,String.valueOf(fboxQuantity.divide(feveryBoxQuantity)) , 
					materialcreatequantity, makeDate, erpFactory, materialSpecName, sdkid, phase, unit,
					String.valueOf((fboxQuantity.remainder(feveryBoxQuantity))),truegg,remark);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return AjaxResult.me().setSuccess(false).setMessage(e.toString());
		}
		System.out.println(timeKey);
//		String sqlString = "SELECT LASTEVENTTIMEKEY, MATERIALSPECNAME, SPECNAME, PHASE, MATERIALQUANTITY, UNIT, CHARGE, MATERIALPACKINGNAME FROM MATERIALPACKING m LEFT JOIN SDK_SPEC ss ON m.SDK_ID = ss.SDK_ID  WHERE  m.LASTEVENTTIMEKEY = :LASTEVENTTIMEKEY";
//		String sqlString = "	SELECT  m.LASTEVENTTIMEKEY, m.MATERIALSPECNAME, ss.SPECNAME, m.PHASE, m.MATERIALQUANTITY, m2.FNAME AS UNIT, m.CHARGE, m.MATERIALPACKINGNAME	FROM MATERIALPACKING m 	LEFT JOIN SDK_SPEC ss ON m.SDK_ID = ss.SDK_ID LEFT JOIN MATERIALUNIT m2 ON m.UNIT = m2.FNUMBER WHERE  m.LASTEVENTTIMEKEY = :LASTEVENTTIMEKEY";
		String sqlString = "SELECT  m.LASTEVENTTIMEKEY, m.MATERIALSPECNAME, ss.SPECNAME, m.PHASE, m.MATERIALQUANTITY, m2.FNAME AS UNIT, m.CHARGE, m.MATERIALPACKINGNAME,m.TRUEGG,m.REMARK\r\n"
				+ "FROM MATERIALPACKING m 	\r\n"
				+ "LEFT JOIN SDK_SPEC ss ON m.SDK_ID = ss.SDK_ID \r\n"
				+ "LEFT JOIN MATERIALUNIT m2 ON m.UNIT = m2.FNUMBER \r\n"
				+ "WHERE  1=1\r\n"
				+ "	AND m.LASTEVENTTIMEKEY = :LASTEVENTTIMEKEY";
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("LASTEVENTTIMEKEY", timeKey);
		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlString, bindMap);
		if(Objects.isNull(list) || list.isEmpty()) {
//			throw new GlobalException("未找到对应的单位！");
			 return AjaxResult.me().setSuccess(false).setMessage("未找到对应的数据！");
		}
		
		return AjaxResult.me().setResultObj(list);
	}

    //@PostMapping("generateLabelId")
    //@Operation(summary = "生成打印批号")
//    public JsonResponse<List<String>> generateLabelId(@RequestBody NameRuleDto data) {
//        String labelId = labelService.generateLabelId(data);
//        return new JsonResponse(labelId);
//    }

//    @PostMapping("saveNcData")
//    //@Operation(summary = "保存NC数据")
//    public JsonResponse<String> saveNcData(@RequestBody List<NcDataDto> data) {
//        labelService.saveNcData(data);
//        return JsonResponse.success();
//    }
    
    private float BigDecimal(String materialquantity) {
		// TODO Auto-generated method stub
		return 0;
	}

	/**
     * 修改标签备注
     * @param in
     * @return
     */
	@RequestMapping(value = "/updateRemark", method = RequestMethod.POST)
	public AjaxResult updateRemark(@RequestBody JSONObject in) {

		MaterialReceiveRequest sl = JSON.toJavaObject(in, MaterialReceiveRequest.class);
		String remark = sl.getRemark();
		String user = sl.getUser();
		List<MaterialPacking> boxList = sl.getBoxList();
		List<MaterialPackingKey> listKey = new ArrayList<MaterialPackingKey> ();
		for (MaterialPacking materialPacking : boxList) {
			MaterialPackingKey key = materialPacking.getKey();
			listKey.add(key);
		}
		EventInfo makeEventInfo = new EventInfoUtil().makeEventInfo("ModifiedPackingRemark", user, "ModifiedPackingRemark");
		SetEventInfo setEventInfo = new SetEventInfo();
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("remark", remark);
		setEventInfo.setUserColumns(hashMap);
		MaterialPackingServiceProxy.getMaterialPackingService().setEvent(listKey, makeEventInfo, setEventInfo);
	    return AjaxResult.me().setSuccess(true).setMessage("标签更新成功");
	}
	
	/**
     * 修改实际规格
     * @param in
     * @return
     */
	@RequestMapping(value = "/updateTruegg", method = RequestMethod.POST)
	public AjaxResult updateTruegg(@RequestBody JSONObject in) {

		MaterialReceiveRequest sl = JSON.toJavaObject(in, MaterialReceiveRequest.class);
		String truegg = sl.getTruegg();
		String user = sl.getUser();
		List<MaterialPacking> boxList = sl.getBoxList();
		List<MaterialPackingKey> listKey = new ArrayList<MaterialPackingKey> ();
		for (MaterialPacking materialPacking : boxList) {
			MaterialPackingKey key = materialPacking.getKey();
			listKey.add(key);
		}
		EventInfo makeEventInfo = new EventInfoUtil().makeEventInfo("ModifiedPackingTruegg", user, "ModifiedPackingTruegg");
		SetEventInfo setEventInfo = new SetEventInfo();
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("truegg", truegg);
		setEventInfo.setUserColumns(hashMap);
		MaterialPackingServiceProxy.getMaterialPackingService().setEvent(listKey, makeEventInfo, setEventInfo);
	    return AjaxResult.me().setSuccess(true).setMessage("实际规格更新成功");
	}
	//更新业助
	@RequestMapping(value = "/updateCareerAssistance", method = RequestMethod.POST)
	public AjaxResult updateCareerAssistance(@RequestBody JSONObject in) {	

		MaterialReceiveRequest sl = JSON.toJavaObject(in, MaterialReceiveRequest.class);
		List<MaterialPacking> boxList = sl.getBoxList();//CAREER_ASSISTANCE
		String user = sl.getUser();
		String siteName = sl.getSiteName();
		String career_ASSISTANCE = sl.getRemark();
		String CUSTOMNO = sl.getCUSTOMNO();
		String pc = "(";
		for (MaterialPacking materialPacking : boxList) {
			String career_ASSISTANCE2 = materialPacking.getCAREER_ASSISTANCE();
			String CUSTOMNO2 = materialPacking.getCUSTOMNO();
			String materialPackingName = materialPacking.getMaterialPackingName();
			pc += "'" + materialPackingName + "',";
			String materialspecname = materialPacking.getMaterialSpecName();
			String charge = materialPacking.getCharge();
			String phase = materialPacking.getPHASE();
//			SetEventInfo setEventInfo = new SetEventInfo();
			Map<String, Object> hashMap = new HashMap<String,Object> ();
//			hashMap.put("CAREER_ASSISTANCE", career_ASSISTANCE);
			if (career_ASSISTANCE2 != null &&  !"".equals(career_ASSISTANCE2)) {
				hashMap.put("CAREER_ASSISTANCE2", career_ASSISTANCE2);
			}
			if (CUSTOMNO2 != null &&  !"".equals(CUSTOMNO2)) {
				hashMap.put("CUSTOMNO2", CUSTOMNO2);
			}
			
			hashMap.put("SITENAME", siteName);
			hashMap.put("MATERIALPACKINGNAME", materialPackingName);
			hashMap.put("MATERIALSPECNAME", materialspecname);
			hashMap.put("CHARGE", charge);
			hashMap.put("PHASE", phase);
			hashMap.put("IS_CHECK", "N");
			hashMap.put("USERID", user);
			hashMap.put("CAREER_ASSISTANCE", career_ASSISTANCE);
			hashMap.put("CUSTOMNO", CUSTOMNO);
//			setEventInfo.setUserColumns(hashMap);
//			MaterialPackingKey mk = new MaterialPackingKey(siteName,materialPackingName);
//			EventInfo makeEventInfo = new EventInfoUtil().makeEventInfo("UpdateCareerAssistance", user, "UpdateCareerAssistance");
//			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mk, makeEventInfo, setEventInfo);
			
//			String yzSql = "SELECT * FROM USERINFO WHERE U.USERNAME = A.CAREER_ASSISTANCE";
			String yzSql = "SELECT U.USERNAME FROM USERINFO U WHERE  U.USERID = :USERID ";
			
			List<Map<String, Object>> userQueryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(yzSql, hashMap);
			
			
			if(Objects.isNull(userQueryForList) || userQueryForList.isEmpty() || userQueryForList.size() < 1) {
//				throw new RuntimeException("业助名称不正确或未注册");
				return AjaxResult.me().setSuccess(false).setMessage("业助名称不正确或未注册");
			}else {
				String userName = userQueryForList.get(0).get("USERNAME") == null ? "" : userQueryForList.get(0).get("USERNAME").toString();
				if ((career_ASSISTANCE2 != null || !"".equals(career_ASSISTANCE2)) &&  !userName.equals(career_ASSISTANCE2)) {
					return AjaxResult.me().setSuccess(false).setMessage("业助" + career_ASSISTANCE2 + "不能被修改");
				}
				if ((career_ASSISTANCE != null || !"".equals(career_ASSISTANCE)) &&  !userName.equals(career_ASSISTANCE)) {
					return AjaxResult.me().setSuccess(false).setMessage("业助" + career_ASSISTANCE + "不能被修改");
				}
			}
		}
		pc += "'')";
			
			String updateSql = "MERGE\r\n" + 
					"INTO\r\n" + 
					"	MATERIALPACKINGCHECK T\r\n" + 
					"		USING (\r\n" + 
					"	SELECT\r\n" + 
					"		*\r\n" + 
					"	FROM\r\n" + 
					"		MATERIALPACKING\r\n" + 
					"	WHERE\r\n" + 
					"		MATERIALPACKINGNAME IN " + pc +  " ) M " + 
					"ON\r\n" + 
					"	(T.MATERIALPACKINGNAME = M.MATERIALPACKINGNAME)\r\n" + 
					"	WHEN MATCHED THEN\r\n" + 
					"UPDATE\r\n" + 
					"SET\r\n" + 
					"	T.CAREER_ASSISTANCE = :CAREER_ASSISTANCE,\r\n" + 
					"	T.CUSTOMNO = :CUSTOMNO, T.IS_CHECK = 'N' \r\n" + 
					"	WHEN NOT MATCHED THEN\r\n" + 
					"INSERT\r\n" + 
					"	(SITENAME,\r\n" + 
					"	MATERIALPACKINGNAME,\r\n" + 
					"	MATERIALSPECNAME,\r\n" + 
					"	CHARGE,\r\n" + 
					"	PHASE,\r\n" + 
					"	IS_CHECK,\r\n" + 
					"	CAREER_ASSISTANCE,\r\n" + 
					"	CUSTOMNO)\r\n" + 
					"VALUES (M.SITENAME,\r\n" + 
					"M.MATERIALPACKINGNAME,\r\n" + 
					"M.MATERIALSPECNAME,\r\n" + 
					"M.CHARGE,\r\n" + 
					"M.PHASE,\r\n" + 
					"'N',\r\n" + 
					":CAREER_ASSISTANCE,\r\n" + 
					":CUSTOMNO)" ;

			Map<String, Object> map = new HashMap<String,Object> ();
			map.put("CAREER_ASSISTANCE", career_ASSISTANCE);
			map.put("CUSTOMNO", CUSTOMNO);
			IDMFrameServiceProxy.getSqlTemplate().update(updateSql, map);
			
		
		return AjaxResult.me().setSuccess(true).setMessage("业助更新成功");
	}

	@RequestMapping(value = "/checkMaterialPack", method = RequestMethod.POST)
	public BaseResponse<Map<String, Object>> checkMaterial(@RequestBody Map<String,Object> param){

		String siteName = (String)param.get("SITENAME");
		String materialpackingname = (String)param.get("MATERIALPACKINGNAME");
		String materialspecname = (String)param.get("MATERIALSPECNAME");
		String charge = (String)param.get("CHARGE");
		String career_assistance = (String)param.get("CAREER_ASSISTANCE");
		String customno = (String)param.get("CUSTOMNO");
		String user = (String)param.get("user");
		String is_check = (String)param.get("IS_CHECK");

		SetSpecEventInfo info = new SetSpecEventInfo();
		Map<String, Object> bindMap = new HashMap<String, Object>();

		bindMap.put("MATERIALPACKINGNAME", materialpackingname);
		bindMap.put("MATERIALSPECNAME", materialspecname);
		bindMap.put("CHARGE", charge);
		bindMap.put("IS_CHECK", is_check);

		String uptSql = "UPDATE\r\n" +
				"	MATERIALPACKINGCHECK mk\r\n" +
				"SET\r\n" +
				"	mk.IS_CHECK = :IS_CHECK \r\n" +
				"WHERE \r\n" +
				"	mk.MATERIALPACKINGNAME = :MATERIALPACKINGNAME\r\n" +
				"	AND mk.MATERIALSPECNAME = :MATERIALSPECNAME\r\n" +
				"	AND (mk.CHARGE = :CHARGE OR :CHARGE IS NULL)";

		IDMFrameServiceProxy.getSqlTemplate().update(uptSql, bindMap);

		Map<String, Object> bindMap2 = new HashMap<String, Object>();
		bindMap2.put("MATERIALPACKINGNAME", materialpackingname);
//		bindMap2.put("CHARGE", charge);
		bindMap2.put("CAREER_ASSISTANCE", career_assistance);
		bindMap2.put("CUSTOMNO", customno);
		SetEventInfo setEventInfo = new SetEventInfo();
		setEventInfo.setUserColumns(bindMap2);
		MaterialPackingKey mk = new MaterialPackingKey(siteName,materialpackingname);
		EventInfo makeEventInfo = new EventInfoUtil().makeEventInfo("UpdateCareerAssistance", user, "UpdateCareerAssistance");
		MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mk, makeEventInfo, setEventInfo);

		BaseResponse returnOK = RespGenerator.returnOK(param);
		return returnOK;

	}
	
	/**
	 * 查询规格
	 * @param in
	 * @return
	 */
	@RequestMapping(value = "/getSpecList", method = RequestMethod.POST)
	public AjaxResult getSpecList(@RequestBody JSONObject in ){
		SpecPartnumber spec = JSON.toJavaObject(in, SpecPartnumber.class);
		String materialSpecName = spec.getPRODUCTSPECNAME();
		//根据料号获取sdk规格信息
		if (materialSpecName == null || "".equals(materialSpecName)) {
			return AjaxResult.me().setSuccess(false).setMessage("料号获取sdk规格信息不能为空");
		}
		if (materialSpecName.startsWith("4")) {
			materialSpecName = "4";
		}
		String sql = " SELECT SDK_ID  as \"value\" ,SPECNAME  as \"text\" FROM SDK_SPEC ss WHERE ss.PARTNUMBER = :PARTNUMBER";
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("PARTNUMBER", materialSpecName);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
		return AjaxResult.me().setResultObj(queryForList);
	}
	
	/**
	 * 查询规格
	 * @param in
	 * @return
	 */
	@RequestMapping(value = "/labelMaterial", method = RequestMethod.POST)
	public AjaxResult labelMaterial(@RequestBody JSONObject in ){
		GetLabelMaterial labelMaterial = JSON.toJavaObject(in, GetLabelMaterial.class);
		String materialpackingname = labelMaterial.getMATERIALPACKINGNAME();
		String materialspecname = labelMaterial.getMATERIALSPECNAME();
		String sqlString = "SELECT m.MATERIALPACKINGNAME,m2.DESC_CN,m.TRUEGG,m.MATERIALQUANTITY "
				+ "FROM MATERIALPACKING m "
				+ "LEFT JOIN MATERIALSPEC m2 ON m.MATERIALSPECNAME = m2.MATERIALSPECNAME "
				+ "WHERE 1=1 "
				+ "AND m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME "
				+ "AND m.MATERIALSPECNAME = :MATERIALSPECNAME";
		HashMap<String,Object> hashMap = new HashMap<String, Object>();
		hashMap.put("MATERIALPACKINGNAME", materialpackingname);
		hashMap.put("MATERIALSPECNAME", materialspecname);
		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlString, hashMap);
		return AjaxResult.me().setResultObj(list);
	}
}