package com.uas.eis.serviceImpl;

import com.uas.eis.core.config.SpObserver;
import com.uas.eis.dao.BaseDao;
import com.uas.eis.dto.DataCenter;
import com.uas.eis.entity.ErrorMessage;
import com.uas.eis.exception.ApiSystemException;
import com.uas.eis.sdk.entity.ApiResult;
import com.uas.eis.sdk.resp.ApiResponse;
import com.uas.eis.service.MESDataService;
import com.uas.eis.utils.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

@Service
public class MESDataServiceImpl implements MESDataService {

	@Autowired
	private BaseDao baseDao;

	@Value("${spring.datasource.username}")
	private String username;

	@Override
	public List<Map<Object,Object>> snStepPass(String accessKey, String requestId, String data) {
		String AE_MASTER = checkAccessKey(accessKey, requestId);
		List<Map<Object, Object>> maps = BaseUtil.parseGridStoreToMaps(data);
		SpObserver.putSp(AE_MASTER);
		List<Map<Object, Object>> relist = new ArrayList<>();
		for (Map<Object, Object> map : maps) {
			Map<Object, Object> remap = new HashMap<>();
			String remark = "";
			int cn = baseDao.getJdbcTemplate().queryForObject("select count(1) from TEMP_STEPPASSED where sp_id=? and nvl(t_status,'W')='W' ",Integer.class,map.get("SP_ID"));
			remap.put("id",map.get("SP_ID"));
			if(cn>0){
				map.put("T_STATUS","D");
				map.put("T_REMAKR","重复");
				remark = "重复";
			}else{
				map.put("T_STATUS","W");
			}
			map.put("T_KEY",accessKey);
			map.put("T_INDATE", Timestamp.valueOf(DateUtil.currentDateString(Constant.YMD_HMS)));
			try {
				baseDao.execute(SqlUtil.getInsertSqlByMap(map,"TEMP_STEPPASSED"));
				remap.put("result","OK");
				remap.put("remark",remark);
			}catch (Exception e){
				remap.put("result","NG");
				remap.put("remark",e.getMessage());
				e.printStackTrace();
			}
			relist.add(remap);
		}
		//baseDao.execute(SqlUtil.getInsertSqlbyGridStore(maps, "TEMP_STEPPASSED"));
		//baseDao.execute("update temp_steppassed set t_status='D',T_REMAKR='重复' where t_id in (select t_id from (select temp_steppassed.*,row_number()over(partition by sp_id order by t_id desc) cn from temp_steppassed where nvl(t_status,'W')='W' ) where cn>1)");
		SpObserver.putSp(username);
		return relist;
	}

	@Override
	public List<Map<Object,Object>> snInfo(String accessKey, String requestId, String data) {
		String AE_MASTER = checkAccessKey(accessKey, requestId);
		List<Map<Object, Object>> maps = BaseUtil.parseGridStoreToMaps(data);
		SpObserver.putSp(AE_MASTER);
		List<Map<Object, Object>> relist = new ArrayList<>();
		for (Map<Object, Object> map : maps) {
			Map<Object, Object> remap = new HashMap<>();
			String remark = "";
			int cn = baseDao.getJdbcTemplate().queryForObject("select count(1) from TEMP_SNINFO where SI_ID=? and nvl(t_status,'W')='W' ",Integer.class,map.get("SI_ID"));
			remap.put("id",map.get("SI_ID"));
			if(cn>0){
				map.put("T_STATUS","D");
				map.put("T_REMAKR","重复");
				remark = "重复";
			}else{
				map.put("T_STATUS","W");
			}
			map.put("T_KEY",accessKey);
			map.put("T_INDATE", Timestamp.valueOf(DateUtil.currentDateString(Constant.YMD_HMS)));
			try {
				baseDao.execute(SqlUtil.getInsertSqlByMap(map,"TEMP_SNINFO"));
				remap.put("result","OK");
				remap.put("remark",remark);
			}catch (Exception e){
				remap.put("result","NG");
				remap.put("remark",e.getMessage());
				e.printStackTrace();
			}
			relist.add(remap);
		}
		SpObserver.putSp(username);
		return relist;
	}

