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

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.production.dto.ProductionAbnormalDto;
import com.sw.mes.yb.production.entity.ProductionAbnormal;
import com.sw.mes.yb.production.service.ProductionAbnormalService;
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.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lf
 * @description
 * @date 2024/1/12 11:07
 */
@Jinko(value = "新增生产异常相关接口", author = "liangfeng")
@RestController
@RequestMapping("/productionAbnormal")
@Slf4j
@Api(description = "生产异常接口")
public class ProductionAbnormalController {
    @Autowired
    private ModelMapper modelMapper;
    @Autowired
    private ProductionAbnormalService productionAbnormalService;

    @ApiOperation(value = "分页查询生产异常列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<ProductionAbnormalDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<ProductionAbnormal> specification = DynamicSpecifications.bySearchFilter(request, ProductionAbnormal.class);
        Page<ProductionAbnormal> page = productionAbnormalService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<ProductionAbnormalDto> 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("/{id}")
    public Result<ProductionAbnormalDto> get(@PathVariable @ApiParam(value = "生产异常id") Integer id) {
        ProductionAbnormal productionAbnormal = productionAbnormalService.get(id);
        if (null == productionAbnormal) {
            return ResultGenerator.fail("生产异常不存在");
        }
        return ResultGenerator.success(toLazyDto(productionAbnormal));
    }

    @ApiOperation(value = "创建生产异常")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "生产异常对象") ProductionAbnormalDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        ProductionAbnormal productionAbnormal = fromDto(dto);
        productionAbnormalService.save(productionAbnormal);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新生产异常")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "生产异常") ProductionAbnormalDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        ProductionAbnormal entity = productionAbnormalService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            ProductionAbnormal productionAbnormal = fromDto(dto);
            BeanUtils.copyProperties(productionAbnormal, entity, BeanUtil.getIgnoreProperties(productionAbnormal, null, null));
            productionAbnormalService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "处理生产异常")
    @PostMapping("/processingException")
    public Result processingException(@RequestBody @Valid @ApiParam(value = "生产异常") ProductionAbnormalDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        ProductionAbnormal entity = productionAbnormalService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            ProductionAbnormal productionAbnormal = fromDto(dto);
            BeanUtils.copyProperties(productionAbnormal, entity, BeanUtil.getIgnoreProperties(productionAbnormal, null, null));
            entity.setProcessingUser(BaseContextHandler.getUsername());
            entity.setProcessingDate(new Date());
            productionAbnormalService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "删除生产异常信息")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id", type = "query") @RequestParam Integer id) {
        ProductionAbnormal productionAbnormal = productionAbnormalService.get(id);
        if (null == productionAbnormal) {
            return ResultGenerator.fail("生产异常对象不存在");
        }
        productionAbnormalService.delete(id);
        return ResultGenerator.success();
    }

    private ProductionAbnormalDto toLazyDto(ProductionAbnormal entity) {
        ProductionAbnormalDto map = modelMapper.map(entity, ProductionAbnormalDto.class);
        map.setEquipmentCode(entity.getEquipmentCode());
        return map;
    }

    private ProductionAbnormal fromDto(ProductionAbnormalDto dto) {
        return modelMapper.map(dto, ProductionAbnormal.class);
    }

}
