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.FormulaMaterialClassDto;
import com.sw.mes.production.entity.FormulaMaterialClass;
import com.sw.mes.production.service.FormulaMaterialClassService;
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.util.Assert;
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.Date;
import java.util.List;
import java.util.stream.Collectors;


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

    @Autowired
    private FormulaMaterialClassService formulaMaterialClassService;

    @ApiOperation(value = "分页查询配方物料分类列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<FormulaMaterialClassDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<FormulaMaterialClass> specification = DynamicSpecifications.bySearchFilter(request, FormulaMaterialClass.class);
        Page<FormulaMaterialClass> page = formulaMaterialClassService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<FormulaMaterialClassDto> dtos = page.getContent().stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        ResponsePage<FormulaMaterialClassDto> responsePage = new ResponsePage<>(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有配方物料分类")
    @GetMapping("/listAll")
    public Result<List<FormulaMaterialClassDto>> listAll(ServletRequest request) {
        Specification<FormulaMaterialClass> specification = DynamicSpecifications.bySearchFilter(request, FormulaMaterialClass.class);
        List<FormulaMaterialClass> formulaMaterialClasss = formulaMaterialClassService.findByExampleSort(specification, null);
        List<FormulaMaterialClassDto> formulaMaterialClassDtos = formulaMaterialClasss.stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        return ResultGenerator.success(formulaMaterialClassDtos);
    }

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

    @ApiOperation(value = "创建配方物料分类")
    @PostMapping("/create")
    public Result<Long> create(@RequestBody @Valid @ApiParam(value = "配方物料分类对象") FormulaMaterialClassDto formulaMaterialClassDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        FormulaMaterialClass formulaMaterialClassOld = formulaMaterialClassService.findByName(formulaMaterialClassDto.getName());
        Assert.isNull(formulaMaterialClassOld, "配方物料分类名称已存在");
        FormulaMaterialClass formulaMaterialClass = fromDto(formulaMaterialClassDto);
        formulaMaterialClass.setGmtCreate(new Date());
        formulaMaterialClass.setUserCreate(BaseContextHandler.getUsername());
        formulaMaterialClassService.saveOrUpdate(formulaMaterialClass);
        return ResultGenerator.success(formulaMaterialClass.getId());
    }

    @ApiOperation(value = "更新配方物料分类")
    @PostMapping("/update")
    public Result<String> update(@RequestBody @Valid @ApiParam(value = "配方物料分类") FormulaMaterialClassDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        FormulaMaterialClass entity = formulaMaterialClassService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            FormulaMaterialClass formulaMaterialClassOld = formulaMaterialClassService.findByName(dto.getName());
            Assert.isTrue(formulaMaterialClassOld == null || formulaMaterialClassOld.getId().equals(entity.getId()), "配方物料分类名称已存在");
            FormulaMaterialClass entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            entity.setGmtUpdate(new Date());
            entity.setUserUpdate(BaseContextHandler.getUsername());
            formulaMaterialClassService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "删除配方物料分类")
    @PostMapping("/delete")
    public Result<String> remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        for (Long id : ids) {
            formulaMaterialClassService.delete(id);
        }
        return ResultGenerator.success();
    }

    public FormulaMaterialClassDto toLazyDto(FormulaMaterialClass entity) {
        return modelMapper.map(entity, FormulaMaterialClassDto.class);
    }

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

    public FormulaMaterialClass fromDto(FormulaMaterialClassDto dto) {
        return modelMapper.map(dto, FormulaMaterialClass.class);
    }


}
