package com.sw.mes.mmcs.scheduled;

import com.alibaba.fastjson.JSON;
import com.sw.mes.base.factory.init.entity.Equipment;
import com.sw.mes.base.factory.init.service.EquipmentService;
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.context.BaseContextHandler;
import com.sw.mes.core.utils.DateUtil;
import com.sw.mes.core.utils.IpUtils;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.enumvalue.EnumValuesServer;
import com.sw.mes.mmcs.dto.DistributionPlanDto;
import com.sw.mes.mmcs.dto.McsReturnResult;
import com.sw.mes.mmcs.entity.MmcsDistributionPlan;
import com.sw.mes.mmcs.service.MmcsDistributionPlanService;
import com.sw.mes.utils.MMCSHttpUtil;
import com.sw.mes.yb.plan.entity.ProductionOrder;
import com.sw.mes.yb.plan.entity.ProductionSchedule;
import com.sw.mes.yb.plan.service.ProductionScheduleService;
import com.sw.mes.yb.production.entity.ProductionCircleDosingList;
import com.sw.mes.yb.production.service.ProductionCircleDosingListService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Component
public class MMcsTimer {

	@Autowired
    private DictionaryItemService dictionaryItemService;
	@Autowired
	private MmcsDistributionPlanService mmcsDistributionPlanService;
	@Autowired
    private ProductionScheduleService productionScheduleService;
	@Autowired
    private EquipmentService equipmentService;
	@Autowired
	private ProductionCircleDosingListService productionCircleDosingListService;
	@Autowired
	private SysLogService sysLogService;


