package com.sw.mes.production.controller;

import com.sw.mes.core.context.BaseContextHandler;
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 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.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import com.sw.mes.production.entity.FormulaSchemeDetail;
import com.sw.mes.production.dto.FormulaSchemeDetailDto;
import com.sw.mes.production.service.FormulaSchemeDetailService;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/formulaSchemeDetail")
@Slf4j
@Api(description = "配方方案明细接口")
public class FormulaSchemeDetailController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private FormulaSchemeDetailService formulaSchemeDetailService;

	@ApiOperation(value = "分页查询配方方案明细列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<FormulaSchemeDetailDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		Specification<FormulaSchemeDetail> specification = DynamicSpecifications.bySearchFilter(request, FormulaSchemeDetail.class);
    	Page<FormulaSchemeDetail> page = formulaSchemeDetailService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<FormulaSchemeDetailDto> 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<FormulaSchemeDetailDto>> listAll(ServletRequest request) {
		Specification<FormulaSchemeDetail> specification = DynamicSpecifications.bySearchFilter(request, FormulaSchemeDetail.class);
		List<FormulaSchemeDetail> formulaSchemeDetails = formulaSchemeDetailService.findByExampleSort(specification, null);
		List<FormulaSchemeDetailDto> formulaSchemeDetailDtos = formulaSchemeDetails.stream()
					.map(formulaSchemeDetail -> toLazyDto(formulaSchemeDetail))
					.collect(Collectors.toList());
		return ResultGenerator.success(formulaSchemeDetailDtos);
	}

	@ApiOperation(value = "配方方案明细详细信息")
	@GetMapping("/{id}")
	public Result<FormulaSchemeDetailDto> get(@PathVariable @ApiParam(value="配方方案明细id") Long id) {
		FormulaSchemeDetail formulaSchemeDetail = formulaSchemeDetailService.get(id);
		if (null == formulaSchemeDetail)
			return ResultGenerator.fail("该配方方案明细不存在");
		return ResultGenerator.success(toEagerDto(formulaSchemeDetail));
	}

	@ApiOperation(value = "创建配方方案明细")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "配方方案明细对象") FormulaSchemeDetailDto formulaSchemeDetailDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		FormulaSchemeDetail formulaSchemeDetail = fromDto(formulaSchemeDetailDto);
		formulaSchemeDetailService.saveOrUpdate(formulaSchemeDetail);
		return ResultGenerator.success();
	}

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

	public FormulaSchemeDetailDto toLazyDto(FormulaSchemeDetail entity) {
		return modelMapper.map(entity, FormulaSchemeDetailDto.class);
	}

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

	public FormulaSchemeDetail fromDto(FormulaSchemeDetailDto dto) {
		return modelMapper.map(dto, FormulaSchemeDetail.class);
	}


}
