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.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.domain.MaterialReworking;
import com.sw.mes.itemclean.clean.domain.MaterialStoreSignBox;
import com.sw.mes.itemclean.clean.domain.MaterialUnpacking;
import com.sw.mes.itemclean.clean.dto.BoxPropertyDto;
import com.sw.mes.itemclean.clean.dto.GeneralScanBoxNoParam;
import com.sw.mes.itemclean.clean.dto.MaterialReworkSignatureDto;
import com.sw.mes.itemclean.clean.domain.MaterialReworkSignature;
import com.sw.mes.itemclean.clean.dto.MaterialReworkingDto;
import com.sw.mes.itemclean.clean.dto.MaterialUnpackingDto;
import com.sw.mes.itemclean.clean.mapper.MaterialReworkSignatureMapper;
import com.sw.mes.itemclean.clean.service.MaterialReworkSignatureService;
import com.sw.mes.itemclean.clean.service.MaterialReworkingService;
import com.sw.mes.itemclean.clean.service.MaterialStoreSignBoxService;
import com.sw.mes.itemclean.clean.vo.MaterialReworkingVo;
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.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/clean/materialReworkSignature")
@Slf4j
@Api(tags = "返工打签")
public class MaterialReworkSignatureController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private MaterialReworkSignatureService materialReworkSignatureService;

    @Autowired
    private MaterialReworkSignatureMapper materialReworkSignatureMapper;

    @Autowired
    private MaterialReworkingService materialReworkingService;

    @Autowired
    private MaterialStoreSignBoxService materialStoreSignBoxService;

    @ApiOperation(value = "分页查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<MaterialReworkSignatureDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        //分页查询
        QueryWrapper<MaterialReworkSignature> queryWrapper =  DynmaicQueryWrapper.searchFilter(request, MaterialReworkSignature.class);
        Page<MaterialReworkSignature> listPage = materialReworkSignatureService.page(new Page<>(requestPage.getPage(), requestPage.getRows()), queryWrapper);
        List<MaterialReworkSignatureDto> 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<MaterialReworkSignatureDto>> listAll(ServletRequest request) {
        QueryWrapper<MaterialReworkSignature> queryWrapper =  DynmaicQueryWrapper.searchFilter(request, MaterialReworkSignature.class);
        List<MaterialReworkSignature> materialReworkSignatures = materialReworkSignatureService.list(queryWrapper);
        List<MaterialReworkSignatureDto> materialReworkSignatureDtos = materialReworkSignatures.stream()
                .map(materialReworkSignature -> toLazyDto(materialReworkSignature))
                .collect(Collectors.toList());
        return ResultGenerator.success(materialReworkSignatureDtos);
    }

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

    /**
     * 返工暂存打签
     * @param materialReworkingVo
     * @param bindingResult
     * @return
     */
    @ApiOperation(value = "返工暂存打签")
    @PostMapping("/createReworkingStorageSign")
    public Result createStorageSign(@RequestBody @Valid @ApiParam(value = "返工暂存打签vo对象") MaterialReworkingVo materialReworkingVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        return ResultGenerator.success(materialReworkSignatureService.createStorageSign(materialReworkingVo));
    }


    @ApiOperation(value = "获取返工暂存打签的详细信息")
    @GetMapping("/selectReworkingStorageSign")
    public Result<MaterialReworkingVo> selectReworkingStorageSign(@ApiParam(value = "成箱箱号") String materialBoxNo) {
        return ResultGenerator.success( materialReworkingService.selectReworkingStorageSign(materialBoxNo));
    }


    @ApiOperation(value = "获取所有暂存打签列表（主表）")
    @GetMapping("/listAllReworkStorage")
    public Result<List<MaterialReworkingDto>> listAllReworkStorage(ServletRequest request) {
        QueryWrapper<MaterialReworking> queryWrapper =  DynmaicQueryWrapper.searchFilter(request, MaterialReworking.class);
        queryWrapper.ne("staging_flag",0);
        List<MaterialReworking> materialReworkings = materialReworkingService.list(queryWrapper);
        List<MaterialReworkingDto> materialReworkingDtos = materialReworkings.stream()
                .map(materialReworking -> toLazyDto2(materialReworking))
                .collect(Collectors.toList());
        return ResultGenerator.success(materialReworkingDtos);
    }


    @ApiOperation(value = "分页查询返工暂存列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPageForReworkStorage")
    public Result<ResponsePage<MaterialUnpackingDto>> listByPageForReworkStorage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        //分页查询
        QueryWrapper<MaterialReworking> queryWrapper =  DynmaicQueryWrapper.searchFilter(request, MaterialReworking.class);
        queryWrapper.ne("staging_flag",0);
        Page<MaterialReworking> listPage = materialReworkingService.page(new Page<>(requestPage.getPage(), requestPage.getRows()), queryWrapper);
        List<MaterialReworkingDto> dtos = listPage.getRecords().stream()
                .map(entity -> toLazyDto2(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, listPage.getTotal());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "创建")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "Dto对象") MaterialReworkSignatureDto materialReworkSignatureDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        MaterialReworkSignature materialReworkSignature = fromDto(materialReworkSignatureDto);
        materialReworkSignatureService.saveOrUpdate(materialReworkSignature);
        return ResultGenerator.success();
    }

    /**
     * 返工料打签扫描箱号
     * @param generalScanBoxNoParam
     * @param bindingResult
     * @return
     */
    @ApiOperation(value = "返工料打签扫描箱号")
    @PostMapping("/generalScanFgBoxNo")
    public Result<BoxPropertyDto> generalScanFxBoxNo(@RequestBody @Valid @ApiParam(value = "打签箱待存（待扫码领料）对象") GeneralScanBoxNoParam generalScanBoxNoParam, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        return ResultGenerator.success(materialStoreSignBoxService.generalScanBoxNo(generalScanBoxNoParam));
    }

    /**
     * 返工料成箱打签
     * @param materialReworkingVo
     * @param bindingResult
     * @return
     */
    @ApiOperation(value = "返工料成箱打签")
    @PostMapping("/reworkSignature")
    public Result reworkSignature(@RequestBody @Valid @ApiParam(value = "返工成箱打签vo对象") MaterialReworkingVo materialReworkingVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        return materialReworkSignatureService.reworkSignature2(materialReworkingVo);
    }


    @ApiOperation(value = "返工料成箱打签（接口已弃用）")
    @PostMapping("/reworkSignature2")
    @Deprecated
    public Result reworkSignature2(@RequestBody @Valid @ApiParam(value = "Dto对象") MaterialReworkSignatureDto materialReworkSignatureDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        return materialReworkSignatureService.reworkSignature(materialReworkSignatureDto);
    }



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

    public MaterialReworkSignatureDto toLazyDto(MaterialReworkSignature entity) {
        return modelMapper.map(entity, MaterialReworkSignatureDto.class);
    }

    public MaterialReworkingDto toLazyDto2(MaterialReworking entity) {
        return modelMapper.map(entity, MaterialReworkingDto.class);
    }

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

    public MaterialReworkSignature fromDto(MaterialReworkSignatureDto dto) {
        return modelMapper.map(dto, MaterialReworkSignature.class);
    }

    public GeneralScanBoxNoParam toGeneralScanBoxNoParam (MaterialStoreSignBox materialStoreSignBox){
        GeneralScanBoxNoParam generalScanBoxNoParam = new GeneralScanBoxNoParam();
        generalScanBoxNoParam.setBoxNo(materialStoreSignBox.getMaterialBoxNo());
        generalScanBoxNoParam.setScanName("");
        return generalScanBoxNoParam;
    }
}
