package com.sw.mes.yb.accessory.controller;

import com.sw.mes.base.factory.material.entity.MaterialModel;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.core.annotation.Jinko;
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.yb.accessory.dto.AccessoryMaterialDto;
import com.sw.mes.yb.accessory.entity.AccessoryMaterial;
import com.sw.mes.yb.accessory.service.AccessoryMaterialService;
import com.sw.mes.yb.accessory.service.EquipmentAccessoryService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 辅料接口
 *
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/accessoryMaterial")
@Slf4j
@Api(description = "热场模型接口")
public class AccessoryMaterialController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private AccessoryMaterialService accessoryMaterialService;

    @Autowired
    private EquipmentAccessoryService equipmentAccessoryService;

    @Autowired
    private MaterialModelService materialModelService;

    @ApiOperation(value = "分页查询热场模型列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<AccessoryMaterialDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<AccessoryMaterial> specification = DynamicSpecifications.bySearchFilter(request, AccessoryMaterial.class);
        Page<AccessoryMaterial> page = accessoryMaterialService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<AccessoryMaterialDto> 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<AccessoryMaterialDto>> listAll(ServletRequest request) {
        Specification<AccessoryMaterial> specification = DynamicSpecifications.bySearchFilter(request, AccessoryMaterial.class);
        List<AccessoryMaterial> accessoryMaterials = accessoryMaterialService.findByExampleSort(specification, null);
        List<AccessoryMaterialDto> accessoryMaterialDtos = accessoryMaterials.stream()
                .map(accessoryMaterial -> toLazyDto(accessoryMaterial))
                .collect(Collectors.toList());
        return ResultGenerator.success(accessoryMaterialDtos);
    }

    @ApiOperation(value = "热场模型详细信息")
    @GetMapping("/{id}")
    public Result<AccessoryMaterialDto> get(@PathVariable @ApiParam(value = "热场模型id") Long id) {
        AccessoryMaterial accessoryMaterial = accessoryMaterialService.get(id);
        if (null == accessoryMaterial) {
            return ResultGenerator.fail("该热场模型不存在");
        }
        return ResultGenerator.success(toEagerDto(accessoryMaterial));
    }

    @ApiOperation(value = "创建热场模型")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "热场模型对象") AccessoryMaterialDto accessoryMaterialDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        MaterialModel materialModel = materialModelService.get(accessoryMaterialDto.getMaterialModelId());
        if (null != materialModel) {
            Integer status = materialModel.getStatus();
            if (status==1){
                return ResultGenerator.fail("物料主数据状态关闭时不能创建!!!");
            }
        }
        AccessoryMaterial accessoryMaterial = fromDto(accessoryMaterialDto);
        accessoryMaterial.setCreateUserId(BaseContextHandler.getUserID());
        accessoryMaterial.setCreateUser(BaseContextHandler.getUsername());
        accessoryMaterial.setCreateDate(new Date());
        accessoryMaterialService.saveOrUpdate(accessoryMaterial);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新热场模型")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "热场模型") AccessoryMaterialDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        AccessoryMaterial entity = accessoryMaterialService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            Double useLife = entity.getUseLife();
            AccessoryMaterial entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            accessoryMaterialService.saveOrUpdate(entity);
            if (useLife != null && !useLife.equals(dto.getUseLife())) {
                equipmentAccessoryService.updateUseLife(entity.getId(), dto.getUseLife());
            }
            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) {
            accessoryMaterialService.delete(id);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "根据热场编码从物料主数据获取辅料属性数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "codes", value = "热场编码", paramType = "path", dataType = "String"),
    })
    @GetMapping("/getByCodes")
    public Result<AccessoryMaterialDto> getByCodes(@RequestParam String codes) {
        if (StringUtils.isBlank(codes)) {
            return ResultGenerator.fail("输入的热场编码为空！");
        }

        List<MaterialModel> materialModelByCode = materialModelService.findMaterialModelByCode(codes);
        if (null == materialModelByCode || materialModelByCode.size() == 0) {
            return ResultGenerator.fail("SAP不存在该物料主数据!");
        }
        AccessoryMaterialDto accessoryMaterialDto = new AccessoryMaterialDto();
        accessoryMaterialDto.setCodes(codes);
        accessoryMaterialDto.setName(materialModelByCode.get(0).getName());
        accessoryMaterialDto.setModelId(materialModelByCode.get(0).getMaterialType().getId());
        accessoryMaterialDto.setModelName(materialModelByCode.get(0).getMaterialType().getName());
        accessoryMaterialDto.setUnitId(materialModelByCode.get(0).getUnit().getId());
        accessoryMaterialDto.setUnitName(materialModelByCode.get(0).getUnit().getName());
        return ResultGenerator.success(accessoryMaterialDto);
    }

    @ApiOperation(value = "根据物料主数据ID获取辅料信息")
    @GetMapping("/getByMaterialId")
    @Jinko(value = "根据物料主数据ID获取辅料信息", author = "wupeng")
    public Result<AccessoryMaterialDto> getByMaterialId(@RequestParam("materialId") Long materialId) {
        AccessoryMaterial accessoryMaterial = accessoryMaterialService.findMaterialId(materialId);
        if (null == accessoryMaterial) {
            return ResultGenerator.fail("辅料数据不存在!");
        }
        return ResultGenerator.success(toEagerDto(accessoryMaterial));
    }

    @ApiOperation(value = "根据物料编码获取辅料信息")
    @GetMapping("/getByMaterialCode")
    @Jinko(value = "根据物料编码获取辅料信息", author = "wupeng")
    public Result<AccessoryMaterialDto> getByMaterialCode(@RequestParam("materialCode") String materialCode) {
        AccessoryMaterial accessoryMaterial = accessoryMaterialService.getByMaterialCode(materialCode);
        if (null == accessoryMaterial) {
            return ResultGenerator.fail("辅料数据不存在!");
        }
        return ResultGenerator.success(toEagerDto(accessoryMaterial));
    }
    @ApiOperation(value = "根据物料编码获取辅料信息")
    @GetMapping("/getByMaterialCodes")
    public Result<AccessoryMaterialDto> getByMaterialCodes(@RequestParam("materialCode") String materialCode) {
        AccessoryMaterial accessoryMaterial = accessoryMaterialService.getByMaterialCode(materialCode);
        if (null == accessoryMaterial) {
            return ResultGenerator.fail("辅料数据不存在!");
        }
        AccessoryMaterialDto eagerDto = toEagerDto(accessoryMaterial);
        if(null != accessoryMaterial.getMaterialModel()){
            eagerDto.setMaterialModelId(accessoryMaterial.getMaterialModel().getId());
        }
        return ResultGenerator.success(eagerDto);
    }
    public AccessoryMaterialDto toLazyDto(AccessoryMaterial entity) {
        return modelMapper.map(entity, AccessoryMaterialDto.class);
    }

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

    public AccessoryMaterial fromDto(AccessoryMaterialDto dto) {
        return modelMapper.map(dto, AccessoryMaterial.class);
    }


}