	@Override
	public List<Map<Object,Object>> makeSnRelation(String accessKey, String requestId, String data) {
		String AE_MASTER = checkAccessKey(accessKey, requestId);
		List<Map<Object, Object>> maps = BaseUtil.parseGridStoreToMaps(data);
		SpObserver.putSp(AE_MASTER);
		List<Map<Object, Object>> relist = new ArrayList<>();
		for (Map<Object, Object> map : maps) {
			Map<Object, Object> remap = new HashMap<>();
			String remark = "";
			int cn = baseDao.getJdbcTemplate().queryForObject("select count(1) from TEMP_MAKESNRELATION where ID=? and nvl(t_status,'W')='W' ",Integer.class,map.get("ID"));
			remap.put("id",map.get("ID"));
			if(cn>0){
				map.put("T_STATUS","D");
				map.put("T_REMAKR","重复");
				remark = "重复";
			}else{
				map.put("T_STATUS","W");
			}
			map.put("T_KEY",accessKey);
			map.put("T_INDATE", Timestamp.valueOf(DateUtil.currentDateString(Constant.YMD_HMS)));
			try {
				baseDao.execute(SqlUtil.getInsertSqlByMap(map,"TEMP_MAKESNRELATION"));
				remap.put("result","OK");
				remap.put("remark",remark);
			}catch (Exception e){
				remap.put("result","NG");
				remap.put("remark",e.getMessage());
				e.printStackTrace();
			}
			relist.add(remap);
		}
		SpObserver.putSp(username);
		return relist;
	}

	@Override
	public List<Map<Object,Object>> MAKEBAD(String accessKey, String requestId, String data) {
		String AE_MASTER = checkAccessKey(accessKey, requestId);
		List<Map<Object, Object>> maps = BaseUtil.parseGridStoreToMaps(data);
		SpObserver.putSp(AE_MASTER);
		List<Map<Object, Object>> relist = new ArrayList<>();
		for (Map<Object, Object> map : maps) {
			Map<Object, Object> remap = new HashMap<>();
			String remark = "";
			int cn = baseDao.getJdbcTemplate().queryForObject("select count(1) from TEMP_MAKEBAD where MB_CODE=? and nvl(t_status,'W')='W' ",Integer.class,map.get("MB_CODE"));
			remap.put("id",map.get("MB_CODE"));
			if(cn>0){
				map.put("T_STATUS","D");
				map.put("T_REMAKR","重复");
				remark = "重复";
			}else{
				map.put("T_STATUS","W");
			}
			map.put("T_KEY",accessKey);
			map.put("T_INDATE", Timestamp.valueOf(DateUtil.currentDateString(Constant.YMD_HMS)));
			try {
				baseDao.execute(SqlUtil.getInsertSqlByMap(map,"TEMP_MAKEBAD"));
				remap.put("result","OK");
				remap.put("remark",remark);
			}catch (Exception e){
				remap.put("result","NG");
				remap.put("remark",e.getMessage());
				e.printStackTrace();
			}
			relist.add(remap);
		}
		SpObserver.putSp(username);
		return relist;
	}

