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

import com.alibaba.fastjson.JSON;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.entity.SysLog;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.system.service.SysLogService;
import com.sw.mes.core.utils.*;
import com.sw.mes.yb.report.dto.CastMaterialInfoDto;
import com.sw.mes.yb.report.dto.EmsPushInfoDto;
import com.sw.mes.yb.report.dto.EmsPushListDataDto;
import com.sw.mes.yb.report.entity.CastMaterialInfo;
import com.sw.mes.yb.report.service.CastMaterialInfoService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.*;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/castMaterialInfo")
@Slf4j
@Api(description = "单晶投料信息接口")
public class CastMaterialInfoController {
	private static final Map<String,String> Input_Type = new HashMap<String, String>();

	public CastMaterialInfoController() {
		//推送类型
		Input_Type.put("materialsWeight","feeding_quantity");//投料量
		Input_Type.put("inspectionYbWeight","round_bar_inspection_quantity");//圆棒过检量
		Input_Type.put("inspectionFbWeight","square_bar_inspection_quantity");//方棒过检量
		Input_Type.put("totalOpen","device_open_flag");//设备开机数量
		Input_Type.put("standby","device_standby_flag");//设备待机数量
	}

	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private CastMaterialInfoService castMaterialInfoService;

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private DictionaryItemService dictionaryItemService;

	@Autowired
	private SysLogService sysLogService;

	@ApiOperation(value = "分页查询单晶投料信息列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<CastMaterialInfoDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		Specification<CastMaterialInfo> specification = DynamicSpecifications.bySearchFilter(request, CastMaterialInfo.class);
    	Page<CastMaterialInfo> page = castMaterialInfoService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<CastMaterialInfoDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
		ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
	}

	@ApiOperation(value = "获取所有单晶投料信息")
	@GetMapping("/listAll")
	public Result<List<CastMaterialInfoDto>> listAll(ServletRequest request) {
		Specification<CastMaterialInfo> specification = DynamicSpecifications.bySearchFilter(request, CastMaterialInfo.class);
		List<CastMaterialInfo> castMaterialInfos = castMaterialInfoService.findByExampleSort(specification, null);
		List<CastMaterialInfoDto> castMaterialInfoDtos = castMaterialInfos.stream()
					.map(castMaterialInfo -> toLazyDto(castMaterialInfo))
					.collect(Collectors.toList());
		return ResultGenerator.success(castMaterialInfoDtos);
	}

	@ApiOperation(value = "单晶投料信息详细信息")
	@GetMapping("/{id}")
	public Result<CastMaterialInfoDto> get(@PathVariable @ApiParam(value="单晶投料信息id") Long id) {
		CastMaterialInfo castMaterialInfo = castMaterialInfoService.get(id);
		if (null == castMaterialInfo)
			return ResultGenerator.fail("该单晶投料信息不存在");
		return ResultGenerator.success(toEagerDto(castMaterialInfo));
	}

	@ApiOperation(value = "创建单晶投料信息")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "单晶投料信息对象") CastMaterialInfoDto castMaterialInfoDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		CastMaterialInfo castMaterialInfo = fromDto(castMaterialInfoDto);
		castMaterialInfoService.saveOrUpdate(castMaterialInfo);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新单晶投料信息")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "单晶投料信息") CastMaterialInfoDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
            CastMaterialInfo entity = castMaterialInfoService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            CastMaterialInfo entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			castMaterialInfoService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

	@ApiOperation(value = "删除单晶投料信息")
	@PostMapping("/delete")
	public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Integer[] ids) {
		for (Integer id : ids) {
				castMaterialInfoService.delete(id);
		}
		return ResultGenerator.success();
	}

	@ApiOperation(value = "生产数据")
	@PostMapping("/aaaaaa")
	public Result aaaaaa() {
		String url = "";
		String ak = "";
		List<DictionaryItem> emsUrl = dictionaryItemService.findByThemeValueAndEnable("emsUrl", true);
		if (emsUrl != null && emsUrl.size() > 0){
			url = emsUrl.get(0).getValue();
			ak = emsUrl.get(0).getExtendValue();
		}

		EmsPushInfoDto emsPushInfoDto = new EmsPushInfoDto();
		List<EmsPushListDataDto> listData = new ArrayList<>();
		emsPushInfoDto.setAk("");
		List<Map<String, Object>> rptData = castMaterialInfoService.energyStatisticsInfo();
		for (Map<String, Object> map : rptData) {
			for (Map.Entry<String, String> entry : Input_Type.entrySet()) {
				EmsPushListDataDto emsPushListDataDto = new EmsPushListDataDto();
				emsPushListDataDto.setUsedDate(String.valueOf(map.get("time")));
				emsPushListDataDto.setInputType(entry.getValue());
				emsPushListDataDto.setLocationId(String.valueOf(map.get("area")));
				emsPushListDataDto.setTopParentId("宁夏六期工厂");
				String value = String.valueOf(map.get(entry.getKey()));
				if(StringUtils.isNotBlank(value) && value != "null") {
					emsPushListDataDto.setInputData(new BigDecimal(value));
					//bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
				}
				if (emsPushListDataDto.getInputData() != null) {
					listData.add(emsPushListDataDto);
				}
			}
		}
		emsPushInfoDto.setListData(listData);

		String result = "";

		try {
			HttpHeaders headers = new HttpHeaders();
			MediaType mediaType = MediaType.parseMediaType("application/json; charset=UTF-8");
			headers.setContentType(mediaType);
			headers.add("Accept", MediaType.APPLICATION_JSON.toString());
			HttpEntity<EmsPushInfoDto> httpEntity = new HttpEntity<>(emsPushInfoDto, headers);
			//使用exchange请求接口
			ResponseEntity<String> exchange = restTemplate.exchange(url + "/api/ems-cloud-service/common/inputData", HttpMethod.POST, httpEntity, String.class);
			result = JSON.toJSONString(exchange);
		}catch (Exception ex){
			result = "Result（接口调用异常）:" + ex.getMessage();
		}

		try {
			SysLog syslog = new SysLog();
			syslog.setCreateTime(new Date());
			syslog.setType("info");
			syslog.setCreateUserId(BaseContextHandler.getUserID());
			syslog.setCreateUserName("SYSTEM");
			syslog.setContent(JSON.toJSONString(emsPushInfoDto));
			syslog.setResult(result);
			syslog.setCreateUserId(-1);
			syslog.setMethodName("energyManageIssueScheduling()");
			syslog.setStatus(1);
			syslog.setName("MES->EMS能源管理系统");
			String serverAddr = url + "/api/ems-cloud-service/common/inputData";
			syslog.setServerAddr(serverAddr);
			syslog.setReqType("HTTP");
			syslog.setReqIp(IpUtils.getLocalIP());
			sysLogService.save(syslog);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResultGenerator.success(emsPushInfoDto);
	}

	public CastMaterialInfoDto toLazyDto(CastMaterialInfo entity) {
		return modelMapper.map(entity, CastMaterialInfoDto.class);
	}

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

	public CastMaterialInfo fromDto(CastMaterialInfoDto dto) {
		return modelMapper.map(dto, CastMaterialInfo.class);
	}


}
