package com.cim.idm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.cim.idm.exception.GlobalException;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.model.BaseEntity;
import com.cim.idm.model.StorageSpec;
import com.cim.idm.utils.AjaxResult;
import com.cim.idm.utils.CommonUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
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 java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.cim.idm.service.Impl.ERPLocationMoveNoInvoiceServiceImpl;

@Api("无单据库位移动接口")
@RestController
@RequestMapping("/api/location")
@EnableAutoConfiguration
public class ERPLocationMoveNoInvoiceController {

	@Autowired
	private ERPLocationMoveNoInvoiceServiceImpl ERPLocationMoveNoInvoiceServiceImpl;

	CommonUtils CU=new CommonUtils();

	@RequestMapping(value = "/AnalyStockBarCode", method = RequestMethod.POST)
	public AjaxResult AnalyStockBarCode(@RequestBody JSONObject in ){

		StorageSpec storageSpec = JSON.toJavaObject(in, StorageSpec.class);
		String erpFactory = storageSpec.getErpFactory();
		String erpLocation = storageSpec.getErpLocation();
		String storageName = storageSpec.getStorageName();
		String user = storageSpec.getUser();
		String materialPackingName = storageSpec.getMaterialPackingName();
		String materialspecname= storageSpec.getMATERIALSPECNAME();
		String substring = user.substring(0,1);
		String userID = user.substring(1);



		//判断条码是否存在且状态是在库
		String sql = "	SELECT\r\n" + 
				"	M.MATERIALPACKINGNAME,\r\n" + 
				"	M.CHARGE,\r\n" + 
				"	M2.DESC_CN ,\r\n" + 
				"	SS.SPECNAME ,\r\n" + 
				"	M.MATERIALQUANTITY ,\r\n" + 
				"	:ERPLOCATION  AIMERPLOCATION,\r\n" + 
				"	:ERPFACTORY   AIMERPFACTORY,\r\n" + 
				"	:LOCATIONNAME AIMLOCATIONNAME,\r\n" + 
				"	M.ERPLOCATION ,\r\n" + 
				"	M.ERPFACTORY ,\r\n" + 
				"	M.LOCATIONNAME ,"
				+ "M.MATERIALSPECNAME,M.PHASE,PACKINGGRADE, "
				+ "CASE\r\n" + 
				"		WHEN M.MATURATIONINTIME IS NOT NULL THEN SYSDATE - M.MATURATIONINTIME - NVL(m2.MATURATIONTIME,0)\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" + 
				"LEFT JOIN SDK_SPEC SS ON M.SDK_ID = SS.SDK_ID \r\n" + 
				"WHERE\r\n" + 
				"	M.MATERIALPACKINGNAME = :MATERIALPACKINGNAME\r\n" + 
				"	AND STOCKSTATE = 'Stocked' AND SHIPREQUESTNAME IS NULL";

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

		bindMap.put("MATERIALPACKINGNAME",materialPackingName); 
		bindMap.put("ERPFACTORY",erpFactory);
		bindMap.put("ERPLOCATION",erpLocation);
		bindMap.put("LOCATIONNAME",storageName);
		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 = CU.JudgeMtaerialStateWithERPLocation(erpLocation, packingGrade);
		if (!judgeMtaerialStateWithERPLocation) {
			throw new GlobalException("仓库类型和物料品质等级不一致");
		}
		if ("OK".equals(packingGrade) && ("1010".equals(erpFactory) || "1020".equals(erpFactory))) {
			//恒温恒湿管控
			if(!(CU.JudgeMentERPLocationAndMaterialSpec(erpLocation,materialspecname)))
			{
				throw new GlobalException("物料为:"+materialspecname+" 仓库为:"+erpLocation+" ,不符合恒温恒湿管理");
			}
		}

		if(erpLocation.equals(list.get(0).get("ERPLOCATION").toString())) {
			return AjaxResult.me().setSuccess(false).setMessage("相同仓库不能转入").setResultObj(null);
		} else if(!erpFactory.equals(list.get(0).get("ERPFACTORY").toString())) {
			return AjaxResult.me().setSuccess(false).setMessage("不同组织不能转入").setResultObj(null);
		}

		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("1".equals(substring)) {

				String sqlstrString = "SELECT DISTINCT OVEN_PERMISSIONS\r\n"
						+ "FROM USERINFO u \r\n"
						+ "LEFT JOIN USERGROUPLINK u2 ON u.USERID = u2.USERID\r\n"
						+ "LEFT JOIN USERGROUP u3 ON u2.USERGROUPNAME = u3.USERGROUPNAME\r\n"
						+ "WHERE u.USERID = :USERID";
				Map<String, Object> hashMap = new HashMap<String, Object>();
				hashMap.put("USERID",userID); 
				List<Map<String,Object>> queryForMap = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlstrString, hashMap);


				Integer i = 0;

				for (Map<String, Object> map : queryForMap) {
					if("1".equals(map.get("OVEN_PERMISSIONS").toString())) {
						i++;
					}
				}				
				if(i > 0) {
					return AjaxResult.me().setResultObj(list);
				} else {
					return AjaxResult.me().setSuccess(false).setMessage("权限不够").setResultObj(null);
				}

			}

