package com.sw.mes.mmcs.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import com.sw.mes.base.factory.material.entity.MaterialModel;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.entity.SysLog;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.system.service.SysLogService;
import com.sw.mes.core.utils.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.utils.IpUtils;
import com.sw.mes.core.utils.StringUtils;

import com.sw.mes.mmcs.dto.CancelMoDistributionDto;
import com.sw.mes.mmcs.dto.ErrorOrderDto;
import com.sw.mes.mmcs.dto.IssueMoDto;
import com.sw.mes.mmcs.dto.IssueWeightSchemeDto;
import com.sw.mes.mmcs.dto.MaterialDto;
import com.sw.mes.mmcs.dto.McsMaterialNumberDto;
import com.sw.mes.mmcs.dto.McsProductionCircleRecipeDto;
import com.sw.mes.mmcs.dto.McsReturnResult;
import com.sw.mes.mmcs.dto.MoWorkReportingDto;
import com.sw.mes.mmcs.service.MMcsInterfaceService;
import com.sw.mes.utils.MMCSHttpUtil;
import com.sw.mes.webservice.entity.MaterialNumberOutPut;
import com.sw.mes.yb.production.dto.ProductionCircleRecipeDetailVo;
import com.sw.mes.yb.production.dto.ProductionCircleWeightDtoVo;
import com.sw.mes.yb.production.dto.AgainTask.AgainTaskDto;
import com.sw.mes.yb.production.entity.AgainTask;
import com.sw.mes.yb.production.entity.AgainTaskDetail;
import com.sw.mes.yb.production.entity.BlastFurnaceDetail;
import com.sw.mes.yb.production.entity.InputFurnaceBurden;
import com.sw.mes.yb.production.entity.InputFurnaceDetail;
import com.sw.mes.yb.production.entity.LoadingTask;
import com.sw.mes.yb.production.entity.ProductionCircleRecipe;
import com.sw.mes.yb.production.entity.ProductionCircleRecipeDetail;
import com.sw.mes.yb.production.entity.ProductionCircleWeight;
import com.sw.mes.yb.production.entity.ProductionCircleWeightDetail;
import com.sw.mes.yb.production.service.AgainTaskDetailService;
import com.sw.mes.yb.production.service.AgainTaskService;
import com.sw.mes.yb.production.service.BlastFurnaceDetailService;
import com.sw.mes.yb.production.service.InputFurnaceBurdenService;
import com.sw.mes.yb.production.service.InputFurnaceDetailService;
import com.sw.mes.yb.production.service.LoadingTaskService;
import com.sw.mes.yb.production.service.ProductionCircleRecipeDetailService;
import com.sw.mes.yb.production.service.ProductionCircleRecipeService;
import com.sw.mes.yb.production.service.ProductionCircleWeightDetailService;
import com.sw.mes.yb.production.service.ProductionCircleWeightService;

@Service
public class MMcsInterfaceServiceImpl implements MMcsInterfaceService {

	@Autowired
	private DictionaryItemService dictionaryItemService;

	@Autowired
	private SysLogService sysLogService;

	@Autowired
	private ProductionCircleRecipeService productionCircleRecipeService;

	@Autowired
	private ProductionCircleRecipeDetailService productionCircleRecipeDetailService;

	@Autowired
	private ProductionCircleWeightService productionCircleWeightService;
	@Autowired
	private ProductionCircleWeightDetailService productionCircleWeightDetailService;
	@Autowired
	private BlastFurnaceDetailService blastFurnaceDetailService;

	@Autowired
	private LoadingTaskService loadingTaskService;
	@Autowired
	private AgainTaskService againTaskService;
	@Autowired
	private MaterialModelService materialModelService;
	@Autowired
	private AgainTaskDetailService againTaskDetailService;
	@Autowired
	private InputFurnaceBurdenService inputFurnaceBurdenService;
	@Autowired
	private InputFurnaceDetailService inputFurnaceDetailService;


	private static List<String> filterMaterialOutteamNo = new ArrayList<String>();
	static {
		filterMaterialOutteamNo.add("A01");
		filterMaterialOutteamNo.add("A02");
		filterMaterialOutteamNo.add("A03");
		filterMaterialOutteamNo.add("A04");
	}


