package com.sw.mes.itemclean.clean.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.DynmaicQueryWrapper;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.itemclean.clean.dto.MaterialScrapDto;
import com.sw.mes.itemclean.clean.domain.MaterialScrap;
import com.sw.mes.itemclean.clean.mapper.MaterialScrapMapper;
import com.sw.mes.itemclean.clean.service.MaterialScrapService;
import io.swagger.annotations.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/clean/materialScrap")
@Slf4j
@Api(tags = "废料入库")
public class MaterialScrapController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private MaterialScrapService materialScrapService;

    @Autowired
    private MaterialScrapMapper materialScrapMapper;

    @ApiOperation(value = "废料分页查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_materialName", value = "物料名称", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_materialCode", value = "物料编码", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_createTime", value = "组托开始时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LTE_createTime", value = "组托结束时间", dataType = "string", paramType = "query"),

    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<MaterialScrapDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        //分页查询
        QueryWrapper<MaterialScrap> queryWrapper =  DynmaicQueryWrapper.searchFilter(request, MaterialScrap.class);
        Page<MaterialScrap> listPage = materialScrapService.page(new Page<>(requestPage.getPage(), requestPage.getRows()), queryWrapper);
        List<MaterialScrapDto> dtos = listPage.getRecords().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, listPage.getTotal());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有列表")
    @GetMapping("/listAll")
    public Result<List<MaterialScrapDto>> listAll(ServletRequest request) {
        QueryWrapper<MaterialScrap> queryWrapper =  DynmaicQueryWrapper.searchFilter(request, MaterialScrap.class);
        List<MaterialScrap> materialScraps = materialScrapService.list(queryWrapper);
        List<MaterialScrapDto> materialScrapDtos = materialScraps.stream()
                .map(materialScrap -> toLazyDto(materialScrap))
                .collect(Collectors.toList());
        return ResultGenerator.success(materialScrapDtos);
    }

    @ApiOperation(value = "详细信息")
    @GetMapping("/{id}")
    public Result<MaterialScrapDto> get(@PathVariable @ApiParam(value="设备类型id") Integer id) {
        MaterialScrap materialScrap = materialScrapService.getById(id);
        if (null == materialScrap)
            return ResultGenerator.fail("该对象不存在");
        return ResultGenerator.success(toEagerDto(materialScrap));
    }

    @ApiOperation(value = "创建")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "Dto对象") MaterialScrapDto materialScrapDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        MaterialScrap materialScrap = fromDto(materialScrapDto);
        materialScrap.setCreateUser(BaseContextHandler.getUsername());
        materialScrap.setUpdateUser(BaseContextHandler.getUsername());
        materialScrap.setCreateTime(LocalDateTime.now());
        materialScrap.setUpdateTime(LocalDateTime.now());
        materialScrapService.saveOrUpdate(materialScrap);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "Dto对象") MaterialScrapDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        MaterialScrap entity = materialScrapService.getById(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            MaterialScrap entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            materialScrapService.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) {
            materialScrapMapper.deleteById(id);
        }
        return ResultGenerator.success();
    }

    public MaterialScrapDto toLazyDto(MaterialScrap entity) {
        return modelMapper.map(entity, MaterialScrapDto.class);
    }

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

    public MaterialScrap fromDto(MaterialScrapDto dto) {
        return modelMapper.map(dto, MaterialScrap.class);
    }
}
