package com.sw.mes.yb.accessory.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.accessory.dto.AccessoryReturnFeedbackDto;
import com.sw.mes.yb.accessory.entity.AccessoryReturnFeedback;
import com.sw.mes.yb.accessory.service.AccessoryReturnFeedbackService;
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.validation.annotation.Validated;
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("/accessoryReturnFeedback")
@Slf4j
@Api(description = "辅料退库反馈接口wms→mes(辅料退料拒绝)")
@Validated
public class AccessoryReturnFeedbackController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private AccessoryReturnFeedbackService accessoryReturnFeedbackService;

	@ApiOperation(value = "分页查询辅料退库反馈列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<AccessoryReturnFeedbackDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
		Specification<AccessoryReturnFeedback> specification = DynamicSpecifications.bySearchFilter(request, AccessoryReturnFeedback.class);
    	Page<AccessoryReturnFeedback> page = accessoryReturnFeedbackService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<AccessoryReturnFeedbackDto> 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<AccessoryReturnFeedbackDto>> listAll(ServletRequest request) {
		Specification<AccessoryReturnFeedback> specification = DynamicSpecifications.bySearchFilter(request, AccessoryReturnFeedback.class);
		List<AccessoryReturnFeedback> accessoryReturnFeedbacks = accessoryReturnFeedbackService.findByExampleSort(specification, null);
		List<AccessoryReturnFeedbackDto> accessoryReturnFeedbackDtos = accessoryReturnFeedbacks.stream()
					.map(accessoryReturnFeedback -> toLazyDto(accessoryReturnFeedback))
					.collect(Collectors.toList());
		return ResultGenerator.success(accessoryReturnFeedbackDtos);
	}

	@ApiOperation(value = "辅料退库反馈详细信息")
	@GetMapping("/{id}")
	public Result<AccessoryReturnFeedbackDto> get(@PathVariable @ApiParam(value="辅料退库反馈id") Integer id) {
		AccessoryReturnFeedback accessoryReturnFeedback = accessoryReturnFeedbackService.get(id);
		if (null == accessoryReturnFeedback) {
            return ResultGenerator.fail("该辅料退库反馈不存在");
        }
		return ResultGenerator.success(toEagerDto(accessoryReturnFeedback));
	}

	@ApiOperation(value = "创建辅料退库反馈")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "辅料退库反馈对象") List<AccessoryReturnFeedbackDto> dtos, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		if(dtos.isEmpty()){
		    throw new RuntimeException("收到的参数为空");
        }
		accessoryReturnFeedbackService.batchSaveFeedback(dtos);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新辅料退库反馈")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "辅料退库反馈") AccessoryReturnFeedbackDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
            AccessoryReturnFeedback entity = accessoryReturnFeedbackService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            AccessoryReturnFeedback entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			accessoryReturnFeedbackService.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) {
				accessoryReturnFeedbackService.delete(id);
		}
		return ResultGenerator.success();
	}

	public AccessoryReturnFeedbackDto toLazyDto(AccessoryReturnFeedback entity) {
		return modelMapper.map(entity, AccessoryReturnFeedbackDto.class);
	}

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

	public AccessoryReturnFeedback fromDto(AccessoryReturnFeedbackDto dto) {
		return modelMapper.map(dto, AccessoryReturnFeedback.class);
	}


}