	@XxlJob("sendMMcsDistributionPlan")
	@Transactional
	public void sendDistributionPlan() throws Exception {
		Map<String,ProductionCircleDosingList> cacheDosing = new HashMap<String,ProductionCircleDosingList>();
		Map<String,ProductionSchedule> cacheProductionSchedule = new HashMap<String,ProductionSchedule>();

		Date nowTime = new Date();

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(nowTime);
		int hour = calendar.get(Calendar.HOUR_OF_DAY);

		DictionaryItem dictionaryItem = dictionaryItemService.findByThemeValueAndNameAndEnable("MMCSPrepare", "sendMMCSHour", true);//下发生产计划时间(H)点

		DictionaryItem weightItem = dictionaryItemService.findByThemeValueAndNameAndEnable("MMCSPrepare", "totalJoinWeight", true);//总装料总量

		// 字典中配置的 MMCS url前缀
		DictionaryItem dic = dictionaryItemService.findByThemeValueAndNameAndEnable("MMCSApi", "MMCSBASEURL", true);
		if(dictionaryItem==null || weightItem==null || dic==null)
			return;


		String configHours = dictionaryItem.getValue();

		String[] configHourArr = configHours.split(",");

		List<Integer> configHourList = new ArrayList<Integer>();
		for (String configHour : configHourArr) {
			if(StringUtils.isBlank(configHour)) {
				continue;
			}
			configHourList.add(Integer.valueOf(configHour));
		}

		if(configHourList.contains(hour)) {
			List<DistributionPlanDto> dtos = new ArrayList<DistributionPlanDto>();

			//执行下发操作
			List<MmcsDistributionPlan> notSends =  mmcsDistributionPlanService.findByNotSend();
			for (MmcsDistributionPlan mmcsDistributionPlan : notSends) {

				ProductionSchedule productionSchedule = null;
				if(cacheProductionSchedule.containsKey(mmcsDistributionPlan.getEquipmentCode())) {
					productionSchedule = cacheProductionSchedule.get(mmcsDistributionPlan.getEquipmentCode());
				}else {
					productionSchedule = productionScheduleService.findTopByDeviceNoAndStatusOrderByIdDesc(mmcsDistributionPlan.getEquipmentCode(), Arrays.asList(EnumValuesServer.ProductionScheduleStatus.未开始.getKey()));
					cacheProductionSchedule.put(mmcsDistributionPlan.getEquipmentCode(), productionSchedule);
				}

				//判断是否存在排产
				if(productionSchedule!=null && productionSchedule.getProductionOrder()!=null) {
					ProductionOrder order = productionSchedule.getProductionOrder();

					Equipment equipment = equipmentService.get(productionSchedule.getDeviceId());

					ProductionCircleDosingList dosing = null;
					if(!cacheDosing.containsKey(order.getMatnr())) {
						dosing = productionCircleDosingListService.getProductName(order.getMatnr());
						if(dosing!=null) {
							cacheDosing.put(order.getMatnr(), dosing);
						}
					}else {
						dosing = cacheDosing.get(order.getMatnr());
					}

					String type = mmcsDistributionPlan.getType();


					DistributionPlanDto dto = new DistributionPlanDto();
					dto.setOrderNo(productionSchedule.getId()+"");
					dto.setOrderName(DateUtil.formatDate(order.getGstrp())+"-"+DateUtil.formatDate(order.getGltrp())+":"+DateUtil.formatDate(nowTime));
					dto.setCreateBy(productionSchedule.getCreateUserName());
					dto.setCreateTime(productionSchedule.getCreateTime());
					dto.setModuleNo(equipment!=null?equipment.getArea():null);
					dto.setFurnaceSeries(equipment!=null?equipment.getSeries():null);
					dto.setFormulaNo(dosing!=null?dosing.getRecipeId()+"":null);
					dto.setSchemeNo(dosing!=null?dosing.getWeightId()+"":null);
					if(type.equals("0")) {
						dto.setQuantity(convertBigDecimal(1));
						dto.setWeight(convertBigDecimal(0));
					}else {
						dto.setQuantity(convertBigDecimal(1));
						int totalWeight = Integer.valueOf(weightItem.getValue());
						int slWeight = formartToInt(mmcsDistributionPlan.getResidualWeight());
						int weight = totalWeight - slWeight;
						dto.setWeight(convertBigDecimal(weight));
					}
					dto.setOrderType(type);
					dto.setBeginTime(mmcsDistributionPlan.getEstimate());
					dtos.add(dto);
				}
			}

			//按系列模块配方ID重量ID分组
			Map<String,DistributionPlanDto> groups = new HashMap<String, DistributionPlanDto>();
			for (DistributionPlanDto mmcsDistributionPlan : dtos) {
				String key = mmcsDistributionPlan.getFurnaceSeries()+"-"+mmcsDistributionPlan.getModuleNo() +"-"+mmcsDistributionPlan.getFormulaNo() +"-"+mmcsDistributionPlan.getSchemeNo();
				if(!groups.containsKey(key)) {
					groups.put(key, mmcsDistributionPlan);
				}else {
					DistributionPlanDto dto = groups.get(key);
					dto.setQuantity(mmcsDistributionPlan.getQuantity());
					dto.setWeight(convertBigDecimal(dto.getWeight().floatValue()+mmcsDistributionPlan.getWeight().floatValue()));
				}
			}


			dtos = new ArrayList<DistributionPlanDto>(groups.values());


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

			//保存已统计发送过的
			for (MmcsDistributionPlan mmcsDistributionPlan : notSends) {
				mmcsDistributionPlan.setSended(true);
				mmcsDistributionPlan.setSendTime(nowTime);
				mmcsDistributionPlanService.saveOrUpdate(mmcsDistributionPlan);
			}


			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("sendDistributionPlan()");
				syslog.setStatus(1);
				syslog.setName("MES->MMCS下发生产计划接口");
				String serverAddr = dic.getValue() + "/mes/api/DistributionPlan";
				syslog.setServerAddr(serverAddr);
				syslog.setReqType("HTTP");
				syslog.setReqIp(IpUtils.getLocalIP());
				sysLogService.save(syslog);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}


	private int formartToInt(String value) {
		if(value==null) {
			return 0;
		}else {
			try {
				BigDecimal bd = new BigDecimal(value);
				return bd.intValue();
			}catch (Exception e) {
				return 0;
			}
		}
	}

	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;
		}
	}


}
