package com.sw.mes.yb.production.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 com.sw.mes.yb.production.dto.FbProductCardDto;
import com.sw.mes.yb.production.entity.FbProductCard;
import com.sw.mes.yb.production.service.FbProductCardService;
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;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/fbProductCard")
@Slf4j
@Api(description = "产品标准卡接口")
public class FbProductCardController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private FbProductCardService fbProductCardService;

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

	@ApiOperation(value = "产品标准卡详细信息")
	@GetMapping("/{id}")
	public Result<FbProductCardDto> get(@PathVariable @ApiParam(value="产品标准卡id") Integer id) {
		FbProductCard fbProductCard = fbProductCardService.get(id);
		if (null == fbProductCard)
			return ResultGenerator.fail("该产品标准卡不存在");
		return ResultGenerator.success(toEagerDto(fbProductCard));
	}

	@ApiOperation(value = "创建产品标准卡")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "产品标准卡对象") FbProductCardDto fbProductCardDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		FbProductCard fbProductCard = fromDto(fbProductCardDto);
		fbProductCard.setCreateTime(new Date());
		fbProductCard.setCreateUser(BaseContextHandler.getUsername());
		fbProductCard.setCreateUserId(BaseContextHandler.getUserID());
		fbProductCardService.saveOrUpdate(fbProductCard);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新产品标准卡")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "产品标准卡") FbProductCardDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
            FbProductCard entity = fbProductCardService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            FbProductCard entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			entity.setUpdateTime(new Date());
			entity.setUpdateUser(BaseContextHandler.getUsername());
			entity.setUpdateUserId(BaseContextHandler.getUserID());
			fbProductCardService.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") @RequestBody Integer[] ids) {
		for (Integer id : ids) {
				fbProductCardService.softDelete(id);
		}
		return ResultGenerator.success();
	}

	public FbProductCardDto toLazyDto(FbProductCard entity) {
		return modelMapper.map(entity, FbProductCardDto.class);
	}

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

	public FbProductCard fromDto(FbProductCardDto dto) {
		return modelMapper.map(dto, FbProductCard.class);
	}


}
