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

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.core.utils.BeanUtil;
import com.sw.mes.core.utils.DynamicSpecifications;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
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.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import com.sw.mes.yb.report.entity.CrystalPullingInfo;
import com.sw.mes.yb.report.dto.CrystalPullingInfoDto;
import com.sw.mes.yb.report.service.CrystalPullingInfoService;


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

	@Autowired
	private CrystalPullingInfoService crystalPullingInfoService;

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

	@ApiOperation(value = "获取所有CrystalPullingInfo")
	@GetMapping("/listAll")
	public Result<List<CrystalPullingInfoDto>> listAll(ServletRequest request) {
		Specification<CrystalPullingInfo> specification = DynamicSpecifications.bySearchFilter(request, CrystalPullingInfo.class);
		List<CrystalPullingInfo> crystalPullingInfos = crystalPullingInfoService.findByExampleSort(specification, null);
		List<CrystalPullingInfoDto> crystalPullingInfoDtos = crystalPullingInfos.stream()
					.map(crystalPullingInfo -> toLazyDto(crystalPullingInfo))
					.collect(Collectors.toList());
//		for (CrystalPullingInfoDto crystalPullingInfoDto : crystalPullingInfoDtos){
//			crystalPullingInfoDto.setRunTime(getTime(crystalPullingInfoDto.getDataUpdateTime(),new Date()));
//		}
		return ResultGenerator.success(crystalPullingInfoDtos);
	}

	@ApiOperation(value = "CrystalPullingInfo详细信息")
	@GetMapping("/{id}")
	public Result<CrystalPullingInfoDto> get(@PathVariable @ApiParam(value="CrystalPullingInfoid") Long id) {
		CrystalPullingInfo crystalPullingInfo = crystalPullingInfoService.get(id);
		if (null == crystalPullingInfo)
			return ResultGenerator.fail("该CrystalPullingInfo不存在");
		CrystalPullingInfoDto crystalPullingInfoDto = toEagerDto(crystalPullingInfo);
//		crystalPullingInfoDto.setRunTime(getTime(crystalPullingInfoDto.getDataUpdateTime(),new Date()));
		return ResultGenerator.success(crystalPullingInfoDto);
	}

	@ApiOperation(value = "创建CrystalPullingInfo")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "CrystalPullingInfo对象") CrystalPullingInfoDto crystalPullingInfoDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		CrystalPullingInfo crystalPullingInfo = fromDto(crystalPullingInfoDto);
		crystalPullingInfoService.saveOrUpdate(crystalPullingInfo);
		return ResultGenerator.success();
	}

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

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

	public CrystalPullingInfoDto toLazyDto(CrystalPullingInfo entity) {
		return modelMapper.map(entity, CrystalPullingInfoDto.class);
	}

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

	public CrystalPullingInfo fromDto(CrystalPullingInfoDto dto) {
		return modelMapper.map(dto, CrystalPullingInfo.class);
	}

	public BigDecimal getTime(Date startDate, Date endDate){
		Double hour = 0d;
		if (startDate == null || startDate.after(endDate)) {
			return new BigDecimal(0);
		}
		long startTime = startDate.getTime();
		long endTime = endDate.getTime();
		hour = ((endTime-startTime)/1000d)/60/60;
        return  BigDecimal.valueOf(hour).setScale(0, BigDecimal.ROUND_DOWN);
	}
}
