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

import com.sw.mes.core.entity.SearchFilter;
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 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.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.sw.mes.yb.pc.entity.EstimatedRecord;
import com.sw.mes.yb.pc.dto.EstimatedRecordDto;
import com.sw.mes.yb.pc.service.EstimatedRecordService;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/EstimatedRecord")
@Slf4j
@Api(description = "预取棒记录接口")
public class EstimatedRecordController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private EstimatedRecordService estimatedRecordService;

    @ApiOperation("分页查询预取棒记录列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_deviceCode", value = "设备号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_nodeTime", value = "取段/停炉开始时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LTE_nodeTime", value = "取段/停炉结束时间", dataType = "string", paramType = "query"),

    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<EstimatedRecordDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<EstimatedRecord> specification = DynamicSpecifications.bySearchFilter(request, EstimatedRecord.class,
                new SearchFilter("isDeleted", SearchFilter.Operator.EQ, 0),
                new SearchFilter("takeTime", SearchFilter.Operator.GT, DateUtil.addMinute(new Date(), -30)));
        requestPage.setOrderField("nodeTime");
        requestPage.setOrderDirection("DESC");
        Page<EstimatedRecord> page = estimatedRecordService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<EstimatedRecordDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation("获取所有预取棒记录")
    @GetMapping("/listAll")
    public Result<List<EstimatedRecordDto>> listAll(ServletRequest request) {
        Specification<EstimatedRecord> specification = DynamicSpecifications.bySearchFilter(request, EstimatedRecord.class);
        List<EstimatedRecord> estimatedRecords = estimatedRecordService.findByExampleSort(specification, null);
        List<EstimatedRecordDto> estimatedRecordDtos = estimatedRecords.stream()
                .map(estimatedRecord -> toLazyDto(estimatedRecord))
                .collect(Collectors.toList());
        return ResultGenerator.success(estimatedRecordDtos);
    }

    @ApiOperation("预取棒记录详细信息")
    @GetMapping("/{id}")
    public Result<EstimatedRecordDto> get(@PathVariable @ApiParam(value = "预取棒记录id") Integer id) {
        EstimatedRecord estimatedRecord = estimatedRecordService.get(id);
        if (null == estimatedRecord) {
            return ResultGenerator.fail("该预取棒记录不存在");
        }
        return ResultGenerator.success(toEagerDto(estimatedRecord));
    }

    @ApiOperation("创建预取棒记录")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "预取棒记录对象") EstimatedRecordDto estimatedRecordDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        EstimatedRecord estimatedRecord = fromDto(estimatedRecordDto);
        estimatedRecordService.saveOrUpdate(estimatedRecord);
        return ResultGenerator.success();
    }

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

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

    @ApiOperation("删除超过半小时的预取棒记录")
    @PostMapping("/deleteBeforeHalfHourEstimatedRecord")
    public Result remove() {
        Date halfHour = DateUtil.addMinute(new Date(), -30);
        estimatedRecordService.deleteBeforeHalfHourEstimatedRecord(halfHour,new Date());
        return ResultGenerator.success();
    }

    public EstimatedRecordDto toLazyDto(EstimatedRecord entity) {
        return modelMapper.map(entity, EstimatedRecordDto.class);
    }

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

    public EstimatedRecord fromDto(EstimatedRecordDto dto) {
        return modelMapper.map(dto, EstimatedRecord.class);
    }


}
