package com.sw.mes.yb.report.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.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.CrystalBrokenBaseDto;
import com.sw.mes.yb.report.dto.CrystalBrokenBaseReasonDto;
import com.sw.mes.yb.report.entity.CrystalBrokenBase;
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.report.service.CrystalBrokenBaseService;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/crystalBrokenBase")
@Slf4j
@Api(description = "引断基础表接口")
public class CrystalBrokenBaseController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private CrystalBrokenBaseService crystalBrokenBaseService;

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

	@ApiOperation(value = "获取所有CrystalBrokenBase")
	@GetMapping("/listAll")
	public Result<List<CrystalBrokenBaseDto>> listAll(ServletRequest request) {
		Specification<CrystalBrokenBase> specification = DynamicSpecifications.bySearchFilter(request, CrystalBrokenBase.class);
		List<CrystalBrokenBase> crystalBrokenBases = crystalBrokenBaseService.findByExampleSort(specification, null);
		List<CrystalBrokenBaseDto> crystalBrokenBaseDtos = crystalBrokenBases.stream()
					.map(crystalBrokenBase -> toLazyDto(crystalBrokenBase))
					.collect(Collectors.toList());
		return ResultGenerator.success(crystalBrokenBaseDtos);
	}

	@ApiOperation(value = "CrystalBrokenBase详细信息")
	@GetMapping("/{id}")
	public Result<CrystalBrokenBaseDto> get(@PathVariable @ApiParam(value="CrystalBrokenBaseid") Long id) {
		CrystalBrokenBase crystalBrokenBase = crystalBrokenBaseService.get(id);
		if (null == crystalBrokenBase)
			return ResultGenerator.fail("该CrystalBrokenBase不存在");
		return ResultGenerator.success(toEagerDto(crystalBrokenBase));
	}

	@ApiOperation(value = "创建CrystalBrokenBase")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "CrystalBrokenBase对象") CrystalBrokenBaseDto crystalBrokenBaseDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		CrystalBrokenBase crystalBrokenBase = fromDto(crystalBrokenBaseDto);
		crystalBrokenBaseService.saveOrUpdate(crystalBrokenBase);
		return ResultGenerator.success();
	}

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

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

	public CrystalBrokenBaseDto toLazyDto(CrystalBrokenBase entity) {
		return modelMapper.map(entity, CrystalBrokenBaseDto.class);
	}

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

	public CrystalBrokenBase fromDto(CrystalBrokenBaseDto dto) {
		return modelMapper.map(dto, CrystalBrokenBase.class);
	}


	@ApiOperation(value = "更新CrystalBrokenBase原因类型、原因分析")
	@PostMapping("/updateReason")
	public Result updateReason(@RequestBody @Valid @ApiParam(value = "CrystalBrokenBaseReasonDto") CrystalBrokenBaseReasonDto dto, BindingResult bindingResult) {
		if (bindingResult.hasErrors())
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		if (dto.getIds() == null)
			return ResultGenerator.fail("id不能为空");
		try {
			for (Long id : dto.getIds()) {
				CrystalBrokenBase entity = crystalBrokenBaseService.get(id);
				if (entity != null){
					entity.setReasonType(dto.getReasonType());
					entity.setReasonInfo(dto.getReasonInfo());
					if (entity.getOperationUser() == null || entity.getOperationUser() == ""){
						entity.setOperationUser(dto.getUser());
						entity.setOperationTime(new Date());
					}else{
						entity.setUpdateUser(dto.getUser());
						entity.setUpdateTime(new Date());
					}
					crystalBrokenBaseService.saveOrUpdate(entity);
				}
			}
			return ResultGenerator.success();
		} catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}

}