			// 判断是否是熟化仓
			String erplocationSH = list.get(0).get("ERPLOCATION") == null ? "" : list.get(0).get("ERPLOCATION").toString();		
			String DetailSql2 = "SELECT IS_OVEN FROM BS_ERPLOCATION m WHERE ERPLOCATIONNAME =:ERPLOCATIONAMEE AND IS_OVEN='Y'";
			Map<String, Object> DetailMap2 = new HashMap<String, Object>();
			DetailMap2.put("ERPLOCATIONAMEE",erplocationSH); 
			List<Map<String,Object>>  ShipDetaillist2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(DetailSql2, DetailMap2);

			if (ShipDetaillist2.size() != 0 && parseFloat < 0) {
				//					throw new GlobalException("还差" + abs + "天才能熟化出库!");
				// 总分钟数  
				int totalMinutes = (int) (abs * 24 * 60);
				// 天数（总分钟数除以60再除以24）  
				int days = totalMinutes / (60 * 24); 
				// 剩余分钟数（总分钟数减去天数的分钟数）  
				int house = (totalMinutes - days * 24 * 60) / 60; 
				int minutes = totalMinutes - days * 24 * 60 - house * 60; 
				//				throw new GlobalException("烤箱还差" + days + "天" + house + "小时" + minutes + "分钟" + "才能熟化出库!");
				return AjaxResult.me().setSuccess(false).setMessage("烤箱还差" + days + "天" + house + "小时" + minutes + "分钟" + "才能熟化出库!").setResultObj(null);
			}
		}
		return AjaxResult.me().setResultObj(list);
	}



	@RequestMapping(value = "/CommitMove", method = RequestMethod.POST)
	public AjaxResult CommitMove(@RequestBody JSONObject in ) throws Exception{

		BaseEntity<StorageSpec> storageSpec = JSONObject.parseObject(in.toJSONString(),
				new TypeReference<BaseEntity<StorageSpec>>() {
		});
		List<StorageSpec> body = storageSpec.getBody();
		String user = storageSpec.getUser();
		String time = storageSpec.getTime();
		String opCode = storageSpec.getOpCode();
		ERPLocationMoveNoInvoiceServiceImpl.CommitMove(body,user,time,opCode);

		return AjaxResult.me().setResultObj(null);
	}
	
	@RequestMapping(value = "/CommitMove1", method = RequestMethod.POST)
	public AjaxResult CommitMove1(@RequestBody JSONObject in ) throws Exception{

		BaseEntity<StorageSpec> storageSpec = JSONObject.parseObject(in.toJSONString(),
				new TypeReference<BaseEntity<StorageSpec>>() {
		});
		List<StorageSpec> body = storageSpec.getBody();
		String user = storageSpec.getUser();
		String time = storageSpec.getTime();
		String opCode = storageSpec.getOpCode();
//		Map<String, List<StorageSpec>> collect = body.stream().collect(Collectors.groupingBy(StorageSpec::getErpLocation));
		
//		for (Map.Entry<String,List<StorageSpec>> entry : collect.entrySet()) {
//			String key = entry.getKey();
//			List<StorageSpec> val = entry.getValue();
//			ERPLocationMoveNoInvoiceServiceImpl.CommitMove(val,user,time,opCode);
//		}
        Function<StorageSpec, String> nonNullAimLocationName = spec -> spec.getAIMLOCATIONNAME() == null ? "" : spec.getAIMLOCATIONNAME();
		Map<String, Map<String, List<StorageSpec>>> collect = body.stream().collect(Collectors.groupingBy(StorageSpec::getErpLocation,Collectors.groupingBy(nonNullAimLocationName)));
		for (Entry<String, Map<String, List<StorageSpec>>> entry : collect.entrySet()) {
			String key = entry.getKey();
			Map<String, List<StorageSpec>> valueMap = entry.getValue();
			for (Entry<String, List<StorageSpec>> entrysList : valueMap.entrySet()) {
				List<StorageSpec> val = entrysList.getValue();
				for (int i = 0; i < val.size(); i++) {
					System.out.println(val.get(i).getCHARGE() + val.get(i).getAIMLOCATIONNAME());
				}
				ERPLocationMoveNoInvoiceServiceImpl.CommitMove(val,user,time,opCode);
			}
		}
		
		return AjaxResult.me().setResultObj(null);
	}
	
	//PC端无来源转库新增拆分
	@RequestMapping(value = "/CommitMove2", method = RequestMethod.POST)
	public AjaxResult CommitMove2(@RequestBody JSONObject in ) throws Exception{

		BaseEntity<StorageSpec> storageSpec = JSONObject.parseObject(in.toJSONString(),
				new TypeReference<BaseEntity<StorageSpec>>() {
		});
		List<StorageSpec> body = storageSpec.getBody();
		String user = storageSpec.getUser();
		String time = storageSpec.getTime();
		String opCode = storageSpec.getOpCode();
//		Map<String, List<StorageSpec>> collect = body.stream().collect(Collectors.groupingBy(StorageSpec::getErpLocation));
		
//		for (Map.Entry<String,List<StorageSpec>> entry : collect.entrySet()) {
//			String key = entry.getKey();
//			List<StorageSpec> val = entry.getValue();
//			ERPLocationMoveNoInvoiceServiceImpl.CommitMove(val,user,time,opCode);
//		}
        Function<StorageSpec, String> nonNullAimLocationName = spec -> spec.getAIMLOCATIONNAME() == null ? "" : spec.getAIMLOCATIONNAME();
		Map<String, Map<String, List<StorageSpec>>> collect = body.stream().collect(Collectors.groupingBy(StorageSpec::getErpLocation,Collectors.groupingBy(nonNullAimLocationName)));
		for (Entry<String, Map<String, List<StorageSpec>>> entry : collect.entrySet()) {
			String key = entry.getKey();
			Map<String, List<StorageSpec>> valueMap = entry.getValue();
			for (Entry<String, List<StorageSpec>> entrysList : valueMap.entrySet()) {
				List<StorageSpec> val = entrysList.getValue();
				for (int i = 0; i < val.size(); i++) {
					System.out.println(val.get(i).getCHARGE() + val.get(i).getAIMLOCATIONNAME());
				}
				ERPLocationMoveNoInvoiceServiceImpl.CommitMove1(val,user,time,opCode);
			}
		}
		
		return AjaxResult.me().setResultObj(null);
	}

}