	@Override
	public List<Map<Object,Object>> makeBadReason(String accessKey, String requestId, String data) {
		String AE_MASTER = checkAccessKey(accessKey, requestId);
		List<Map<Object, Object>> maps = BaseUtil.parseGridStoreToMaps(data);
		SpObserver.putSp(AE_MASTER);
		List<Map<Object, Object>> relist = new ArrayList<>();
		for (Map<Object, Object> map : maps) {
			Map<Object, Object> remap = new HashMap<>();
			String remark = "";
			int cn = baseDao.getJdbcTemplate().queryForObject("select count(1) from TEMP_MAKEBADREASON where MBR_ID=? and nvl(t_status,'W')='W' ",Integer.class,map.get("MBR_ID"));
			remap.put("id",map.get("MBR_ID"));
			if(cn>0){
				map.put("T_STATUS","D");
				map.put("T_REMAKR","重复");
				remark = "重复";
			}else{
				map.put("T_STATUS","W");
			}
			map.put("T_KEY",accessKey);
			map.put("T_INDATE", Timestamp.valueOf(DateUtil.currentDateString(Constant.YMD_HMS)));
			try {
				baseDao.execute(SqlUtil.getInsertSqlByMap(map,"TEMP_MAKEBADREASON"));
				remap.put("result","OK");
				remap.put("remark",remark);
			}catch (Exception e){
				remap.put("result","NG");
				remap.put("remark",e.getMessage());
				e.printStackTrace();
			}
			relist.add(remap);
		}
		SpObserver.putSp(username);
		return relist;
	}

	@Override
	public List<Map<Object,Object>> packageDetail(String accessKey, String requestId, String data) {
		String AE_MASTER = checkAccessKey(accessKey, requestId);
		List<Map<Object, Object>> maps = BaseUtil.parseGridStoreToMaps(data);
		SpObserver.putSp(AE_MASTER);
		List<Map<Object, Object>> relist = new ArrayList<>();
		for (Map<Object, Object> map : maps) {
			Map<Object, Object> remap = new HashMap<>();
			String remark = "";
			int cn = baseDao.getJdbcTemplate().queryForObject("select count(1) from TEMP_PACKAGEDETAIL where PD_ID=? and nvl(t_status,'W')='W' ",Integer.class,map.get("MBR_ID"));
			remap.put("id",map.get("PD_ID"));
			if(cn>0){
				map.put("T_STATUS","D");
				map.put("T_REMAKR","重复");
				remark = "重复";
			}else{
				map.put("T_STATUS","W");
			}
			map.put("T_KEY",accessKey);
			map.put("T_INDATE", Timestamp.valueOf(DateUtil.currentDateString(Constant.YMD_HMS)));
			try {
				baseDao.execute(SqlUtil.getInsertSqlByMap(map,"TEMP_PACKAGEDETAIL"));
				remap.put("result","OK");
				remap.put("remark",remark);
			}catch (Exception e){
				remap.put("result","NG");
				remap.put("remark",e.getMessage());
				e.printStackTrace();
			}
			relist.add(remap);
		}
		SpObserver.putSp(username);
		return relist;
	}

	@Override
	public List<Map<Object, Object>> craftmaterial(String accessKey, String requestId, String data) {
		String AE_MASTER = checkAccessKey(accessKey, requestId);
		List<Map<Object, Object>> maps = BaseUtil.parseGridStoreToMaps(data);
		SpObserver.putSp(AE_MASTER);
		List<Map<Object, Object>> relist = new ArrayList<>();
		for (Map<Object, Object> map : maps) {
			Map<Object, Object> remap = new HashMap<>();
			String remark = "";
			int cn = baseDao.getJdbcTemplate().queryForObject("select count(1) from TEMP_CRAFTMATERIAL where cm_id=? and nvl(t_status,'W')='W' ",Integer.class,map.get("cm_id"));
			remap.put("id",map.get("cm_id"));
			if(cn>0){
				map.put("T_STATUS","D");
				map.put("T_REMAKR","重复");
				remark = "重复";
			}else{
				map.put("T_STATUS","W");
			}
			map.put("T_KEY",accessKey);
			map.put("T_INDATE", Timestamp.valueOf(DateUtil.currentDateString(Constant.YMD_HMS)));
			try {
				baseDao.execute(SqlUtil.getInsertSqlByMap(map,"TEMP_CRAFTMATERIAL"));
				remap.put("result","OK");
				remap.put("remark",remark);
			}catch (Exception e){
				remap.put("result","NG");
				remap.put("remark",e.getMessage());
				e.printStackTrace();
			}
			relist.add(remap);
		}
		SpObserver.putSp(username);
		return relist;
	}

