package com.cim.idm.controller;

import java.text.ParseException;

import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.cim.idm.exception.GlobalException;
import com.cim.idm.model.po.MaterialReceiveRequest;
import com.cim.idm.model.ShelfDto;
import com.cim.idm.utils.AjaxResult;
import com.cim.idm.utils.CommonUtils;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
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 com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cim.idm.framework.IDMFrameServiceProxy;

import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking;

import io.swagger.annotations.Api;


@Api("已批次管理入库")
@RestController
@RequestMapping("/api/NoInvoice")
@EnableAutoConfiguration
public class NoInvoiceManagerContoller {

//	@Autowired
//	NoInvoiceManagerServiceImpl NoInvoiceManagerServiceImpl;

	CommonUtils untils=new CommonUtils();
	/**
	 * 获取其他待入集合
	 * @param in
	 * @return
	 */
	@RequestMapping(value = "/getBarCode", method = RequestMethod.POST)
	public AjaxResult getQTRList(@RequestBody JSONObject in ){
		MaterialPacking m = JSON.toJavaObject(in, MaterialPacking.class);
		String materialPackingName = m.getMaterialPackingName();
		String locationName = m.getLocationName();
		String erpFactory = m.getErpFactory();
		String erpLocation = m.getErpLocation();
		String createUser = m.getCreateUser();
		String[] split = materialPackingName.split("\\|");
		// 470110856|1|C|75mm*1000m|SHBP01JT1202305240009|20230524|11|75
		String materialSpecName = split[0];
		String phase = split[2];
		String specName = split[3];
		String charge = split[4];
		String makeDate = split[5];
		String unit = split[6];
		String qty = split[7];
		//恒温恒湿管控

		if(!(untils.JudgeMentERPLocationAndMaterialSpec(erpLocation,materialSpecName)))
		{
			throw new GlobalException("物料为:"+materialSpecName+" 仓库为:"+erpLocation+" ,不符合恒温恒湿管理");
		}
		Map<String, Object> expridate = getExpridate(makeDate, materialSpecName);
		String sql = "SELECT STOCKSTATE, MAKEDATE, EXPIRINGDATE, CHARGE, MATERIALQUANTITY, ERPFACTORY,ERPLOCATION,SUPPLIERNAME,LOCATIONNAME,SDK_ID,PHASE,MATERIALSPECNAME FROM MATERIALPACKING WHERE ((MATERIALSPECNAME = :MATERIALSPECNAME AND CHARGE = :CHARGE) OR MATERIALPACKINGNAME = :MATERIALPACKINGNAME)  ";
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("MATERIALSPECNAME", materialSpecName);
		hashMap.put("CHARGE", charge);
		hashMap.put("MATERIALPACKINGNAME", materialPackingName);
		List<Map<String,Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
		if (queryForList == null || queryForList.size() < 1) {
			throw new GlobalException("录入批次系统未在系统流转");
		}
		if ("Stocked".equals(queryForList.get(0).get("STOCKSTATE").toString())) {
			throw new GlobalException("录入批次在库");
		}
		String packingGrade =  queryForList.get(0).get("OQARESULT") == null ? "" : queryForList.get(0).get("OQARESULT").toString();
		Boolean judgeMtaerialStateWithERPLocation = untils.JudgeMtaerialStateWithERPLocation(erpLocation, packingGrade);
		if (!judgeMtaerialStateWithERPLocation) {
			throw new GlobalException("仓库类型和物料品质等级不一致");
		}
		List<Map<String, Object>> arrayList = new ArrayList<Map<String,Object>> ();
		Map<String,Object> map = new HashMap<String,Object> ();
		map.put("MATERIALPACKINGNAME", materialPackingName);
		map.put("MATERIALSPECNAME", queryForList.get(0).get("MATERIALSPECNAME") == null ? "" : queryForList.get(0).get("MATERIALSPECNAME") .toString());
		map.put("CHARGE", queryForList.get(0).get("CHARGE") == null ? "" : queryForList.get(0).get("CHARGE") .toString());
		map.put("PHASE", phase);
		map.put("MATERIALQUANTITY", queryForList.get(0).get("MATERIALQUANTITY") == null ? "" : queryForList.get(0).get("MATERIALQUANTITY") .toString());
		map.put("SPECNAME", specName);
		map.put("LOCATIONNAME", locationName);
		map.put("ERPFACTORY", erpFactory);
		map.put("ERPLOCATION", erpLocation);
		map.put("SDK_ID", queryForList.get(0).get("SDK_ID") == null ? "" : queryForList.get(0).get("SDK_ID") .toString());
//		if (expridate != null) {
//			map.put("MAKEDATE", makeDate);
//			map.put("EXPRIDATE", expridate);
//		}
		map.put("MAKEDATE", queryForList.get(0).get("MAKEDATE") == null ? "" : queryForList.get(0).get("MAKEDATE") .toString());
		map.put("EXPIRINGDATE", queryForList.get(0).get("EXPIRINGDATE") == null ? "" : queryForList.get(0).get("EXPIRINGDATE") .toString());

		arrayList.add(map);
		return AjaxResult.me().setResultObj(arrayList);
	}


