
package com.sw.mes.store.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sw.mes.core.api.system.YbFeignClients;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.MaterialModelDto;
import com.sw.mes.core.exception.BusinessException;
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.RequestPage;
import com.sw.mes.store.dto.WarehouseMaterialDto;
import com.sw.mes.store.entity.WarehouseMaterial;
import com.sw.mes.store.service.WarehouseMaterialService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
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.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author wupeng
 * @Description 线边仓-物料配置模型
 * @Date 11:10 2023/7/24
 * @Param
 * @return
 **/
@RestController
@RequestMapping("/warehouse/material")
@Slf4j
@Api(tags = "线边仓-物料配置模型")
public class WarehouseMaterialController {

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private WarehouseMaterialService warehouseMaterialService;

    @Autowired
    private YbFeignClients ybFeignClients;


    @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_LIKE_materialCode", value = "物料编码", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_IN_materialTypeId", value = "物料类型", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_materialTypeName", value = "物料类型名称", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_materialTypeCode", value = "物料类型编码", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_defaultLocation", value = "默认仓库位置", dataType = "string", paramType = "query")
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<WarehouseMaterialDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Page<WarehouseMaterial> page = warehouseMaterialService.listByPage(request, requestPage);
        List<WarehouseMaterialDto> dtos = page.getRecords().stream()
                .map(entity -> toLazyDto(entity))
                .filter(e -> e.getId() != null).collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotal());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "线边仓-物料配置模型详细信息")
    @GetMapping("/{id}")
    public Result<WarehouseMaterialDto> get(@PathVariable @ApiParam(value = "存储配置id") Integer id) {
        WarehouseMaterial storeLocation = warehouseMaterialService.getById(id);
        if (null == storeLocation) {
            return ResultGenerator.fail("该对象不存在");
        }
        return ResultGenerator.success(toEagerDto(storeLocation));
    }

    @ApiOperation(value = "创建线边仓-物料配置模型")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "线边仓-物料配置模型对象") WarehouseMaterialDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            warehouseMaterialService.create(dto);
        } catch (Exception e) {
            return ResultGenerator.fail("保存失败，失败原因：" + e.getMessage());
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新线边仓-物料配置模型")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "线边仓-物料配置模型对象") WarehouseMaterialDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        WarehouseMaterial entity = warehouseMaterialService.getById(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            entity.setBatch(dto.getBatch());
            entity.setUniqueCode(dto.getUniqueCode());
            entity.setDefaultLocation(dto.getDefaultLocation());
            entity.setDefaultLocationId(dto.getDefaultLocationId());
            entity.setLowerLimit(dto.getLowerLimit());
            entity.setUpperLimit(dto.getUpperLimit());
            entity.setResidenceTime(dto.getResidenceTime());
            entity.setTimeUnit(dto.getTimeUnit());
            entity.setSafetyStock(dto.getLowerLimit() + "-" + dto.getUpperLimit());
            entity.setUpdateTime(new Date());
            entity.setUpdateUserId(BaseContextHandler.getUserID());
            entity.setUpdateUserName(BaseContextHandler.getUsername());
            warehouseMaterialService.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) {
        if (ids == null || ids.length == 0) {
            return ResultGenerator.fail("id不能为空");
        }
        warehouseMaterialService.removeByIds(Arrays.asList(ids));
        return ResultGenerator.success();
    }

    @ApiOperation(value = "根据物料ID查询物料配置")
    @GetMapping("/getByMaterialId")
    public Result<WarehouseMaterialDto> getByMaterialId(@ApiParam(value = "物料ID", type = "query") @RequestParam Long materialId) {
        if (materialId == null) {
            return ResultGenerator.fail("id不能为空");
        }
        WarehouseMaterial byMaterialId = warehouseMaterialService.getByMaterialId(materialId);
        return ResultGenerator.success(toLazyDto(byMaterialId));
    }
    @ApiOperation(value = "根据物料Code查询物料配置")
    @GetMapping("/getByMaterialCode")
    public Result<WarehouseMaterialDto> getByMaterialCode(@ApiParam(value = "物料编码", type = "query") @RequestParam String materialCode) {
        if (materialCode == null) {
            return ResultGenerator.fail("编码不能为空");
        }
        WarehouseMaterial byMaterialId = warehouseMaterialService.getByMaterialCode(materialCode);
        return ResultGenerator.success(toLazyDto(byMaterialId));
    }
    @ApiOperation(value = "根据物料ID集合查询物料配置")
    @GetMapping("/getByMaterialIds")
    public Result<List<WarehouseMaterialDto>> getByMaterialIds(@ApiParam(value = "物料ID", type = "query") @RequestParam List<Long> materialIds) {
        try {
            List<WarehouseMaterial> warehouseMaterials = warehouseMaterialService.getByMaterialIds(materialIds);
            List<WarehouseMaterialDto> dtos = warehouseMaterials.stream().map(e -> toLazyDto(e)).filter(e -> e.getId() != null).collect(Collectors.toList());
            return ResultGenerator.success(dtos);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }


    public WarehouseMaterialDto toLazyDto(WarehouseMaterial entity) {
        WarehouseMaterialDto materialDto = modelMapper.map(entity, WarehouseMaterialDto.class);
        //TODO wupeng 此处调用查询物料主数据的接口
        String materialCode = entity.getMaterialCode();
        Result<MaterialModelDto> result = ybFeignClients.getMaterialByCode(materialCode);
        MaterialModelDto materialModel = result.getData();
        if (materialModel == null) {
            throw new BusinessException("【"+materialCode+"】物料主数据不存在，请检查数据！");
        }
        List<MaterialModelDto> materials = new ArrayList<>();
        materials.add(materialModel);
        materialDto.setMaterials(materials);
        return materialDto;
    }

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

    public WarehouseMaterial fromDto(WarehouseMaterialDto dto) {
        return modelMapper.map(dto, WarehouseMaterial.class);
    }

}







