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 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.List;
import java.util.stream.Collectors;
import com.sw.mes.outside.entity.AlarmData;
import com.sw.mes.outside.dto.AlarmDataDto;
import com.sw.mes.outside.service.AlarmDataService;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/AlarmData")
@Slf4j
@Api(description = "报警数据接口")
public class AlarmDataController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private AlarmDataService alarmDataService;

	@ApiOperation(value = "分页查询报警数据列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<AlarmDataDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		Specification<AlarmData> specification = DynamicSpecifications.bySearchFilter(request, AlarmData.class);
    	Page<AlarmData> page = alarmDataService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<AlarmDataDto> 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<AlarmDataDto>> listAll(ServletRequest request) {
		Specification<AlarmData> specification = DynamicSpecifications.bySearchFilter(request, AlarmData.class);
		List<AlarmData> alarmDatas = alarmDataService.findByExampleSort(specification, null);
		List<AlarmDataDto> alarmDataDtos = alarmDatas.stream()
					.map(alarmData -> toLazyDto(alarmData))
					.collect(Collectors.toList());
		return ResultGenerator.success(alarmDataDtos);
	}

	@ApiOperation(value = "报警数据详细信息")
	@GetMapping("/{id}")
	public Result<AlarmDataDto> get(@PathVariable @ApiParam(value="报警数据id") Long id) {
		AlarmData alarmData = alarmDataService.get(id);
		if (null == alarmData){
			return ResultGenerator.fail("该报警数据不存在");
		}
		return ResultGenerator.success(toEagerDto(alarmData));
	}

	@ApiOperation(value = "创建报警数据")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "报警数据对象") AlarmDataDto alarmDataDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		AlarmData alarmData = fromDto(alarmDataDto);
		alarmDataService.saveOrUpdate(alarmData);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新报警数据")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "报警数据") AlarmDataDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
        if (dto.getId() == null){
            return ResultGenerator.fail("id不能为空");
		}
		AlarmData entity = alarmDataService.get(dto.getId());
        if (entity == null){
            return ResultGenerator.fail("原信息不存在");
		}
        try {
            AlarmData entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			alarmDataService.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) {
				alarmDataService.delete(id);
		}
		return ResultGenerator.success();
	}

	public AlarmDataDto toLazyDto(AlarmData entity) {
		return modelMapper.map(entity, AlarmDataDto.class);
	}

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

	public AlarmData fromDto(AlarmDataDto dto) {
		return modelMapper.map(dto, AlarmData.class);
	}


}