	@Override
	public List<Map<Object, Object>> oqcbatch(String accessKey, String requestId, String data) {
		String AE_MASTER = checkAccessKey(accessKey, requestId);
		List<Map<Object, Object>> maps = BaseUtil.parseGridStoreToMaps(data);
		SpObserver.putSp(AE_MASTER);
		List<Map<Object, Object>> relist = new ArrayList<>();
		for (Map<Object, Object> map : maps) {
			Map<Object, Object> remap = new HashMap<>();
			String remark = "";
			int cn = baseDao.getJdbcTemplate().queryForObject("select count(1) from TEMP_OQCBATCHDETAIL where obd_id=? and nvl(t_status,'W')='W' ",Integer.class,map.get("obd_id"));
			remap.put("id",map.get("obd_id"));
			if(cn>0){
				map.put("T_STATUS","D");
				map.put("T_REMAKR","重复");
				remark = "重复";
			}else{
				map.put("T_STATUS","W");
			}
			map.put("T_KEY",accessKey);
			map.put("T_INDATE", Timestamp.valueOf(DateUtil.currentDateString(Constant.YMD_HMS)));
			try {
				baseDao.execute(SqlUtil.getInsertSqlByMap(map,"TEMP_OQCBATCHDETAIL"));
				remap.put("result","OK");
				remap.put("remark",remark);
			}catch (Exception e){
				remap.put("result","NG");
				remap.put("remark",e.getMessage());
				e.printStackTrace();
			}
			relist.add(remap);
		}
		SpObserver.putSp(username);
		return relist;
	}

	@Override
	public List<Map<Object, Object>> inspectdata(String accessKey, String requestId, String data) {
		String AE_MASTER = checkAccessKey(accessKey, requestId);
		List<Map<Object, Object>> maps = BaseUtil.parseGridStoreToMaps(data);
		SpObserver.putSp(AE_MASTER);
		List<Map<Object, Object>> relist = new ArrayList<>();
		for (Map<Object, Object> map : maps) {
			Map<Object, Object> remap = new HashMap<>();
			String remark = "";
			int cn = baseDao.getJdbcTemplate().queryForObject("select count(1) from temp_inspectdata where id_id=? and nvl(t_status,'W')='W' ",Integer.class,map.get("id_id"));
			remap.put("id",map.get("id_id"));
			if(cn>0){
				map.put("T_STATUS","D");
				map.put("T_REMAKR","重复");
				remark = "重复";
			}else{
				map.put("T_STATUS","W");
			}
			map.put("T_KEY",accessKey);
			map.put("T_INDATE", Timestamp.valueOf(DateUtil.currentDateString(Constant.YMD_HMS)));
			try {
				baseDao.execute(SqlUtil.getInsertSqlByMap(map,"temp_inspectdata"));
				remap.put("result","OK");
				remap.put("remark",remark);
			}catch (Exception e){
				remap.put("result","NG");
				remap.put("remark",e.getMessage());
				e.printStackTrace();
			}
			relist.add(remap);
		}
		SpObserver.putSp(username);
		return relist;
	}

	@Override
	public List<Map<Object, Object>> prodiomac(String accessKey, String requestId, String data) {
		String AE_MASTER = checkAccessKey(accessKey, requestId);
		List<Map<Object, Object>> maps = BaseUtil.parseGridStoreToMaps(data);
		SpObserver.putSp(AE_MASTER);
		List<Map<Object, Object>> relist = new ArrayList<>();
		for (Map<Object, Object> map : maps) {
			Map<Object, Object> remap = new HashMap<>();
			String remark = "";
			int cn = baseDao.getJdbcTemplate().queryForObject("select count(1) from temp_prodiomac where pim_id=? and nvl(t_status,'W')='W' ",Integer.class,map.get("pim_id"));
			remap.put("id",map.get("pim_id"));
			if(cn>0){
				map.put("T_STATUS","D");
				map.put("T_REMAKR","重复");
				remark = "重复";
			}else{
				map.put("T_STATUS","W");
			}
			map.put("T_KEY",accessKey);
			map.put("T_INDATE", Timestamp.valueOf(DateUtil.currentDateString(Constant.YMD_HMS)));
			try {
				baseDao.execute(SqlUtil.getInsertSqlByMap(map,"temp_prodiomac"));
				remap.put("result","OK");
				remap.put("remark",remark);
			}catch (Exception e){
				remap.put("result","NG");
				remap.put("remark",e.getMessage());
				e.printStackTrace();
			}
			relist.add(remap);
		}
		SpObserver.putSp(username);
		return relist;
	}