	@Override
	@Async
	public void mcsMaterialToMmcs(List<MaterialNumberOutPut> source) {
		try {
			// 字典中配置的 MMCS url前缀
			DictionaryItem dic = dictionaryItemService.findByThemeValueAndNameAndEnable("MMCSApi", "MMCSBASEURL", true);

			if (dic == null) {
				return;
			}

			List<McsMaterialNumberDto> dtos = new ArrayList<McsMaterialNumberDto>();
			for (MaterialNumberOutPut materialNumberOutPut : source) {
				McsMaterialNumberDto dto = new McsMaterialNumberDto();
				BeanUtil.copyProperties(materialNumberOutPut, dto);

				if(dto.getLVORM()==null || !dto.getLVORM().equals("X")) {
					dto.setLVORM("0");
				}else {
					dto.setLVORM("1");
				}

				//冻结转删除状态
				if(materialNumberOutPut.getMSTAE()!=null && (materialNumberOutPut.getMSTAE().equals("01") || materialNumberOutPut.getMSTAE().equals("03"))) {
					dto.setLVORM("1");
				}


				//过滤需要物料类型
				if(filterMaterialOutteamNo.contains(dto.getEXTWG()))
					dtos.add(dto);
			}

			McsReturnResult result = MMCSHttpUtil.post(dic.getValue() + "/mes/api/mcsMaterialToMmcs", dtos, 30000);

			try {
				SysLog syslog = new SysLog();
				syslog.setCreateTime(new Date());
				syslog.setType("info");
				syslog.setCreateUserId(BaseContextHandler.getUserID());
				syslog.setCreateUserName("MMCS");
				syslog.setContent(JSON.toJSONString(dtos));
				syslog.setResult(JSON.toJSONString(result));
				syslog.setCreateUserId(-1);
				syslog.setMethodName("mcsMaterialToMmcs()");
				syslog.setStatus(1);
				syslog.setName("MES->MMCS同步物料信息接口");
				String serverAddr = dic.getValue() + "/mes/api/mcsMaterialToMmcs";
				syslog.setServerAddr(serverAddr);
				syslog.setReqType("HTTP");
				syslog.setReqIp(IpUtils.getLocalIP());
				sysLogService.save(syslog);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
		}
	}



	@Override
	@Async
	public void mcsRecipeToMmcs() {
		try {
			// 字典中配置的 MMCS url前缀
			DictionaryItem dic = dictionaryItemService.findByThemeValueAndNameAndEnable("MMCSApi", "MMCSBASEURL", true);
			if (dic == null) {
				return;
			}
			//查询所有配方
			List<ProductionCircleRecipe> recipes = productionCircleRecipeService.findAll();
			List<McsProductionCircleRecipeDto> dtos = new ArrayList<McsProductionCircleRecipeDto>();
			for (ProductionCircleRecipe productionCircleRecipe : recipes) {


				List<ProductionCircleRecipeDetailVo> map = productionCircleRecipeDetailService.getRecipeDetailById(productionCircleRecipe.getId(),null);

				for (ProductionCircleRecipeDetailVo productionCircleRecipeDetailVo : map) {

					//配方类型
					String recipePurpose = productionCircleRecipeDetailVo.getRecipePurpose();
					String formulaType = null;
					if(recipePurpose.equals("csft")) {
						formulaType = "1";
					}else if(recipePurpose.equals("cszl")) {
						formulaType = "0";
					}else if(recipePurpose.equals("qdft")) {
						formulaType = "2";
					}else {
						continue;
					}


					Map<String,Object> kinds = (Map<String, Object>) productionCircleRecipeDetailVo.getKind();
					for (Iterator iterator = kinds.keySet().iterator(); iterator.hasNext();) {
						String key = (String) iterator.next();

						List<ProductionCircleRecipeDetail> details = (List<ProductionCircleRecipeDetail>) kinds.get(key);

						for (ProductionCircleRecipeDetail value : details) {
							if(value==null)continue;

							McsProductionCircleRecipeDto dto = new McsProductionCircleRecipeDto();
							dto.setFormulaNo(productionCircleRecipe.getId()+"");
							dto.setFormulaName(productionCircleRecipe.getRecipeName());
							dto.setProduct_seriesfurnaceSeries("以排产炉台系列为准");
							dto.setCreateBy(productionCircleRecipe.getUserName());
							dto.setCreateTime(productionCircleRecipe.getCreateTime());

							//配方类型
							dto.setFormulaType(formulaType);

							String formulaVariety = null;
							if(key.equals("ddl")) {
								formulaVariety = "打底料";
							}else if(key.equals("dj")) {
								formulaVariety = "多晶料";
							}else if(key.equals("hsl")) {
								formulaVariety = "回收料";
							}else if(key.equals("sygg")) {
								formulaVariety = "坩埚";
							}else if(key.equals("xzl")) {
								formulaVariety = "小规格料";
							}else {
								continue;
							}

							dto.setFormulaVariety(formulaVariety);

							dto.setDiameter(convertBigDecimal(value.getSuppliesSize()));
							dto.setHeight(convertBigDecimal(value.getSuppliesHeight()));
							dto.setPriority(convertBigDecimal(value.getPriority()));
							dto.setBrand(value.getSuppliesBrand());
							dto.setTechnologyRequirements(value.getSuppliesCraft());
							dto.setMaterialTeamNo(value.getSuppliesCode());
							dto.setMaterialTeamName(value.getSuppliesName());
							dto.setMaterialForm(value.getSuppliesType());
							dto.setDopant(value.getSuppliesDopant());
							dto.setGrainsizeBegin(convertBigDecimal(value.getSuppliesGrainMin()));
							dto.setGrainsizeEnd(convertBigDecimal(value.getSuppliesGrainMax()));
							dto.setResistanceBegin(convertBigDecimal(value.getSuppliesResistanceMin()));
							dto.setResistanceEnd(convertBigDecimal(value.getSuppliesResistanceMax()));

							dtos.add(dto);
						}
					}

				}


			}




			McsReturnResult result = MMCSHttpUtil.post(dic.getValue() + "/mes/api/issueMaterialFormulaInterface", dtos, 30000);

			try {
				SysLog syslog = new SysLog();
				syslog.setCreateTime(new Date());
				syslog.setType("info");
				syslog.setCreateUserId(BaseContextHandler.getUserID());
				syslog.setCreateUserName("MMCS");
				syslog.setContent(JSON.toJSONString(dtos));
				syslog.setResult(JSON.toJSONString(result));
				syslog.setCreateUserId(-1);
				syslog.setMethodName("mcsRecipeToMmcs()");
				syslog.setStatus(1);
				syslog.setName("MES->MMCS下发物料配方接口");
				String serverAddr = dic.getValue() + "/mes/api/issueMaterialFormulaInterface";
				syslog.setServerAddr(serverAddr);
				syslog.setReqType("HTTP");
				syslog.setReqIp(IpUtils.getLocalIP());
				sysLogService.save(syslog);
			} catch (Exception e) {
				e.printStackTrace();
			}



		} catch (Exception e) {
		}
	}


	@Override
	@Async
	public void issueWeightSchemeInterface() {
		try {
			// 字典中配置的 MMCS url前缀
			DictionaryItem dic = dictionaryItemService.findByThemeValueAndNameAndEnable("MMCSApi", "MMCSBASEURL", true);
			if (dic == null) {
				return;
			}

			List<IssueWeightSchemeDto> dtos = new ArrayList<IssueWeightSchemeDto>();
			List<ProductionCircleWeight> weights = productionCircleWeightService.findAll();

			for (ProductionCircleWeight w : weights) {
				List<ProductionCircleWeightDtoVo> details = productionCircleWeightDetailService.getRecipeWeightDetail(w.getWeightName(),w.getWeightCode(),w.getVersion());
				for (ProductionCircleWeightDtoVo d : details) {
					String recipePurpose = d.getRecipePurpose();
					Map<String, List<ProductionCircleWeightDetail>> kind = (Map<String, List<ProductionCircleWeightDetail>>) d.getKind();
					String[] rps = recipePurpose.split(",");

					for (String r : rps) {
						IssueWeightSchemeDto dto = new IssueWeightSchemeDto();
						dto.setSchemeNo(w.getId()+"");
						dto.setSchemeName(w.getWeightName());

						if(r.contains("cszl"))
							dto.setFormulaType("0");
						else if(r.contains("csft")) {
							dto.setFormulaType("1");
						}else if(r.contains("qdft")) {
							dto.setFormulaType("2");
						}

						dto.setCreateBy(w.getUserName());
						dto.setCreateTime(w.getCreateTime());

						for (Iterator iterator = kind.keySet().iterator(); iterator.hasNext();) {
							String key = (String) iterator.next();
							List<ProductionCircleWeightDetail> infos = kind.get(key);

							if(key.equals("0"))
								continue;

							for (ProductionCircleWeightDetail _detail : infos) {
								//TODO 实际业务要修改
//								if(_detail.getRecipeKind().equals("ddl")) {//打底料
//									dto.setBottomingWeight(convertBigDecimal(_detail.getWeight()));
//								}else if(_detail.getRecipeKind().equals("dj")) {//多晶
//									dto.setPolycrystalWeight(convertBigDecimal(_detail.getWeight()));
//								}else if(_detail.getRecipeKind().equals("hsl")) {//回收料
//									dto.setMonocrystalWeight(convertBigDecimal(_detail.getWeight()));
//								}else if(_detail.getRecipeKind().equals("xzl")) {//小种类
//									dto.setSmallsizeWeight(convertBigDecimal(_detail.getWeight()));
//								}
//
//								//重复设置 没关系
//								dto.setTotalWeight(convertBigDecimal(_detail.getGross()));
							}
						}

						dtos.add(dto);
					}
				}
			}




			McsReturnResult result = MMCSHttpUtil.post(dic.getValue() + "/mes/api/issueWeightSchemeInterface", dtos, 30000);

			try {
				SysLog syslog = new SysLog();
				syslog.setCreateTime(new Date());
				syslog.setType("info");
				syslog.setCreateUserId(BaseContextHandler.getUserID());
				syslog.setCreateUserName("MMCS");
				syslog.setContent(JSON.toJSONString(dtos));
				syslog.setResult(JSON.toJSONString(result));
				syslog.setCreateUserId(-1);
				syslog.setMethodName("issueWeightSchemeInterface()");
				syslog.setStatus(1);
				syslog.setName("MES->MMCS下发重量方案接口");
				String serverAddr = dic.getValue() + "/mes/api/issueWeightSchemeInterface";
				syslog.setServerAddr(serverAddr);
				syslog.setReqType("HTTP");
				syslog.setReqIp(IpUtils.getLocalIP());
				sysLogService.save(syslog);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}catch (Exception e) {
		}
	}

	@Override
	@Async
	public void issueMoInterface(Object obj) {
		try {
			// 字典中配置的 MMCS url前缀
			DictionaryItem dic = dictionaryItemService.findByThemeValueAndNameAndEnable("MMCSApi", "MMCSBASEURL", true);
			if (dic == null) {
				return;
			}

			if(obj instanceof LoadingTask) {//装料任务
				IssueMoDto dto = new IssueMoDto();
				LoadingTask task = (LoadingTask)obj;
				dto.setOrderNo("0-"+task.getId());
				dto.setOrderName(task.getEquipmentCode()+"-"+task.getLotNo());
				dto.setOrderType(0+"");
				dto.setCreateBy(task.getUserName());
				dto.setCreateTime(task.getGmtCreate());
				dto.setFormulaNo(task.getRecipeId()+"");
				dto.setSchemeNo(task.getWeigthId()+"");
				dto.setModuleNo(task.getArea());
				dto.setFurnaceSeries(task.getSeries());
				dto.setFurnaceNo(task.getEquipmentCode());
				dto.setPriority(convertBigDecimal(20));
				dto.setMonocrystalTime(task.getEtTime());
				//dto.setWeight(task.getWeight()!=null?task.getWeight():null);

				try {
					List<ProductionCircleWeightDtoVo> weightDtoVos = productionCircleWeightDetailService.getRecipeWeightDetailById(task.getWeigthId());
					if(weightDtoVos!=null) {
						for (ProductionCircleWeightDtoVo productionCircleWeightDtoVo : weightDtoVos) {
							if(productionCircleWeightDtoVo.getRecipePurpose().contains("cszl")) {
								Map<String, List<ProductionCircleWeightDetail>> maps = (Map<String, List<ProductionCircleWeightDetail>>) productionCircleWeightDtoVo.getKind();
								for (Iterator iterator = maps.keySet().iterator(); iterator.hasNext();) {
									String gross = (String) iterator.next();
									if(Integer.valueOf(gross) > 0) {
										dto.setWeight(new BigDecimal(gross));
									}
								}
							}
						}
					}
				}catch (Exception e) {
				}

				List<IssueMoDto> dtos = new ArrayList<IssueMoDto>();
				dtos.add(dto);

				McsReturnResult result = MMCSHttpUtil.post(dic.getValue() + "/mes/api/issueMoInterface", dtos, 30000);
				try {
					SysLog syslog = new SysLog();
					syslog.setCreateTime(new Date());
					syslog.setType("info");
					syslog.setCreateUserId(BaseContextHandler.getUserID());
					syslog.setCreateUserName("MMCS");
					syslog.setContent(JSON.toJSONString(dtos));
					syslog.setResult(JSON.toJSONString(result));
					syslog.setCreateUserId(-1);
					syslog.setMethodName("issueMoInterface()");
					syslog.setStatus(1);
					syslog.setName("MES->MMCS下发生产任务接口");
					String serverAddr = dic.getValue() + "/mes/api/issueMoInterface";
					syslog.setServerAddr(serverAddr);
					syslog.setReqType("HTTP");
					syslog.setReqIp(IpUtils.getLocalIP());
					sysLogService.save(syslog);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else if(obj instanceof AgainTaskDetail) {//灌料任务
				IssueMoDto dto = new IssueMoDto();
				AgainTaskDetail task = (AgainTaskDetail)obj;

				dto.setOrderNo(task.getRawType()+"-"+task.getId());
				dto.setOrderName(task.getEquipmentCode()+"-"+task.getLotNo()+"-"+task.getRawType());
				dto.setOrderType(task.getRawType()+"");
				dto.setCreateBy(task.getUserName());
				dto.setCreateTime(task.getRawCreate());
				dto.setFormulaNo(task.getRecipeId()+"");
				dto.setSchemeNo(task.getWeigthId()+"");
				dto.setModuleNo(task.getArea());
				dto.setFurnaceSeries(task.getSeries());
				dto.setFurnaceNo(task.getEquipmentCode());
				dto.setPriority(convertBigDecimal(20));
				dto.setMonocrystalTime(task.getAgainTime());

				String taskWeights = task.getTaskWeigths();

				if(StringUtils.isNotBlank(taskWeights)) {
					String[] taskWeightArr = taskWeights.split(",");

					if(taskWeightArr.length==1) {
						dto.setWeight(convertBigDecimal(taskWeightArr[0]));
					}else if(taskWeightArr.length==2) {
						dto.setWeight(convertBigDecimal(taskWeightArr[0]));
						dto.setWeightOther(convertBigDecimal(taskWeightArr[1]));
					}
				}

				List<IssueMoDto> dtos = new ArrayList<IssueMoDto>();
				dtos.add(dto);

				McsReturnResult result = MMCSHttpUtil.post(dic.getValue() + "/mes/api/issueMoInterface", dtos, 30000);

				try {
					SysLog syslog = new SysLog();
					syslog.setCreateTime(new Date());
					syslog.setType("info");
					syslog.setCreateUserId(BaseContextHandler.getUserID());
					syslog.setCreateUserName("MMCS");
					syslog.setContent(JSON.toJSONString(dtos));
					syslog.setResult(JSON.toJSONString(result));
					syslog.setCreateUserId(-1);
					syslog.setMethodName("issueMoInterface()");
					syslog.setStatus(1);
					syslog.setName("MES->MMCS下发生产任务接口");
					String serverAddr = dic.getValue() + "/mes/api/issueMoInterface";
					syslog.setServerAddr(serverAddr);
					syslog.setReqType("HTTP");
					syslog.setReqIp(IpUtils.getLocalIP());
					sysLogService.save(syslog);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
//			else if(obj instanceof AgainTask) {//灌料任务 - 复投
//				IssueMoDto dto = new IssueMoDto();
//				AgainTask task = (AgainTask)obj;
//				dto.setOrderNo(task.getRawType()+"-"+task.getId());
//				dto.setOrderName(task.getEquipmentCode()+"-"+task.getLotNo()+"-"+task.getRawType());
//				dto.setOrderType(task.getRawType()+"");
//				dto.setCreateBy(task.getUserName());
//				dto.setCreateTime(task.getGmtCreate());
//				dto.setFormulaNo(task.getRecipeId()+"");
//				dto.setSchemeNo(task.getWeigthId()+"");
//				dto.setModuleNo(task.getArea());
//				dto.setFurnaceSeries(task.getSeries());
//				dto.setFurnaceNo(task.getEquipmentCode());
//				dto.setPriority(convertBigDecimal(20));
//				dto.setMonocrystalTime(task.getEtTime());
//				dto.setWeight(task.getAgainWeigth()!=null?task.getAgainWeigth():null);
//
//				List<IssueMoDto> dtos = new ArrayList<IssueMoDto>();
//				dtos.add(dto);
//
//				McsReturnResult result = MMCSHttpUtil.post(dic.getValue() + "/mes/api/issueMoInterface", dtos, 30000);
//
//				try {
//					SysLog syslog = new SysLog();
//					syslog.setCreateTime(new Date());
//					syslog.setType("info");
//					syslog.setCreateUserId(BaseContextHandler.getUserID());
//					syslog.setCreateUserName("MMCS");
//					syslog.setContent(JSON.toJSONString(dtos));
//					syslog.setResult(JSON.toJSONString(result));
//					syslog.setCreateUserId(-1);
//					syslog.setMethodName("issueMoInterface()");
//					syslog.setStatus(1);
//					syslog.setName("MES->MMCS下发生产任务接口");
//					String serverAddr = dic.getValue() + "/mes/api/issueMoInterface";
//					syslog.setServerAddr(serverAddr);
//					syslog.setReqType("HTTP");
//					syslog.setReqIp(IpUtils.getLocalIP());
//					sysLogService.save(syslog);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}

		}catch (Exception e) {
			// TODO: handle exception
		}
	}


	@Override
	@Async
	public void cancelMoDistributionInterface(Object obj) {
		try {
			// 字典中配置的 MMCS url前缀
			DictionaryItem dic = dictionaryItemService.findByThemeValueAndNameAndEnable("MMCSApi", "MMCSBASEURL", true);
			if (dic == null) {
				return;
			}

			if(obj instanceof LoadingTask) {//装料任务
				CancelMoDistributionDto dto = new CancelMoDistributionDto();
				LoadingTask task = (LoadingTask)obj;
				dto.setOrderNo("0-"+task.getId());
				dto.setOrderType(0+"");
				dto.setReason(task.getOperationCause());
				dto.setCancelTime(task.getOperationTime());

				List<CancelMoDistributionDto> dtos = new ArrayList<CancelMoDistributionDto>();
				dtos.add(dto);

				McsReturnResult result = MMCSHttpUtil.post(dic.getValue() + "/mes/api/cancelMoDistributionInterface", dtos, 30000);

				try {
					SysLog syslog = new SysLog();
					syslog.setCreateTime(new Date());
					syslog.setType("info");
					syslog.setCreateUserId(BaseContextHandler.getUserID());
					syslog.setCreateUserName("MMCS");
					syslog.setContent(JSON.toJSONString(dtos));
					syslog.setResult(JSON.toJSONString(result));
					syslog.setCreateUserId(-1);
					syslog.setMethodName("cancelMoDistributionInterface()");
					syslog.setStatus(1);
					syslog.setName("MES->MMCS取消生产任务下发接口");
					String serverAddr = dic.getValue() + "/mes/api/cancelMoDistributionInterface";
					syslog.setServerAddr(serverAddr);
					syslog.setReqType("HTTP");
					syslog.setReqIp(IpUtils.getLocalIP());
					sysLogService.save(syslog);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else if(obj instanceof AgainTask) {//灌料任务
				CancelMoDistributionDto dto = new CancelMoDistributionDto();
				AgainTask task = (AgainTask)obj;
				dto.setOrderNo(task.getRawType()+"-"+task.getId());
				dto.setOrderType(task.getRawType()+"");
				dto.setReason(task.getOperationCause());
				dto.setCancelTime(task.getOperationTime());

				List<CancelMoDistributionDto> dtos = new ArrayList<CancelMoDistributionDto>();
				dtos.add(dto);

				McsReturnResult result = MMCSHttpUtil.post(dic.getValue() + "/mes/api/cancelMoDistributionInterface", dtos, 30000);

				try {
					SysLog syslog = new SysLog();
					syslog.setCreateTime(new Date());
					syslog.setType("info");
					syslog.setCreateUserId(BaseContextHandler.getUserID());
					syslog.setCreateUserName("MMCS");
					syslog.setContent(JSON.toJSONString(dtos));
					syslog.setResult(JSON.toJSONString(result));
					syslog.setCreateUserId(-1);
					syslog.setMethodName("cancelMoDistributionInterface()");
					syslog.setStatus(1);
					syslog.setName("MES->MMCS取消生产任务下发接口");
					String serverAddr = dic.getValue() + "/mes/api/cancelMoDistributionInterface";
					syslog.setServerAddr(serverAddr);
					syslog.setReqType("HTTP");
					syslog.setReqIp(IpUtils.getLocalIP());
					sysLogService.save(syslog);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}catch (Exception e) {
		}
	}



	@Override
	public void errorOrder(ErrorOrderDto dto, Object obj) {
		try {
			if(obj instanceof LoadingTask) {//装料任务
				LoadingTask task = (LoadingTask)obj;

				String reasonType = "";
				if(dto.getCancelType()!=null && dto.getCancelType().equals("1")) {
					reasonType = "无法分配装灌料机";
				}else if(dto.getCancelType()!=null && dto.getCancelType().equals("2")) {
					reasonType = "缺料";
				}
				task.setErrorStatus(1);
				task.setOperationCause(reasonType+":"+dto.getReason());
				task.setOperationTime(dto.getIn_Time());
	            loadingTaskService.saveOrUpdate(task);
			}else if(obj instanceof AgainTask) {//灌料任务
				AgainTask task = (AgainTask)obj;

				String reasonType = "";
				if(dto.getCancelType()!=null && dto.getCancelType().equals("1")) {
					reasonType = "无法分配装灌料机";
				}else if(dto.getCancelType()!=null && dto.getCancelType().equals("2")) {
					reasonType = "缺料";
				}
				task.setErrorStatus(1);
				task.setOperationCause(reasonType+":"+dto.getReason());
				task.setOperationTime(dto.getIn_Time());
	            againTaskService.saveOrUpdate(task);
			}

		}catch (Exception e) {
		}
	}



	@Override
	@Transactional
	public void moWorkReportingInterface(MoWorkReportingDto dto, Object obj) {
		if (obj instanceof LoadingTask) {// 装料任务
			LoadingTask task = (LoadingTask) obj;

			if(dto.getFinishType()!=null && dto.getFinishType().equals("0")) {
				task.setRawStatus(AgainTaskDto.rawStatus_3);
			}else if(dto.getFinishType()!=null && dto.getFinishType().equals("1")) {
				task.setRawStatus(AgainTaskDto.rawStatus_4);
			}else {
				task.setRawStatus(AgainTaskDto.rawStatus_3);
			}

			task.setUserName("MMCS");
			task.setOperationTime(dto.getFeedingEndTime());
			task.setWeight(getWeight(dto.getMaterialList()));
			task.setEquipmentCode(dto.getFillingMachine());
			loadingTaskService.saveOrUpdate(task);

			int crucibleNum = 0;
			for (MaterialDto mDto : dto.getMaterialList()) {
				BlastFurnaceDetail detail = new BlastFurnaceDetail();

				detail.setBlastFurnaceId(task.getId());
				detail.setUserName(task.getUserName());
				detail.setBatchNo(mDto.getBatch());
				detail.setFactoryBrand(mDto.getVender());
				detail.setInstallTime(dto.getFeedingEndTime());
				detail.setMaterialCode(mDto.getMaterialNo());
				detail.setMaterialName(mDto.getMaterialName());
				detail.setRemark(JSON.toJSONString(mDto));
				detail.setWeight(mDto.getMaterialWeight());

				try {
					MaterialModel model = materialModelService.findByCode(mDto.getMaterialNo());
					detail.setProductCode(model.getMaterialType().getCode());
					detail.setUnit(model.getUnit().getName());

					if (model.getMaterialType().getCode() == "A04036") {
						detail.setMarkCrucible(true);
						crucibleNum++;
					} else {
						detail.setMarkCrucible(false);
					}

				} catch (Exception e) {
					detail.setMarkCrucible(false);
				}

				if (crucibleNum >= 2) {
					throw new RuntimeException("存在多个坩埚条码");
				}

				blastFurnaceDetailService.saveOrUpdate(detail);
			}

		} else if (obj instanceof AgainTask) {// 灌料任务
			AgainTask task = (AgainTask) obj;

			if(dto.getFinishType()!=null && dto.getFinishType().equals("0")) {
				task.setRawStatus(AgainTaskDto.rawStatus_3);
			}else if(dto.getFinishType()!=null && dto.getFinishType().equals("1")) {
				task.setRawStatus(AgainTaskDto.rawStatus_4);
			}else {
				task.setRawStatus(AgainTaskDto.rawStatus_3);
			}

			if(StringUtils.isBlank(task.getVesselNo())) {
				task.setVesselNo(dto.getVesselNo());
			}else {
				task.setVesselNo(task.getVesselNo()+","+dto.getVesselNo());
			}

			task.setReportTime(dto.getReportTime());
			task.setReportType(dto.getReportType());
			task.setUserName("MMCS");
			task.setOperationTime(dto.getFeedingEndTime());
			task.setEquipmentCode(dto.getFillingMachine());
			task.setAgainWeigth(getWeight(dto.getMaterialList()));
			task.setRemark(JSON.toJSONString(dto));

			againTaskService.saveOrUpdate(task);



			AgainTaskDetail child = new AgainTaskDetail();
			child.setFurnaceType(task.getFurnaceType());
			child.setAgainTaskId(task.getId());
			child.setAgainPailNum(task.getAgainPailNum());
			child.setEquipmentCode(task.getEquipmentCode());
			child.setLotNo(task.getLotNo());
			child.setSeries(task.getSeries());
			child.setArea(task.getArea());
			child.setSapNo(task.getSapNo());
			child.setProductCode(task.getProductCode());
			child.setProductGrade(task.getProductGrade());
			child.setSpecs(task.getSpecs());
			child.setDopant(task.getDopant());
			child.setProductType(task.getProductType());
			child.setRawType(task.getRawType());
			child.setRecipeId(task.getRecipeId());
			child.setWeigthId(task.getWeigthId());
			child.setTaskWeigths(task.getAgainWeigth()+"");
			child.setRawCreate(task.getReportTime());

			//未知
			child.setCarrierSort(0);
			child.setPailNum("0");
			child.setNum(0);

			//child.setAgainPailNum(tongNum);
			//child.setPreDetailId(preDetailId);
			child.setAgainWeigth(task.getAgainWeigth());
			child.setAgainTime(task.getReportTime());//预计复投时间
			child.setRawStatus(task.getRawStatus());
			child.setDelayedStartTime(task.getReportTime());

			child.setAlreadyPailNum(task.getAgainPailNum());
			child.setStartTime(task.getReportTime());
			child.setEndTime(task.getOperationTime());
			child.setUserName(task.getUserName());

			againTaskDetailService.saveOrUpdate(child);


			//完善灌料开始数据
			InputFurnaceBurden inputFurnaceBurden = new InputFurnaceBurden();
			initStartInputFurnaceBurdenData(child, inputFurnaceBurden);
			inputFurnaceBurdenService.saveOrUpdate(inputFurnaceBurden);


			for (MaterialDto mDto : dto.getMaterialList()) {
				InputFurnaceDetail detail = new InputFurnaceDetail();
				detail.setInputFurnaceId(inputFurnaceBurden.getId());
				detail.setAgainTaskDetailId(child.getId());
				detail.setBatchNo(mDto.getBatch());
				detail.setFactoryBrand(mDto.getVender());
				detail.setMaterialCode(mDto.getMaterialNo());
				detail.setMaterialName(mDto.getMaterialName());
				detail.setRemark(JSON.toJSONString(mDto));
				detail.setWeight(mDto.getMaterialWeight());

				try {
					MaterialModel model = materialModelService.findByCode(mDto.getMaterialNo());
					detail.setProductCode(model.getMaterialType().getCode());
					detail.setUnit(model.getUnit().getName());
				} catch (Exception e) {
				}


				inputFurnaceDetailService.saveOrUpdate(detail);
			}
		}
	}


	private void initStartInputFurnaceBurdenData(AgainTaskDetail againTaskDetail, InputFurnaceBurden inputFurnaceBurden) {
		inputFurnaceBurden.setEquipmentCode(againTaskDetail.getEquipmentCode());
		inputFurnaceBurden.setLotNo(againTaskDetail.getLotNo());
		inputFurnaceBurden.setSeries(againTaskDetail.getSeries());
		inputFurnaceBurden.setArea(againTaskDetail.getArea());
		inputFurnaceBurden.setRawType(againTaskDetail.getRawType());
		if(inputFurnaceBurden.getPailNum()==null) {
            inputFurnaceBurden.setPailNum(againTaskDetail.getNum());
        }
		inputFurnaceBurden.setWeigth(againTaskDetail.getAgainWeigth());
		inputFurnaceBurden.setEndTime(new Date());
		inputFurnaceBurden.setFurnaceType(againTaskDetail.getFurnaceType());
		inputFurnaceBurden.setSapNo(againTaskDetail.getSapNo());
		inputFurnaceBurden.setProductCode(againTaskDetail.getProductCode());
		inputFurnaceBurden.setProductGrade(againTaskDetail.getProductGrade());
		inputFurnaceBurden.setSpecs(againTaskDetail.getSpecs());
		inputFurnaceBurden.setDopant(againTaskDetail.getDopant());
		inputFurnaceBurden.setProductType(againTaskDetail.getProductType());
		inputFurnaceBurden.setAgainTaskDetailId(againTaskDetail.getId());
	}




	private BigDecimal getWeight(List<MaterialDto> materialList) {
		float total = 0;
		for (MaterialDto dto : materialList) {
			total += (dto.getMaterialWeight()==null?0:dto.getMaterialWeight().floatValue());
		}
		return BigDecimal.valueOf(total);
	}



	private BigDecimal convertBigDecimal(Object obj) {
		try {
			if(obj == null) {
				return null;
			}
			else if(obj.toString().equals("/")) {
				return new BigDecimal(0);
			}
			else{
				return new BigDecimal(obj.toString());
			}
		}catch (Exception e) {
			return null;
		}
	}





}
