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

import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.service.DictionaryItemService;
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 com.sw.mes.yb.report.dto.CrystalPullingInfoRunTimeDto;
import com.sw.mes.yb.report.entity.CrystalPullingInfo;
import com.sw.mes.yb.report.service.CrystalPullingInfoService;
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 javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import com.sw.mes.yb.report.entity.CrystalPullingInfoLog;
import com.sw.mes.yb.report.dto.CrystalPullingInfoLogDto;
import com.sw.mes.yb.report.service.CrystalPullingInfoLogService;


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

	@Autowired
	private CrystalPullingInfoLogService crystalPullingInfoLogService;

	@Autowired
	private DictionaryItemService dictionaryItemService;

	@Autowired
	private CrystalPullingInfoService crystalPullingInfoService;

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

		//开始时间取上一炉次的停炉时间，重新赋值,需求同包头mes
		dtos.stream().forEach(dto -> {
			CrystalPullingInfoLog log = crystalPullingInfoLogService.getCrystalPullingInfoLogByDeviceNoAndLotNo(dto.getDeviceNo(), dto.getLotNo());
			if (null != log && null != log.getStopTime()){
				dto.setStartTime(log.getStopTime());
			}
		});

		ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
	}

	@ApiOperation(value = "获取所有CrystalPullingInfoLog")
	@GetMapping("/listAll")
	public Result<List<CrystalPullingInfoLogDto>> listAll(ServletRequest request) {
		Specification<CrystalPullingInfoLog> specification = DynamicSpecifications.bySearchFilter(request, CrystalPullingInfoLog.class);
		List<CrystalPullingInfoLog> crystalPullingInfoLogs = crystalPullingInfoLogService.findByExampleSort(specification, null);
		List<CrystalPullingInfoLogDto> crystalPullingInfoLogDtos = crystalPullingInfoLogs.stream()
					.map(crystalPullingInfoLog -> toLazyDto(crystalPullingInfoLog))
					.collect(Collectors.toList());
		return ResultGenerator.success(crystalPullingInfoLogDtos);
	}

	@ApiOperation(value = "CrystalPullingInfoLog详细信息")
	@GetMapping("/{id}")
	public Result<CrystalPullingInfoLogDto> get(@PathVariable @ApiParam(value="CrystalPullingInfoLogid") Long id) {
		CrystalPullingInfoLog crystalPullingInfoLog = crystalPullingInfoLogService.get(id);
		if (null == crystalPullingInfoLog)
			return ResultGenerator.fail("该CrystalPullingInfoLog不存在");
		return ResultGenerator.success(toEagerDto(crystalPullingInfoLog));
	}


	/**
	 * 查询此时停炉时经历的实际运行时长,判定是否为异常停炉
	 * 0810
	 * @param lotNo
	 * @param deviceNo
	 * @return
	 */
	@ApiOperation(value = "查询此时停炉时经历的实际运行时长,判定是否为异常停炉，并返回前端结果，true:异常停炉;false：正常停炉")
	@GetMapping("/getRunTimeInfo")
	public Result<CrystalPullingInfoRunTimeDto> getRunTimeInfo(@NotBlank(message = "炉次号不能为空")@RequestParam String  lotNo, @NotBlank(message = "设备编号不能为空")@RequestParam String deviceNo) {

		return crystalPullingInfoLogService.getRunTimeInfo(lotNo,deviceNo);
	}





	@ApiOperation(value = "创建CrystalPullingInfoLog")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "CrystalPullingInfoLog对象") CrystalPullingInfoLogDto crystalPullingInfoLogDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		CrystalPullingInfoLog crystalPullingInfoLog = fromDto(crystalPullingInfoLogDto);
		crystalPullingInfoLogService.saveOrUpdate(crystalPullingInfoLog);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新CrystalPullingInfoLog")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "CrystalPullingInfoLog") CrystalPullingInfoLogDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
            CrystalPullingInfoLog entity = crystalPullingInfoLogService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");

        //是否有异常时间
		Boolean flag = false;
		if (null == entity.getStandbyTime()){
			entity.setStandbyTime(BigDecimal.ZERO);
		}
		if (null != dto.getStandbyTime() && dto.getStandbyTime().compareTo(entity.getStandbyTime()) != 0){
			flag = true;
		}


        try {
            CrystalPullingInfoLog entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));


			//true 涉及异常时间修改的,重新计算实际运行时间
			if (flag){
				if (null != entity.getStopTime()){
					CrystalPullingInfoLog pullingInfoLogOld = crystalPullingInfoLogService.getCrystalPullingInfoLogByDeviceNoAndLotNo(entity.getDeviceNo(),entity.getLotNo());//上一炉次的拉晶情况记录表
					if (null!= pullingInfoLogOld && null != pullingInfoLogOld.getStopTime()){
						long runTimeLen1 = entity.getStopTime().getTime() - pullingInfoLogOld.getStopTime().getTime();
						double _runTime1 = runTimeLen1 / 1000 / 60 / 60d;
						if (null == dto.getStandbyTime()){
							BigDecimal runTimeActual = new BigDecimal(_runTime1).setScale(2, BigDecimal.ROUND_DOWN);
							entity.setRunTimeActual(runTimeActual);
						}else {
							BigDecimal runTimeActual = new BigDecimal(_runTime1).setScale(2, BigDecimal.ROUND_DOWN);
							BigDecimal subtract = runTimeActual.subtract(dto.getStandbyTime());
							entity.setRunTimeActual(subtract);
						}
					}
				}
			}


			crystalPullingInfoLogService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

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

	public CrystalPullingInfoLogDto toLazyDto(CrystalPullingInfoLog entity) {
		return modelMapper.map(entity, CrystalPullingInfoLogDto.class);
	}

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

	public CrystalPullingInfoLog fromDto(CrystalPullingInfoLogDto dto) {
		return modelMapper.map(dto, CrystalPullingInfoLog.class);
	}


}