	@Override
	public List<Map<Object, Object>> oqcitemsamples(String accessKey, String requestId, String data) {
		String AE_MASTER = checkAccessKey(accessKey, requestId);
		List<Map<Object, Object>> maps = BaseUtil.parseGridStoreToMaps(data);
		SpObserver.putSp(AE_MASTER);
		List<Map<Object, Object>> relist = new ArrayList<>();
		for (Map<Object, Object> map : maps) {
			Map<Object, Object> remap = new HashMap<>();
			String remark = "";
			int cn = baseDao.getJdbcTemplate().queryForObject("select count(1) from temp_oqcitemsamples where OIS_ID=? and nvl(t_status,'W')='W' ",Integer.class,map.get("OIS_ID"));
			remap.put("id",map.get("OIS_ID"));
			if(cn>0){
				map.put("T_STATUS","D");
				map.put("T_REMAKR","重复");
				remark = "重复";
			}else{
				map.put("T_STATUS","W");
			}
			map.put("T_KEY",accessKey);
			map.put("T_INDATE", Timestamp.valueOf(DateUtil.currentDateString(Constant.YMD_HMS)));
			try {
				baseDao.execute(SqlUtil.getInsertSqlByMap(map,"TEMP_OQCITEMSAMPLES"));
				remap.put("result","OK");
				remap.put("remark",remark);
			}catch (Exception e){
				remap.put("result","NG");
				remap.put("remark",e.getMessage());
				e.printStackTrace();
			}
			relist.add(remap);
		}
		SpObserver.putSp(username);
		return relist;
	}

	@Override
	public List<Map<Object, Object>> makeserial(String accessKey, String requestId, String data) {
		String AE_MASTER = checkAccessKey(accessKey, requestId);
		List<Map<Object, Object>> maps = BaseUtil.parseGridStoreToMaps(data);
		SpObserver.putSp(AE_MASTER);
		List<Map<Object, Object>> relist = new ArrayList<>();
		for (Map<Object, Object> map : maps) {
			Map<Object, Object> remap = new HashMap<>();
			String remark = "";
			int cn = baseDao.getJdbcTemplate().queryForObject("select count(1) from temp_makeserial where ms_id=? and nvl(t_status,'W')='W' ",Integer.class,map.get("ms_id"));
			remap.put("id",map.get("ms_id"));
			if(cn>0){
				map.put("T_STATUS","D");
				map.put("T_REMAKR","重复");
				remark = "重复";
			}else{
				map.put("T_STATUS","W");
			}
			map.put("T_KEY",accessKey);
			map.put("T_INDATE", Timestamp.valueOf(DateUtil.currentDateString(Constant.YMD_HMS)));
			try {
				baseDao.execute(SqlUtil.getInsertSqlByMap(map,"temp_makeserial"));
				remap.put("result","OK");
				remap.put("remark",remark);
			}catch (Exception e){
				remap.put("result","NG");
				remap.put("remark",e.getMessage());
				e.printStackTrace();
			}
			relist.add(remap);
		}
		SpObserver.putSp(username);
		return relist;
	}

