package com.sw.mes.fb.instoreapply.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.fb.instoreapply.dto.InstoreApplyItemDto;
import com.sw.mes.fb.instoreapply.entity.InstoreApplyItem;
import com.sw.mes.fb.instoreapply.service.InstoreApplyItemService;
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;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/instoreApplyItem")
@Slf4j
@Api(description = "入库申请明细表接口")
public class InstoreApplyItemController {
	@Autowired
    ModelMapper modelMapper;

	@Autowired
	private InstoreApplyItemService instoreApplyItemService;

	@ApiOperation(value = "分页查询入库申请明细表列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<InstoreApplyItemDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
		Specification<InstoreApplyItem> specification = DynamicSpecifications.bySearchFilter(request, InstoreApplyItem.class);
    	Page<InstoreApplyItem> page = instoreApplyItemService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<InstoreApplyItemDto> 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<InstoreApplyItemDto>> listAll(ServletRequest request) {
		Specification<InstoreApplyItem> specification = DynamicSpecifications.bySearchFilter(request, InstoreApplyItem.class);
		List<InstoreApplyItem> instoreApplyItems = instoreApplyItemService.findByExampleSort(specification, null);
		List<InstoreApplyItemDto> instoreApplyItemDtos = instoreApplyItems.stream()
					.map(instoreApplyItem -> toLazyDto(instoreApplyItem))
					.collect(Collectors.toList());
		return ResultGenerator.success(instoreApplyItemDtos);
	}

	@ApiOperation(value = "入库申请明细表详细信息")
	@GetMapping("/{id}")
	public Result<InstoreApplyItemDto> get(@PathVariable @ApiParam(value="入库申请明细表id") Integer id) {
		InstoreApplyItem instoreApplyItem = instoreApplyItemService.get(id);
		if (null == instoreApplyItem)
			return ResultGenerator.fail("该入库申请明细表不存在");
		return ResultGenerator.success(toEagerDto(instoreApplyItem));
	}

	@ApiOperation(value = "创建入库申请明细表")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "入库申请明细表对象") InstoreApplyItemDto instoreApplyItemDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		InstoreApplyItem instoreApplyItem = fromDto(instoreApplyItemDto);
		instoreApplyItemService.saveOrUpdate(instoreApplyItem);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新入库申请明细表")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "入库申请明细表") InstoreApplyItemDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
            InstoreApplyItem entity = instoreApplyItemService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            InstoreApplyItem entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			instoreApplyItemService.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) {
				instoreApplyItemService.delete(id);
		}
		return ResultGenerator.success();
	}

	public InstoreApplyItemDto toLazyDto(InstoreApplyItem entity) {
		return modelMapper.map(entity, InstoreApplyItemDto.class);
	}

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

	public InstoreApplyItem fromDto(InstoreApplyItemDto dto) {
		return modelMapper.map(dto, InstoreApplyItem.class);
	}


}
