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.AccessoryApplyFeedbackDto;
import com.sw.mes.yb.accessory.entity.AccessoryApplyFeedback;
import com.sw.mes.yb.accessory.service.AccessoryApplyFeedbackService;
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("/accessoryApplyFeedback")
@Slf4j
@Api(description = "辅料申请反馈接口wms→mes(要料拒绝)")
@Validated
public class AccessoryApplyFeedbackController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private AccessoryApplyFeedbackService accessoryApplyFeedbackService;

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

	@ApiOperation(value = "辅料申请反馈详细信息")
	@GetMapping("/{id}")
	public Result<AccessoryApplyFeedbackDto> get(@PathVariable @ApiParam(value="辅料申请反馈id") Integer id) {
		AccessoryApplyFeedback accessoryApplyFeedback = accessoryApplyFeedbackService.get(id);
		if (null == accessoryApplyFeedback) {
            return ResultGenerator.fail("该辅料申请反馈不存在");
        }
		return ResultGenerator.success(toEagerDto(accessoryApplyFeedback));
	}

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

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

	public AccessoryApplyFeedbackDto toLazyDto(AccessoryApplyFeedback entity) {
		return modelMapper.map(entity, AccessoryApplyFeedbackDto.class);
	}

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

	public AccessoryApplyFeedback fromDto(AccessoryApplyFeedbackDto dto) {
		return modelMapper.map(dto, AccessoryApplyFeedback.class);
	}


}