	@Override
	public ApiResult<Map<Object,Object>> barcode(String accessKey, String requestId, String data) {
		String AE_MASTER = checkAccessKey(accessKey, requestId);
		SpObserver.putSp(AE_MASTER);
		Map<Object, Object> map = FlexJsonUtil.fromJson(data);
		try {
			if(!StringUtil.hasText(map.get("outno"))){
				return ApiResponse.failRsp(ErrorMessage.BUSINESS_ILLEGAL.getCode(),requestId,"传参异常，出库单号不能为空！");
			}
			if("ADD".equals(map.get("action"))){
				if(!StringUtil.hasText(map.get("barlist"))){
					return ApiResponse.failRsp(ErrorMessage.BUSINESS_ILLEGAL.getCode(),requestId,"传参操作类型:"+map.get("type")+"是写入，barlist 不允许为空");
				}
				List<Map<Object,Object>> barlist = (ArrayList)map.get("barlist");
				List<Map<Object,Object>> datab = new ArrayList<>();
				for(Map<Object,Object> mp : barlist){
					Map<Object,Object> mapb = new HashMap<>();
					mapb.put("ACTION","W");
					mapb.put("ERPID",mp.get("bar_id"));
					mapb.put("BAR_CODE",mp.get("bar_code"));
					mapb.put("BAR_PRODCODE",mp.get("bar_prodcode"));
					mapb.put("BAR_QTY",mp.get("bar_qty"));
					mapb.put("BAR_LOTNO",mp.get("bar_lotno"));
					mapb.put("BAR_DC",mp.get("bar_dc"));
					mapb.put("BAR_OUTNO",mp.get("bar_outno"));
					mapb.put("BAR_MACODE",mp.get("bar_macode"));
					mapb.put("BAR_BATCHQTY",mp.get("bar_batchqty"));
					datab.add(mapb);
				}
				baseDao.execute(SqlUtil.getInsertSqlbyGridStore(datab,"TEMP_BARCODE"));
			}else if("DEL".equals(map.get("action"))){
				Map<Object,Object> mapb = new HashMap<>();
				mapb.put("ACTION","D");
				mapb.put("ERPID",0);
				mapb.put("BAR_OUTNO",map.get("outno"));
				baseDao.execute(SqlUtil.getInsertSqlByMap(mapb,"TEMP_BARCODE"));
			}else{
				return ApiResponse.failRsp(ErrorMessage.BUSINESS_ILLEGAL.getCode(),requestId,"传参操作类型:"+map.get("action")+"错误，只能是ADD或者DEL");
			}
		}catch (Exception e){
			e.printStackTrace();
			if(e.getMessage().length() > 500) {
				return ApiResponse.failRsp(ErrorMessage.BUSINESS_ILLEGAL.getCode(), requestId, "异常错误，" + e.getMessage().substring(0, 500));
			}else{
				return ApiResponse.failRsp(ErrorMessage.BUSINESS_ILLEGAL.getCode(), requestId, "异常错误，" + e.getMessage());
			}
		}
		return ApiResponse.successRsp("0",requestId,"操作成功");

	}
	private String checkAccessKey(String accessKey,String requestId){
		Object accessSecret_O = baseDao.getFieldDataByCondition("APIEMPLOYEE", "AE_SECRET", "AE_KEY='"+accessKey+"'");
		Object AE_MASTER = baseDao.getFieldDataByCondition("APIEMPLOYEE", "AE_MASTER", "AE_KEY='"+accessKey+"'");
		String accessSecret = accessSecret_O == null ? "" : accessSecret_O.toString();
		// 检查KEY是否合理
		if (StringUtils.isEmpty(accessKey) || StringUtils.isEmpty(accessSecret) || AE_MASTER== null || "".equals(AE_MASTER.toString())) {
			ApiResult apiResult = new ApiResult();
			apiResult.setCode(ErrorMessage.ACCESSKEY_ILLEGAL.getCode());
			apiResult.setMessage(ErrorMessage.ACCESSKEY_ILLEGAL.getMessage());
			apiResult.setRequestId(requestId);
			throw new ApiSystemException(apiResult);
		}
		return AE_MASTER.toString();
	}

}
