package com.sw.mes.mmcs.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.sw.mes.third.entity.SoapData;
import com.sw.mes.third.entity.SoapInDto;
import com.sw.mes.third.entity.SoapOutDto;
import com.sw.mes.third.entity.WebServiceApiName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.mmcs.dto.ErrorOrderDto;
import com.sw.mes.mmcs.dto.MoWorkReportingDto;
import com.sw.mes.mmcs.scheduled.MMcsTimer;
import com.sw.mes.mmcs.service.MMcsInterfaceService;
import com.sw.mes.webservice.entity.MaterialNumberOutPut;
import com.sw.mes.yb.production.entity.AgainTask;
import com.sw.mes.yb.production.entity.LoadingTask;
import com.sw.mes.yb.production.service.AgainTaskService;
import com.sw.mes.yb.production.service.LoadingTaskService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/mmcsInterface")
@Slf4j
@Api(description = "MMCS测试与回调接口")
public class MMcsTestController {

	@Autowired
	private MMcsInterfaceService mMcsInterfaceService;
	
	
	@Autowired
    private AgainTaskService againTaskService;
	@Autowired
	private LoadingTaskService loadingTaskService;
	@Autowired
	private MMcsTimer mMcsTimer;
	

	@ApiOperation(value = "同步物料信息接口调试接口")
	@PostMapping("/mcsMaterialToMmcs")
	public Result mcsMaterialToMmcs(@RequestBody SoapInDto soapInDto, BindingResult bindingResult) {
		try {
			 SoapOutDto soapOutDto=new SoapOutDto();
		        try {
		            if (soapInDto != null) {
		                soapOutDto.setBSKEY(soapInDto.getBSKEY());
		                soapOutDto.setSAPKEY(soapInDto.getSAPKEY());
		                soapOutDto.setZTYPE(soapInDto.getIFYWID());
		                soapOutDto.setZMESSAGE("success");
		                List<SoapData> soapDataList=new ArrayList<>();
		                //List<SoapDataStore> soapDataStoreList = new ArrayList<>();
		                soapOutDto.setBSKEY(UUID.randomUUID().toString());
		                if ("1031MES".equals(soapInDto.getSYSID())){
		                    soapOutDto.setZTYPE("S");
		                    soapOutDto.setZMESSAGE("success");
		                    if (soapInDto.getIFYWID().equalsIgnoreCase(WebServiceApiName.MaterialNumber)) {//处理物料主数据
		                        List<MaterialNumberOutPut> list = null;
		                        try {
		                            list = JSONObject.parseArray(soapInDto.getZDATA(), MaterialNumberOutPut.class);
		                        } catch (JSONException e) {
		                        	e.printStackTrace();
		                            log.info(e.getMessage());
		                            throw  new RuntimeException("Json字符串数据格式错误");
		                        }
		                        
		                        if(list!=null && list.size()>0) {
		                        	mMcsInterfaceService.mcsMaterialToMmcs(list);
		                        }
		                        
		                        soapOutDto.setZDATA(JSONObject.toJSON(soapDataList).toString());
		                    } 
		                }else{
		                    soapOutDto.setZTYPE("E");
		                    soapOutDto.setZMESSAGE("不是中环六期接收的数据！！！");
		                }
		            }
		        } catch (Exception e) {
		            soapOutDto.setZTYPE("E");
		            soapOutDto.setZMESSAGE("调用异常");
		            e.printStackTrace();
		        }
			
			
			
			return ResultGenerator.success();
		} catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}
	
	
	
	@ApiOperation(value = "下发物料配方接口")
	@PostMapping("/issueMaterialFormulaInterface")
	public Result issueMaterialFormulaInterface() {
		try {
			mMcsInterfaceService.mcsRecipeToMmcs();
			return ResultGenerator.success();
		} catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}
	
	
	@ApiOperation(value = "下发重量方案接口")
	@PostMapping("/issueWeightSchemeInterface")
	public Result issueWeightSchemeInterface() {
		try {
			mMcsInterfaceService.issueWeightSchemeInterface();
			return ResultGenerator.success();
		} catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}
	
	
	@ApiOperation(value = "下发生产计划接口")
	@PostMapping("/distributionPlan")
	public Result distributionPlan() {
		try {
			
			//TODO 未完成原始数据开发
			
			mMcsTimer.sendDistributionPlan();
			
			return ResultGenerator.success();
		} catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}
	
	
	
