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 com.sw.mes.production.dto.FormulaMaterialClassDetailDto;
import com.sw.mes.production.entity.FormulaMaterialClassDetail;
import com.sw.mes.production.service.FormulaMaterialClassDetailService;
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.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/formulaMaterialClassDetail")
@Slf4j
@Api(tags = "配方物料分类明细接口")
public class FormulaMaterialClassDetailController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private FormulaMaterialClassDetailService formulaMaterialClassDetailService;

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

    @ApiOperation(value = "配方物料分类明细详细信息")
    @GetMapping("/{id}")
    public Result<FormulaMaterialClassDetailDto> get(@PathVariable @ApiParam(value = "配方物料分类明细id") Long id) {
        FormulaMaterialClassDetail formulaMaterialClassDetail = formulaMaterialClassDetailService.get(id);
        if (null == formulaMaterialClassDetail)
            return ResultGenerator.fail("该配方物料分类明细不存在");
        return ResultGenerator.success(toEagerDto(formulaMaterialClassDetail));
    }

    @ApiOperation(value = "创建配方物料分类明细")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "配方物料分类明细对象") FormulaMaterialClassDetailDto formulaMaterialClassDetailDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        formulaMaterialClassDetailDto.setGmtCreate(new Date());
        formulaMaterialClassDetailDto.setUserCreate(BaseContextHandler.getUsername());
        FormulaMaterialClassDetail formulaMaterialClassDetail = fromDto(formulaMaterialClassDetailDto);
        formulaMaterialClassDetailService.saveOrUpdate(formulaMaterialClassDetail);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "批量创建配方物料分类明细")
    @PostMapping("/creates")
    public Result creates(@RequestBody @Valid @ApiParam(value = "配方物料分类明细对象") List<FormulaMaterialClassDetailDto> formulaMaterialClassDetailDtos, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        List<FormulaMaterialClassDetail> formulaMaterialClassDetails = new ArrayList<>();
        for (FormulaMaterialClassDetailDto formulaMaterialClassDetailDto : formulaMaterialClassDetailDtos) {
            formulaMaterialClassDetailDto.setGmtCreate(new Date());
            formulaMaterialClassDetailDto.setUserCreate(BaseContextHandler.getUsername());
            formulaMaterialClassDetails.add(fromDto(formulaMaterialClassDetailDto));
        }
        formulaMaterialClassDetailService.saveAll(formulaMaterialClassDetails);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新配方物料分类明细")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "配方物料分类明细") FormulaMaterialClassDetailDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        FormulaMaterialClassDetail entity = formulaMaterialClassDetailService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            FormulaMaterialClassDetail entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            entity.setGmtUpdate(new Date());
            entity.setUserUpdate(BaseContextHandler.getUsername());
            formulaMaterialClassDetailService.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 Long[] ids) {
        for (Long id : ids) {
            formulaMaterialClassDetailService.delete(id);
        }
        return ResultGenerator.success();
    }

    public FormulaMaterialClassDetailDto toLazyDto(FormulaMaterialClassDetail entity) {
        return modelMapper.map(entity, FormulaMaterialClassDetailDto.class);
    }

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

    public FormulaMaterialClassDetail fromDto(FormulaMaterialClassDetailDto dto) {
        return modelMapper.map(dto, FormulaMaterialClassDetail.class);
    }


}
