package com.sw.mes.outside.controller;

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.core.utils.*;
import com.sw.mes.outside.dto.DeviceStopStoveInfoDto;
import com.sw.mes.outside.dto.ToMESData;
import com.sw.mes.outside.entity.DeviceStopStoveInfo;
import com.sw.mes.outside.service.DeviceStopStoveInfoService;
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.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/deviceStopStoveInfo")
@Slf4j
@Api(description = "DeviceStopStoveInfo接口")
public class DeviceStopStoveInfoController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private DeviceStopStoveInfoService deviceStopStoveInfoService;

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

	@ApiOperation(value = "获取所有DeviceStopStoveInfo")
	@GetMapping("/listAll")
	public Result<List<DeviceStopStoveInfoDto>> listAll(ServletRequest request) {
		Specification<DeviceStopStoveInfo> specification = DynamicSpecifications.bySearchFilter(request, DeviceStopStoveInfo.class);
		List<DeviceStopStoveInfo> deviceStopStoveInfos = deviceStopStoveInfoService.findByExampleSort(specification, null);
		List<DeviceStopStoveInfoDto> deviceStopStoveInfoDtos = deviceStopStoveInfos.stream()
					.map(deviceStopStoveInfo -> toLazyDto(deviceStopStoveInfo))
					.collect(Collectors.toList());
		return ResultGenerator.success(deviceStopStoveInfoDtos);
	}

	@ApiOperation(value = "DeviceStopStoveInfo详细信息")
	@GetMapping("/{id}")
	public Result<DeviceStopStoveInfoDto> get(@PathVariable @ApiParam(value="DeviceStopStoveInfoid") Integer id) {
		DeviceStopStoveInfo deviceStopStoveInfo = deviceStopStoveInfoService.get(id);
		if (null == deviceStopStoveInfo)
			return ResultGenerator.fail("该DeviceStopStoveInfo不存在");
		return ResultGenerator.success(toEagerDto(deviceStopStoveInfo));
	}

	@ApiOperation(value = "创建DeviceStopStoveInfo")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "DeviceStopStoveInfo对象") DeviceStopStoveInfoDto deviceStopStoveInfoDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		DeviceStopStoveInfo deviceStopStoveInfo = fromDto(deviceStopStoveInfoDto);
		deviceStopStoveInfoService.saveOrUpdate(deviceStopStoveInfo);
		return ResultGenerator.success();
	}

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

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


	@ApiOperation(value = "设备停炉记录接收")
	@PostMapping("/getDeviceStopStove")
	public Result getDeviceStopStove(@RequestBody ToMESData toMESData){

		if(StringUtils.isEmpty(toMESData.getDeviceCode())){
			return ResultGenerator.fail("设备编号不能为空");
		}
		if(toMESData.getStartTime() == null){
			return ResultGenerator.fail("停炉时间不能为空");
		}
		String deviceNo = toMESData.getDeviceCode();
		DeviceStopStoveInfo deviceStopStoveInfo = deviceStopStoveInfoService.findByDeviceNo(deviceNo);
		if(deviceStopStoveInfo == null){
			deviceStopStoveInfo = new DeviceStopStoveInfo();
		}
		Date stopStoveTime = toMESData.getStartTime();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(stopStoveTime);
		calendar.add(Calendar.HOUR,3);
		Date clearPotTime = calendar.getTime();

		deviceStopStoveInfo.setDeviceNo(toMESData.getDeviceCode());
		deviceStopStoveInfo.setStopStoveTime(toMESData.getStartTime());
		deviceStopStoveInfo.setClearPotTime(clearPotTime);
		deviceStopStoveInfo.setCreateTime(new Date());
		deviceStopStoveInfoService.saveOrUpdate(deviceStopStoveInfo);

		return ResultGenerator.success();
	}


	public DeviceStopStoveInfoDto toLazyDto(DeviceStopStoveInfo entity) {
		return modelMapper.map(entity, DeviceStopStoveInfoDto.class);
	}

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

	public DeviceStopStoveInfo fromDto(DeviceStopStoveInfoDto dto) {
		return modelMapper.map(dto, DeviceStopStoveInfo.class);
	}


}
