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.FormulaWeightSchemeDto;
import com.sw.mes.production.entity.FormulaWeightScheme;
import com.sw.mes.production.service.FormulaWeightSchemeService;
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("/formulaWeightScheme")
@Slf4j
@Api(tags = "配方重量方案接口")
public class FormulaWeightSchemeController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private FormulaWeightSchemeService formulaWeightSchemeService;

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

    @ApiOperation(value = "配方重量方案详细信息")
    @GetMapping("/{id}")
    public Result<FormulaWeightSchemeDto> get(@PathVariable @ApiParam(value = "配方重量方案id") Long id) {
        FormulaWeightScheme formulaWeightScheme = formulaWeightSchemeService.get(id);
        if (null == formulaWeightScheme)
            return ResultGenerator.fail("该配方重量方案不存在");
        return ResultGenerator.success(toEagerDto(formulaWeightScheme));
    }

    @ApiOperation(value = "创建配方重量方案")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "配方重量方案对象") FormulaWeightSchemeDto formulaWeightSchemeDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        FormulaWeightScheme formulaWeightSchemeOld = formulaWeightSchemeService.findByName(formulaWeightSchemeDto.getName());
        Assert.isNull(formulaWeightSchemeOld, "配方重量方案名称已存在");
        formulaWeightSchemeDto.setGmtCreate(new Date());
        formulaWeightSchemeDto.setUserCreate(BaseContextHandler.getUsername());
        FormulaWeightScheme formulaWeightScheme = fromDto(formulaWeightSchemeDto);
        formulaWeightSchemeService.saveOrUpdate(formulaWeightScheme);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新配方重量方案")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "配方重量方案") FormulaWeightSchemeDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        FormulaWeightScheme entity = formulaWeightSchemeService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        FormulaWeightScheme formulaWeightSchemeOld = formulaWeightSchemeService.findByName(dto.getName());
        Assert.isTrue(formulaWeightSchemeOld == null || formulaWeightSchemeOld.getId().equals(entity.getId()), "配方物料分类名称已存在");
        try {
            FormulaWeightScheme entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            entity.setGmtUpdate(new Date());
            entity.setUserUpdate(BaseContextHandler.getUsername());
            formulaWeightSchemeService.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) {
            formulaWeightSchemeService.delete(id);
        }
        return ResultGenerator.success();
    }

    public FormulaWeightSchemeDto toLazyDto(FormulaWeightScheme entity) {
        return modelMapper.map(entity, FormulaWeightSchemeDto.class);
    }

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

    public FormulaWeightScheme fromDto(FormulaWeightSchemeDto dto) {
        return modelMapper.map(dto, FormulaWeightScheme.class);
    }


}