	/**
	 * 获取其他待出接口
	 * @param in
	 * @return
	 */
	@RequestMapping(value = "/getQTCList", method = RequestMethod.POST)
	public AjaxResult getQTCList(@RequestBody JSONObject in ){
		MaterialPacking materialPacking = JSON.toJavaObject(in, MaterialPacking.class);

		String sql = "SELECT\r\n" +
				"	M.*,\r\n" +
				"	CASE\r\n" +
				"		WHEN M.MATURATIONINTIME IS NOT NULL THEN SYSDATE - M.MATURATIONINTIME - m2.MATURATIONTIME\r\n" +
				"		ELSE 1\r\n" +
				"	END FLAG\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" +
				"	M.STOCKSTATE = 'Stocked'\r\n" +
				"	AND M.MATERIALPACKINGNAME = :MATERIALPACKINGNAME ";

		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("MATERIALPACKINGNAME", materialPacking.getMaterialPackingName());
		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);

		if(Objects.isNull(list) || list.isEmpty()) {
			throw new GlobalException("未找到对应的数据！");
		}

		if(!Objects.isNull(list) && !list.isEmpty()) {
			String string = list.get(0).get("FLAG").toString();
			float parseFloat = Float.parseFloat(string);
			float abs = Math.abs(parseFloat);
			if (parseFloat < 0) {
				throw new GlobalException("还差" + abs + "天才能熟化出库!");
			}
		}
		return AjaxResult.me().setResultObj(list);

	}


	/**
	 * 其他出提交
	 * @param in
	 * @return
	 */
	@RequestMapping(value = "/QTCCommit", method = RequestMethod.POST)
	public AjaxResult QTCCommit(@RequestBody JSONObject in ){
		//		List<MaterialPacking> object = (List<MaterialPacking>) in.get("boxList");
		MaterialReceiveRequest sl = JSON.toJavaObject(in, MaterialReceiveRequest.class);
		List<MaterialPacking> boxList = sl.getBoxList();
		String user2 = sl.getUser();
		String siteName = sl.getSiteName();
		String user = in.get("user").toString();
		String commitDatesString = sl.getCommitDate();
		String commitDate = commitDatesString + " 00:00:00";
		String opCode = sl.getOpCode();
		//		MaterialPacking selectByKey = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(new MaterialPackingKey("SDK", "311110026|1|C|75mm*1000m|3111100268001421|20230524|11|75"));
		//		ArrayList<MaterialPacking> arrayList = new ArrayList<>();
		//		arrayList.add(selectByKey);
//		NoInvoiceManagerServiceImpl.QTC(boxList,user,siteName,commitDate,opCode);

		return AjaxResult.me().setResultObj(null);

	}

	@RequestMapping(value = "/QTRCommit", method = RequestMethod.POST)
	public AjaxResult QTCRommit(@RequestBody JSONObject in ) throws ParseException{
		MaterialReceiveRequest sl = JSON.toJavaObject(in, MaterialReceiveRequest.class);
		String commitDateString = sl.getCommitDate();
		List<MaterialPacking> boxList = sl.getBoxList();
		String user2 = sl.getUser();
		String opCode = sl.getOpCode();
		//		ArrayList<MaterialPacking> arrayList = new ArrayList<>();
		//		arrayList.add(selectByKey);

		String commitDate = commitDateString + " 00:00:00";

//		NoInvoiceManagerServiceImpl.QTR(boxList,user2,commitDate,opCode);

		return AjaxResult.me().setResultObj(null);

	}

	@RequestMapping(value = "/getChangeLocationBarCode", method = RequestMethod.POST)
	public AjaxResult getChangeLocationBarCode(@RequestBody JSONObject in ){
		MaterialPacking m = JSON.toJavaObject(in, MaterialPacking.class);
		String materialPackingName = m.getMaterialPackingName();
		String locationName = m.getLocationName();
		String erpFactory = m.getErpFactory();
		String erpLocation = m.getErpLocation();
		String supplierCharge = m.getSupplierCharge();
		String createUser = m.getCreateUser();
		String[] split = materialPackingName.split("\\|");
		// 470110856|1|C|75mm*1000m|SHBP01JT1202305240009|20230524|11|75
		String materialSpecName = split[0];
		//		String phase = split[2];
		String specName = split[3];
		//		String charge = split[4];
		//		String makeDate = split[5];
		//		String unit = split[6];
		//		String qty = split[7];
		//        String  materialSpecName=m.getMaterialSpecName();

		if (erpFactory == null || "".equals(erpFactory)) {
			throw new GlobalException("组织不能为空！");
		}
		if (erpLocation == null || "".equals(erpLocation)) {
			throw new GlobalException("仓库不能为空！");
		}
		if (locationName == null || "".equals(locationName)) {
			throw new GlobalException("货位不能为空！");
		}
		//判断货位是否在同一个ERP组织下
		String sql = "SELECT PACKINGGRADE,CHARGE, MATERIALQUANTITY, ERPFACTORY,ERPLOCATION,SUPPLIERNAME,LOCATIONNAME,SDK_ID,PHASE,MATERIALSPECNAME FROM MATERIALPACKING M WHERE M.STOCKSTATE  = 'Stocked' AND M.MATERIALPACKINGNAME = :MATERIALPACKINGNAME ";
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("MATERIALPACKINGNAME", materialPackingName);
		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
		if(Objects.isNull(list) || list.isEmpty()) {
			throw new GlobalException("未找到对应的数据！该标签为空或者不为在库状态");
		}
		// 良品与不良品与仓校验
		String packingGrade = list.get(0).get("PACKINGGRADE") == null ? "" : list.get(0).get("PACKINGGRADE").toString();
		Boolean judgeMtaerialStateWithERPLocation = untils.JudgeMtaerialStateWithERPLocation(erpLocation, packingGrade);
		if (!judgeMtaerialStateWithERPLocation) {
			throw new GlobalException("仓库类型和物料品质等级不一致");
		}
		if ("101".equals(erpFactory) || "102".equals(erpFactory)) {
			if ("OK".equals(packingGrade)) {
				//恒温恒湿管控
				if (!(untils.JudgeMentERPLocationAndMaterialSpec(erpLocation, materialSpecName))) {
					throw new GlobalException("物料为:" + materialSpecName + " 仓库为:" + erpLocation + " ,不符合恒温恒湿管理");
				}
			}
		}
		//判断是否需要绑定供应商
		String SupSql="SELECT ASSFLAG FROM SUPPLIER s WHERE  SUPPLIERNO =:SUPPLIERNO";
		Map<String, Object> bindMap2 = new HashMap<String, Object>();
		bindMap2.put("SUPPLIERNO", list.get(0).get("SUPPLIERNAME") == null ? "" : list.get(0).get("SUPPLIERNAME").toString());
		List<Map<String,Object>> list2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(SupSql, bindMap2);

		if (list2 == null || list2.size() < 1) {

		} else {
			String flag = list2.get(0).get("ASSFLAG") == null ? "N" : list2.get(0).get("ASSFLAG").toString();
			if("Y".equals(flag) && ("".equals(supplierCharge) || supplierCharge == null ))
			{
				throw new GlobalException("需要绑定供应商批次！");
			}
		}

		if (!erpFactory.equals(list.get(0).get("ERPFACTORY").toString())  || !erpLocation.equals(list.get(0).get("ERPLOCATION").toString()) ) {
			throw new GlobalException("目标仓库与组织与原库存不一致！组织:"+erpFactory+"库存组织:"+list.get(0).get("ERPFACTORY")+"仓库:"+erpLocation+"目标仓库:"+list.get(0).get("ERPLOCATION"));
		}
		String preLocation = list.get(0).get("LOCATIONNAME") == null ? "" : list.get(0).get("LOCATIONNAME").toString();
		if (list.get(0).get("LOCATIONNAME") != null && locationName.equals(preLocation) ) {
			throw new GlobalException("货位一致不需要调整");
		}
		List<Map<String, Object>> arrayList = new ArrayList<Map<String,Object>> ();
		Map<String,Object> map = new HashMap<String,Object> ();
		map.put("MATERIALPACKINGNAME", materialPackingName);
		map.put("MATERIALSPECNAME", list.get(0).get("MATERIALSPECNAME"));
		map.put("CHARGE", list.get(0).get("CHARGE"));
		map.put("PHASE", list.get(0).get("PHASE"));
		map.put("SUPPLIERCHARGE", supplierCharge);
		map.put("MATERIALQUANTITY", list.get(0).get("MATERIALQUANTITY"));
		map.put("SPECNAME", specName);
		map.put("LOCATIONNAME", locationName);
		map.put("PRELOCATIONNAME", preLocation);
		map.put("ERPFACTORY", erpFactory);
		map.put("ERPLOCATION", erpLocation);
		//		map.put("SUPPLIERCHARGE", supplierCharge);
		map.put("SDK_ID", list.get(0).get("SDK_ID") == null ? "" : list.get(0).get("SDK_ID").toString());
		arrayList.add(map);
		return AjaxResult.me().setResultObj(arrayList);
	}

	@RequestMapping(value = "/getSupplierChargeByPakingname", method = RequestMethod.POST)
	public AjaxResult getSupplierChargeByPakingname(@RequestBody JSONObject in ){
		MaterialPacking m = JSON.toJavaObject(in, MaterialPacking.class);
		String materialPackingName = m.getMaterialPackingName();
		String siteName = "SDK";
		String sql = "SELECT\n" +
				"\tm.MATERIALPACKINGNAME ,\n" +
				"\tm.SUPPLIERCHARGE\n" +
				"FROM\n" +
				"\tMATERIALPACKING m\n" +
				"WHERE\n" +
				"\tm.MATERIALPACKINGNAME = :MATERIALPACKINGNAME\n" +
				"\tAND m.SITENAME = :SITENAME";
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("MATERIALPACKINGNAME", materialPackingName);
		bindMap.put("SITENAME", siteName);
		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
		String supplierCharge = "";
		if(list != null && list.size() > 0){
			for(Map<String,Object> map : list) {
				supplierCharge = map.get("SUPPLIERCHARGE") == null ? "" : map.get("SUPPLIERCHARGE").toString();
				if(supplierCharge == null) {
					return AjaxResult.me().setSuccess(false).setMessage("当前批次之前未绑定供应商批次，请确认");
				}
			}
		} else {
			return AjaxResult.me().setSuccess(false).setMessage("条码不存在");
		}
		List<Map<String, Object>> arrayList = new ArrayList<Map<String,Object>> ();
		Map<String,Object> map = new HashMap<String,Object> ();
		map.put("MATERIALPACKINGNAME", materialPackingName);
		map.put("SUPPLIERCHARGE", supplierCharge);
		arrayList.add(map);
		return AjaxResult.me().setSuccess(true).setResultObj(arrayList);
	}

	/**
	 * 货位移动
	 * @param in
	 * @return
	 */
	@RequestMapping(value = "/ChangeLocation", method = RequestMethod.POST)
	public AjaxResult ChangeLocation(@RequestBody JSONObject in ){
		//		com.zxy.idm.wms.solution.model.MaterialPacking materialPacking = JSON.toJavaObject(in, ShelfDto.class);
		ShelfDto ShelfDto = JSON.toJavaObject(in, ShelfDto.class);
		String siteName = ShelfDto.getSiteName();
		String user = ShelfDto.getUser();
		String commitDateString = ShelfDto.getCommitDate();
		String opCode = ShelfDto.getOpCode();
		String commitDate = commitDateString + " 00:00:00";
		//		List<MaterialPackingKey> list1 = new ArrayList<> ();
		//		for (MaterialPacking materialPacking : ShelfDto.getBoxList()) {
		//			MaterialPackingKey materialPackingKey;
		//			materialPackingKey =  new MaterialPackingKey();
		//			materialPackingKey.setSiteName(siteName);
		//			materialPackingKey.setMaterialPackingName(materialPacking.getMaterialPackingName());
		//			list1.add(materialPackingKey);
		//		}
		//		 List<MaterialPacking> selectByKey = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(list1);
		//		ArrayList<MaterialPacking> arrayList = new ArrayList<>();
		//		arrayList.add(selectByKey);
//		NoInvoiceManagerServiceImpl.PDAShelf(ShelfDto.getBoxList(),user,commitDate,opCode);

		//		String  SelectSql="SELECT m.MATERIALSPECNAME ,m2.DESC_CN ,m2.DESCRIPTION ,m.PHASE,m.CHARGE,m.MATERIALQUANTITY  FROM MATERIALPACKING m LEFT JOIN MATERIALSPEC m2 ON m.MATERIALSPECNAME =m2.MATERIALSPECNAME  WHERE m.MATERIALPACKINGNAME =:MATERIALPACKINGNAME";
		//		Map<String, Object> bindMap3 = new HashMap<String, Object>();
		//		bindMap3.put("MATERIALPACKINGNAME", materialPackingName);
		//		List<Map<String,Object>> list3 = IDMFrameServiceProxy.getSqlTemplate().queryForList(SelectSql, bindMap3);
		return AjaxResult.me().setResultObj(null);

	}


	/**
	 * 批次换绑供应商批次
	 */
	@RequestMapping(value = "/ChangeSupplierCharge", method = RequestMethod.POST)
	public AjaxResult ChangeSupplierCharge(@RequestBody JSONObject in ){
		ShelfDto ShelfDto = JSON.toJavaObject(in, ShelfDto.class);
		String user = ShelfDto.getUser();
//		NoInvoiceManagerServiceImpl.ChangeChargeName(ShelfDto.getBoxList(),user);
		return AjaxResult.me().setResultObj(null);
	}

	public static Map<String,Object> getExpridate(String makeDate,String materialSpecName) {
		String sql = "SELECT TO_TIMESTAMP(:MAKEDATE,'YYYYMMDD') MAKEDATE,  NVL(T.EXPIRATIONDAY,180) +   TO_TIMESTAMP(:MAKEDATE,'YYYYMMDD') EXP FROM MATERIALSPEC T WHERE T.MATERIALSPECNAME = :MATERIALSPECNAME";

		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("MATERIALSPECNAME", materialSpecName);
		hashMap.put("MAKEDATE", makeDate);
		List<Map<String,Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);

		if (queryForList != null && queryForList.size() > 0) {
			HashMap<String, Object> hashMap2 = new HashMap<String, Object> ();
			hashMap2.put("MAKEDATE", queryForList.get(0).get("MAKEDATE"));
			hashMap2.put("EXP", queryForList.get(0).get("EXP"));
			return new HashMap<String, Object> ();
		}
		return null;
	}
}