	@ApiOperation(value = "下发生产任务接口")
	@PostMapping("/issueMoInterface")
	public Result issueMoInterface(String type,Long id) {
		try {
			if(type.contains("复投")) {
				AgainTask task = againTaskService.get(id);
				if(task!=null) {
					mMcsInterfaceService.issueMoInterface(task);
				}
			}else {
				LoadingTask task = loadingTaskService.get(id);
				if(task!=null) {
					mMcsInterfaceService.issueMoInterface(task);
				}
			}
			return ResultGenerator.success();
		} catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}
	
	
	@ApiOperation(value = "取消生产任务下发接口")
	@PostMapping("/cancelMoDistributionInterface")
	public Result cancelMoDistributionInterface(String type,Long id) {
		try {
			if(type.contains("复投")) {
				AgainTask task = againTaskService.get(id);
				if(task!=null) {
					mMcsInterfaceService.cancelMoDistributionInterface(task);
				}
			}else {
				LoadingTask task = loadingTaskService.get(id);
				if(task!=null) {
					mMcsInterfaceService.cancelMoDistributionInterface(task);
				}
			}
			return ResultGenerator.success();
		} catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}
	
	
	@ApiOperation(value = "异常生产任务上报接口")
	@PostMapping("/errorOrder")
	public Result errorOrder(@RequestBody ErrorOrderDto dto) {
		try {
			
			if(dto.getOrderNo().startsWith("0-")) {//装料
				String idStr = dto.getOrderNo().substring(2);
				LoadingTask task = loadingTaskService.get(Long.valueOf(idStr));
				
				mMcsInterfaceService.errorOrder(dto,task);
			}else if(dto.getOrderNo().startsWith("1-")) {//初始
				String idStr = dto.getOrderNo().substring(2);
				AgainTask task = againTaskService.get(Long.valueOf(idStr));
				mMcsInterfaceService.errorOrder(dto,task);
			}else if(dto.getOrderNo().startsWith("2-")) {//取段
				String idStr = dto.getOrderNo().substring(2);
				AgainTask task = againTaskService.get(Long.valueOf(idStr));
				mMcsInterfaceService.errorOrder(dto,task);
			}else {
				return ResultGenerator.fail("未知的任务ID");
			}
			
			return ResultGenerator.success("异常生产任务上报完成");
		} catch (IndexOutOfBoundsException e) {
			return ResultGenerator.fail("任务ID格式错误");
		}catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}
	
	
	@ApiOperation(value = "生产任务报工接口")
	@PostMapping("/moWorkReportingInterface")
	public Result moWorkReportingInterface(@RequestBody MoWorkReportingDto dto) {
		try {
			
			if(dto.getOrderNo().startsWith("0-")) {//装料
				String idStr = dto.getOrderNo().substring(2);
				LoadingTask task = loadingTaskService.get(Long.valueOf(idStr));
				
				mMcsInterfaceService.moWorkReportingInterface(dto,task);
			}else if(dto.getOrderNo().startsWith("1-")) {//初始
				String idStr = dto.getOrderNo().substring(2);
				AgainTask task = againTaskService.get(Long.valueOf(idStr));
				mMcsInterfaceService.moWorkReportingInterface(dto,task);
			}else if(dto.getOrderNo().startsWith("2-")) {//取段
				String idStr = dto.getOrderNo().substring(2);
				AgainTask task = againTaskService.get(Long.valueOf(idStr));
				mMcsInterfaceService.moWorkReportingInterface(dto,task);
			}else {
				return ResultGenerator.fail("未知的任务ID");
			}
			
			return ResultGenerator.success("生产任务报工接口完成");
		} catch (IndexOutOfBoundsException e) {
			return ResultGenerator.fail("任务ID格式错误");
		}catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}
	
	
}
