package com.sw.mes.yb.turnstore.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.turnstore.dto.TurnstoreInItemDto;
import com.sw.mes.yb.turnstore.entity.TurnstoreIn;
import com.sw.mes.yb.turnstore.entity.TurnstoreInItem;
import com.sw.mes.yb.turnstore.service.TurnstoreInItemService;
import com.sw.mes.yb.turnstore.service.TurnstoreInService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
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("/turnstoreInItem")
@Slf4j
@Api(description = "周转库入库申请明细接口")
public class TurnstoreInItemController {
	@Autowired
    ModelMapper modelMapper;

	@Autowired
	private TurnstoreInItemService turnstoreInItemService;

	@Autowired
	private TurnstoreInService turnstoreInService;

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

	@ApiOperation(value = "周转库入库申请明细详细信息")
	@GetMapping("/{id}")
	public Result<TurnstoreInItemDto> get(@PathVariable @ApiParam(value="周转库入库申请明细id") Integer id) {
		TurnstoreInItem turnstoreInItem = turnstoreInItemService.get(id);
		if (null == turnstoreInItem) {
            return ResultGenerator.fail("该周转库入库申请明细不存在");
        }
		return ResultGenerator.success(toEagerDto(turnstoreInItem));
	}

	@ApiOperation(value = "创建周转库入库申请明细")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "周转库入库申请明细对象") TurnstoreInItemDto turnstoreInItemDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		TurnstoreInItem turnstoreInItem = fromDto(turnstoreInItemDto);
		turnstoreInItemService.saveOrUpdate(turnstoreInItem);
		return ResultGenerator.success();
	}

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

	@ApiOperation(value = "根据单号获取入库申请明细")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orderNo", value = "入库单号", dataType = "string", paramType = "query"),
	})
	@GetMapping("/getItemsByOrderNo")
	public Result getItemsByOrderNo(String orderNo){
		if(StringUtils.isBlank(orderNo)){
			return ResultGenerator.fail("入库单号不能为空");
		}
		return ResultGenerator.success(turnstoreInItemService.getItemsByOrderNo(orderNo));
	}

	public TurnstoreInItemDto toLazyDto(TurnstoreInItem entity) {
		//ModelMapper modelMapper = new ModelMapper();
		modelMapper.getConfiguration().setFullTypeMatchingRequired(true);
		modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
		TurnstoreInItemDto turnstoreInItemDto = modelMapper.map(entity, TurnstoreInItemDto.class);
		//PDA中备注
		if (null != entity.getInId()){
			TurnstoreIn turnstoreIn = turnstoreInService.get(entity.getInId());
			if (null != turnstoreIn){
				turnstoreInItemDto.setWithdrawinRemark(turnstoreIn.getRemark());
			}
		}
		return turnstoreInItemDto;
	}

	public TurnstoreInItemDto toEagerDto(TurnstoreInItem entity) {
		//ModelMapper modelMapper = new ModelMapper();
		modelMapper.getConfiguration().setFullTypeMatchingRequired(true);
		modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
		TurnstoreInItemDto dto = modelMapper.map(entity, TurnstoreInItemDto.class);
		return dto;
	}

	public TurnstoreInItem fromDto(TurnstoreInItemDto dto) {
		//ModelMapper modelMapper = new ModelMapper();
		modelMapper.getConfiguration().setFullTypeMatchingRequired(true);
		modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
		return modelMapper.map(dto, TurnstoreInItem.class);
	}


}
