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.MaterialPreparationRulesDto;
import com.sw.mes.production.entity.MaterialPreparationRules;
import com.sw.mes.production.service.MaterialPreparationRulesService;
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("/materialPreparationRules")
@Slf4j
@Api(tags = "前置备料规则接口")
public class MaterialPreparationRulesController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private MaterialPreparationRulesService materialPreparationRulesService;

    @ApiOperation(value = "分页查询前置备料规则列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "Long", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<MaterialPreparationRulesDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<MaterialPreparationRules> specification = DynamicSpecifications.bySearchFilter(request, MaterialPreparationRules.class);
        Page<MaterialPreparationRules> page = materialPreparationRulesService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<MaterialPreparationRulesDto> 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<MaterialPreparationRulesDto>> listAll(ServletRequest request) {
        Specification<MaterialPreparationRules> specification = DynamicSpecifications.bySearchFilter(request, MaterialPreparationRules.class);
        List<MaterialPreparationRules> materialPreparationRuless = materialPreparationRulesService.findByExampleSort(specification, null);
        List<MaterialPreparationRulesDto> materialPreparationRulesDtos = materialPreparationRuless.stream()
                .map(materialPreparationRules -> toLazyDto(materialPreparationRules))
                .collect(Collectors.toList());
        return ResultGenerator.success(materialPreparationRulesDtos);
    }

    @ApiOperation(value = "前置备料规则详细信息")
    @GetMapping("/{id}")
    public Result<MaterialPreparationRulesDto> get(@PathVariable @ApiParam(value = "前置备料规则id") Long id) {
        MaterialPreparationRules materialPreparationRules = materialPreparationRulesService.get(id);
        if (null == materialPreparationRules)
            return ResultGenerator.fail("该前置备料规则不存在");
        return ResultGenerator.success(toEagerDto(materialPreparationRules));
    }

    @ApiOperation(value = "创建前置备料规则")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "前置备料规则对象") MaterialPreparationRulesDto materialPreparationRulesDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        MaterialPreparationRules materialPreparationRules = fromDto(materialPreparationRulesDto);
        materialPreparationRules.setGmtCreate(new Date());
        materialPreparationRules.setUserCreate(BaseContextHandler.getUsername());
        materialPreparationRulesService.saveOrUpdate(materialPreparationRules);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "创建前置备料规则-批量")
    @PostMapping("/creates")
    public Result creates(@RequestBody @Valid @ApiParam(value = "前置备料规则对象") List<MaterialPreparationRulesDto> materialPreparationRulesDtos, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        List<MaterialPreparationRules> materialPreparationRuless = new ArrayList<>();
        materialPreparationRulesDtos.forEach(materialPreparationRulesDto -> {
            MaterialPreparationRules materialPreparationRules = fromDto(materialPreparationRulesDto);
            MaterialPreparationRules entity = materialPreparationRulesService.findByEquipmentCode(materialPreparationRules.getEquipmentCode());
            if (entity != null) {
                materialPreparationRules.setGmtUpdate(new Date());
                materialPreparationRules.setUserUpdate(BaseContextHandler.getUsername());
                BeanUtils.copyProperties(materialPreparationRules, entity, BeanUtil.getIgnoreProperties(materialPreparationRules, null, null));
                materialPreparationRuless.add(entity);
            } else {
                materialPreparationRules.setGmtCreate(new Date());
                materialPreparationRules.setUserCreate(BaseContextHandler.getUsername());
                materialPreparationRuless.add(materialPreparationRules);
            }
            materialPreparationRuless.add(materialPreparationRules);
        });
        materialPreparationRulesService.saveAll(materialPreparationRuless);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新前置备料规则")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "前置备料规则") MaterialPreparationRulesDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        MaterialPreparationRules entity = materialPreparationRulesService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            MaterialPreparationRules entityfromFto = fromDto(dto);
            entityfromFto.setGmtUpdate(new Date());
            entityfromFto.setUserUpdate(BaseContextHandler.getUsername());
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            materialPreparationRulesService.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) {
            materialPreparationRulesService.delete(id);
        }
        return ResultGenerator.success();
    }

    public MaterialPreparationRulesDto toLazyDto(MaterialPreparationRules entity) {
        return modelMapper.map(entity, MaterialPreparationRulesDto.class);
    }

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

    public MaterialPreparationRules fromDto(MaterialPreparationRulesDto dto) {
        return modelMapper.map(dto, MaterialPreparationRules.class);
    }


}
