package com.sw.mes.yb.pad.controller;

import java.util.Date;
import java.util.List;

import javax.validation.Valid;

import org.modelmapper.ModelMapper;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.enumvalue.EnumValuesAgv;
import com.sw.mes.yb.agv.dto.AgvCallDto;
import com.sw.mes.yb.agv.service.AgvDispatchService;
import com.sw.mes.yb.pad.dto.PadFurnaceAgvDto;
import com.sw.mes.yb.pad.entity.PadFurnaceAgv;
import com.sw.mes.yb.pad.service.PadFurnaceAgvService;
import com.sw.mes.yb.production.entity.LoadingTask;
import com.sw.mes.yb.production.service.BlastFurnaceDetailService;

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

/**
 * @Author 李儒
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/pad/furance/agv")
@Slf4j
@Api(description = "PDA - 装料发料接口")
public class PadFurnaceAgvController {



	/**装料呼叫agv请求接口**/
	public final static String CALLAGVURL = "http://10.60.120.58/test/callagv";

//	@Value("${agv.callagvurl}")
	private String callagvurl;


	@Autowired
	ModelMapper modelMapper;

	@Autowired
	RestTemplate restTemplate;

	@Autowired
	private PadFurnaceAgvService padFurnaceAgvService;
	@Autowired
	private BlastFurnaceDetailService blastFurnaceDetailService;

	@Autowired
	private AgvDispatchService agvDispatchService;

	@SuppressWarnings("rawtypes")
	@ApiOperation(value = "根据坩埚编号查询目标设备")
	@PostMapping("/getEquipmentCode")
	public Result getEquipmentCode(@ApiParam(value = "坩埚ID") @RequestParam String materialCode) {
		List<LoadingTask> loadingTasks = blastFurnaceDetailService.findTaskByMaterialCodes(materialCode);
		if (loadingTasks.size() == 0) {
			return ResultGenerator.fail("坩埚未找到装料完成任务");
		} else {
			return ResultGenerator.success(loadingTasks);
		}
	}

	@SuppressWarnings("rawtypes")
	@ApiOperation(value = "确认呼叫")
	@PostMapping("/call")
	public Result call(@RequestBody @Valid @ApiParam(value = "装料发料对象") PadFurnaceAgvDto padFurnaceAgvDto,
			BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}

		// 1. 操作人由前端传入，PDA上避免登录超时等操作不自动获取
		// 设置操作时间
		PadFurnaceAgv padFurnaceAgv = fromDto(padFurnaceAgvDto);
		padFurnaceAgv.setOperationTime(new Date());


		try {
            AgvCallDto agvCall = new AgvCallDto();
            agvCall.setKeyword(EnumValuesAgv.AGVKeyword.装料发料.getValue());//关键字 根据配置中的信息固定写入  : 圆棒送验
            agvCall.setStartCode(padFurnaceAgv.getStoreCode()); //起始位置编号  - 当前传入机台号
            agvCall.setTargetPoint(padFurnaceAgv.getEquipmentCode());//结束工作位
            //其他信息可根据配置信息自动填充
            String taskCode = agvDispatchService.callAgv(agvCall);

            padFurnaceAgv.setRequestMsg("任务单号:"+taskCode);
			padFurnaceAgv.setRequestTime(new Date());
			padFurnaceAgvService.saveOrUpdate(padFurnaceAgv);
			return ResultGenerator.success(taskCode);
        } catch (Exception e) {
        	padFurnaceAgv.setRequestTime(new Date());
			padFurnaceAgv.setRequestState("999");
			padFurnaceAgv.setRequestMsg("请求发生错误：" + e.getMessage());
			padFurnaceAgvService.saveOrUpdate(padFurnaceAgv);
			return ResultGenerator.fail("请求AGV接口失败,请重试:"+e.getMessage());
        }




		//ResponseEntity<String> result = null;
//		try {
//			FurnaceCallAgvParam callParams = new FurnaceCallAgvParam();
//			callParams.setType("装料发料");
//			callParams.setReqCode(UUID.randomUUID().toString());
//			callParams.setStartCode(padFurnaceAgv.getStoreCode());
//			callParams.setTargetPoint(padFurnaceAgv.getEquipmentCode());

			// 2.调用呼叫Agv接口
			//padFurnaceAgv.setRequestUrl(CALLAGVURL);
			//padFurnaceAgv.setRequestParam(JSON.toJSONString(callParams));

			//result = restTemplate.postForEntity(callagvurl,callParams, String.class);
			//padFurnaceAgv.setRequestState(result.getStatusCode().toString());
			//String resultJson = result.getBody();
//			if (StringUtils.isBlank(resultJson)) {
//				AgvResult agvResult = JSON.parseObject(resultJson, AgvResult.class);
//				padFurnaceAgv.setRequestState(agvResult.getCode());
//				if(agvResult.getCode() == "100") {
//					padFurnaceAgv.setRequestMsg("任务单号:"+agvResult.getData());
//					padFurnaceAgv.setRequestTime(new Date());
//					padFurnaceAgvService.saveOrUpdate(padFurnaceAgv);
//					return ResultGenerator.success(agvResult.getData());
//				}else {
//					padFurnaceAgv.setRequestMsg(agvResult.getMessage());
//					padFurnaceAgv.setRequestTime(new Date());
//					padFurnaceAgvService.saveOrUpdate(padFurnaceAgv);
//					return ResultGenerator.fail(agvResult.getMessage());
//				}
//	        }else {
//	        	padFurnaceAgv.setRequestMsg("请求结果失败");
//	        	padFurnaceAgv.setRequestTime(new Date());
//				padFurnaceAgvService.saveOrUpdate(padFurnaceAgv);
//				return ResultGenerator.success("请求成功");
//	        }
//		}catch (Exception e) {
//			padFurnaceAgv.setRequestTime(new Date());
//			padFurnaceAgv.setRequestState(result==null?"999":result.getStatusCode().toString());
//			padFurnaceAgv.setRequestMsg("请求发生错误：" + e.getMessage());
//			padFurnaceAgvService.saveOrUpdate(padFurnaceAgv);
//			return ResultGenerator.fail("请求AGV接口失败,请重试");
//		}
	}

	public PadFurnaceAgvDto toLazyDto(PadFurnaceAgv entity) {
		return modelMapper.map(entity, PadFurnaceAgvDto.class);
	}

	public PadFurnaceAgvDto toEagerDto(PadFurnaceAgv entity) {
		PadFurnaceAgvDto dto = modelMapper.map(entity, PadFurnaceAgvDto.class);
		return dto;
	}

	public PadFurnaceAgv fromDto(PadFurnaceAgvDto dto) {
		return modelMapper.map(dto, PadFurnaceAgv.class);
	}

}
