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.DynamicSpecifications;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.fb.instoreapply.dto.InstoreApplyDto;
import com.sw.mes.fb.instoreapply.dto.InstoreApplyItemDto;
import com.sw.mes.fb.instoreapply.dto.InstoreApplyPostDto;
import com.sw.mes.fb.instoreapply.entity.InstoreApply;
import com.sw.mes.fb.instoreapply.entity.InstoreApplyItem;
import com.sw.mes.fb.instoreapply.service.InstoreApplyItemService;
import com.sw.mes.fb.instoreapply.service.InstoreApplyService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
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("/instoreApply")
@Slf4j
@Api(description = "入库申请主表接口")
public class InstoreApplyController {
	@Autowired
    ModelMapper modelMapper;

	@Autowired
	private InstoreApplyService instoreApplyService;

	@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<InstoreApplyDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
		Specification<InstoreApply> specification = DynamicSpecifications.bySearchFilter(request, InstoreApply.class);
    	Page<InstoreApply> page = instoreApplyService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<InstoreApplyDto> 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<InstoreApplyDto>> listAll(ServletRequest request) {
		Specification<InstoreApply> specification = DynamicSpecifications.bySearchFilter(request, InstoreApply.class);
		List<InstoreApply> instoreApplys = instoreApplyService.findByExampleSort(specification, null);
		List<InstoreApplyDto> instoreApplyDtos = instoreApplys.stream()
					.map(instoreApply -> toLazyDto(instoreApply))
					.collect(Collectors.toList());
		return ResultGenerator.success(instoreApplyDtos);
	}

	@ApiOperation(value = "入库申请主表详细信息")
	@GetMapping("/{id}")
	public Result<InstoreApplyPostDto> get(@PathVariable @ApiParam(value="入库申请主表id") Integer id) {
		InstoreApply instoreApply = instoreApplyService.get(id);
		if (null == instoreApply){
			return ResultGenerator.fail("此记录不存在");
		}
		InstoreApplyPostDto entity = fromDto(instoreApply);
		List<InstoreApplyItem> items = instoreApplyItemService.getItemsByApplyId(id);
		entity.setItems(toDto(items));
		return ResultGenerator.success(entity);
	}






	@ApiOperation(value = "创建入库申请主表")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "入库申请主表对象") InstoreApplyPostDto instoreApplyPostDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		if(instoreApplyPostDto==null){
			return ResultGenerator.fail("入库申请错误");
		}
		if(instoreApplyPostDto.getItems()==null||instoreApplyPostDto.getItems().size()==0){
			return ResultGenerator.fail("入库申请明细错误");
		}
		InstoreApply instoreApply = fromDto(instoreApplyPostDto);
		List<InstoreApplyItem> items = fromDto(instoreApplyPostDto.getItems());
		instoreApplyService.createIn(instoreApply,items);
		return ResultGenerator.success(instoreApply.getOrderNo());
	}

    @ApiOperation(value = "更新入库申请主表")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "入库申请主表") InstoreApplyPostDto instoreApplyPostDto, BindingResult bindingResult) {
		if(instoreApplyPostDto==null){
			return ResultGenerator.fail("入库申请错误");
		}
		if(instoreApplyPostDto.getItems()==null||instoreApplyPostDto.getItems().size()==0){
			return ResultGenerator.fail("入库申请明细错误");
		}
		InstoreApply entity =  instoreApplyService.get(instoreApplyPostDto.getId());
		if (entity == null){
			return ResultGenerator.fail("原信息不存在");
		}
		if(entity.getIsConfirm()!=null&&entity.getIsConfirm()==1){
			return ResultGenerator.fail("该批次已经确认，不可修改，请重新刷新页面！");
		}
        try {
			InstoreApply instoreApply = fromDto(instoreApplyPostDto);
			List<InstoreApplyItem> items = fromDto(instoreApplyPostDto.getItems());
			instoreApplyService.updateIn(instoreApply,items);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

	//打印入库单 标记为已打印
	@ApiOperation(value = "打印入库单 标记为已打印")
	@PostMapping("/print")
	public Result print(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Integer[] ids) {
		for (Integer id : ids) {
			instoreApplyService.print(id);
			//turnstoreInService.confirmIn(id, user);
		}
		return ResultGenerator.success();
	}



	@ApiOperation(value = "删除入库申请主表")
	@PostMapping("/delete")
	public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Integer[] ids) {
		for (Integer id : ids) {
				instoreApplyService.deleteIn(id);
		}
		return ResultGenerator.success();
	}

	public InstoreApplyDto toLazyDto(InstoreApply entity) {
		return modelMapper.map(entity, InstoreApplyDto.class);
	}

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

	public InstoreApply fromDto(InstoreApplyDto dto) {
		return modelMapper.map(dto, InstoreApply.class);
	}

	public InstoreApply fromDto(InstoreApplyPostDto dto) {
		return modelMapper.map(dto, InstoreApply.class);
	}

	public InstoreApplyPostDto fromDto(InstoreApply dto) {
		return modelMapper.map(dto, InstoreApplyPostDto.class);
	}

	public List<InstoreApplyItem> fromDto(List<InstoreApplyItemDto> dto){
		List<InstoreApplyItem> listEntity = dto.stream().map(instoreApplyItem -> modelMapper.map(instoreApplyItem, InstoreApplyItem.class)).collect(Collectors.toList());
		return listEntity;
	}


	public List<InstoreApplyItemDto> toDto(List<InstoreApplyItem> dto){
		List<InstoreApplyItemDto> listEntity = dto.stream().map(instoreApplyItemDto -> modelMapper.map(instoreApplyItemDto, InstoreApplyItemDto.class)).collect(Collectors.toList());
		return listEntity;
	}

}
