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.TurnstoreOutItemDto;
import com.sw.mes.yb.turnstore.entity.TurnstoreOutItem;
import com.sw.mes.yb.turnstore.service.TurnstoreOutItemService;
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("/turnstoreOutItem")
@Slf4j
@Api(description = "周转库出库申请明细接口")
public class TurnstoreOutItemController {
	@Autowired
    ModelMapper modelMapper;

	@Autowired
	private TurnstoreOutItemService turnstoreOutItemService;

	@ApiOperation(value = "分页查询周转库出库申请明细列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<TurnstoreOutItemDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
		Specification<TurnstoreOutItem> specification = DynamicSpecifications.bySearchFilter(request, TurnstoreOutItem.class);
    	Page<TurnstoreOutItem> page = turnstoreOutItemService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<TurnstoreOutItemDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
		List<String> sectionItems=dtos.stream().map(TurnstoreOutItemDto::getSectionNo).collect(Collectors.toList());
		/*if(sectionItems!=null&&sectionItems.size()>0){
			List<SapSectionMaterialNumber> sapSectionMaterialNumberList = sapSectionMaterialNumberService.getListBySectionList(sectionItems);
			for(TurnstoreOutItemDto turnstoreOutItemDto:dtos){
				for(SapSectionMaterialNumber sapSectionMaterialNumber:sapSectionMaterialNumberList){
					if(turnstoreOutItemDto.getSectionNo().equals(sapSectionMaterialNumber.getSectionNo())){
						turnstoreOutItemDto.setSapOrderNo(sapSectionMaterialNumber.getSapOrderNo());
						turnstoreOutItemDto.setMaterialNumber(sapSectionMaterialNumber.getNewMaterialNumber());
						break;
					}

				}
			}
		}*/
		ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
	}

	@ApiOperation(value = "获取所有周转库出库申请明细")
	@GetMapping("/listAll")
	public Result<List<TurnstoreOutItemDto>> listAll(ServletRequest request) {
		Specification<TurnstoreOutItem> specification = DynamicSpecifications.bySearchFilter(request, TurnstoreOutItem.class);
		List<TurnstoreOutItem> turnstoreOutItems = turnstoreOutItemService.findByExampleSort(specification, null);
		List<TurnstoreOutItemDto> turnstoreOutItemDtos = turnstoreOutItems.stream()
					.map(turnstoreOutItem -> toLazyDto(turnstoreOutItem))
					.collect(Collectors.toList());
		return ResultGenerator.success(turnstoreOutItemDtos);
	}

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

	@ApiOperation(value = "创建周转库出库申请明细")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "周转库出库申请明细对象") TurnstoreOutItemDto turnstoreOutItemDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		TurnstoreOutItem turnstoreOutItem = fromDto(turnstoreOutItemDto);
		turnstoreOutItemService.saveOrUpdate(turnstoreOutItem);
		return ResultGenerator.success();
	}

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

	public TurnstoreOutItemDto toLazyDto(TurnstoreOutItem entity) {
		//ModelMapper modelMapper = new ModelMapper();
		modelMapper.getConfiguration().setFullTypeMatchingRequired(true);
		modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
		return modelMapper.map(entity, TurnstoreOutItemDto.class);
	}

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

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


}
