package com.sw.mes.crucible.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.crucible.dto.CrucibleFixedCastingDto;
import com.sw.mes.crucible.dto.CrucibleFixedCastingSaveDto;
import com.sw.mes.crucible.entity.CrucibleFixedCasting;
import com.sw.mes.crucible.service.CrucibleFixedCastingService;
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/8 9:11
 */
@Jinko(value = "坩埚定投管理相关接口", author = "liangfeng")
@RestController
@RequestMapping("/crucibleFixedCasting")
@Slf4j
@Api(description = "坩埚定投管理接口")
public class CrucibleFixedCastingController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private CrucibleFixedCastingService crucibleFixedCastingService;

    @ApiOperation(value = "分页查询坩埚定投列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_equipment.code", value = "设备号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_code", value = "料号", dataType = "string", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<CrucibleFixedCastingDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<CrucibleFixedCasting> specification = DynamicSpecifications.bySearchFilter(request, CrucibleFixedCasting.class);
        Page<CrucibleFixedCasting> page = crucibleFixedCastingService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<CrucibleFixedCastingDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "坩埚定投管理详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "坩埚定投管理id", paramType = "path", dataType = "Integer"),
    })
    @GetMapping("/{id}")
    public Result<CrucibleFixedCastingDto> get(@PathVariable Integer id) {
        CrucibleFixedCasting crucibleFixedCasting = crucibleFixedCastingService.get(id);
        if (null == crucibleFixedCasting) {
            return ResultGenerator.fail("该坩埚定投信息不存在");
        }
        CrucibleFixedCastingDto crucibleFixedCastingDto = toEagerDto(crucibleFixedCasting);
        return ResultGenerator.success(crucibleFixedCastingDto);
    }

    @ApiOperation(value = "创建坩埚定投管理信息")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "坩埚定投管理对象") CrucibleFixedCastingSaveDto dto,
                         BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        crucibleFixedCastingService.batchCreate(dto);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新坩埚定投管理信息")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "坩埚定投管理对象") CrucibleFixedCastingDto dto,
                         BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        CrucibleFixedCasting crucibleFixedCastingDb = crucibleFixedCastingService.get(dto.getId());
        if (crucibleFixedCastingDb == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        CrucibleFixedCasting crucibleFixedCastingDb1 =
                crucibleFixedCastingService.findByEquipmentIdAndfixedCastingTypeAndIdNot(dto.getEquipmentId(), dto.getFixedCastingType(), dto.getId());
        if (null != crucibleFixedCastingDb1) {
            return ResultGenerator.fail("该设备号与定投类型已存在!!!");
        }
        CrucibleFixedCasting crucibleFixedCasting = fromDto(dto);
        try {
            BeanUtils.copyProperties(crucibleFixedCasting, crucibleFixedCastingDb, BeanUtil.getIgnoreProperties(crucibleFixedCasting, null, null));
            crucibleFixedCastingDb.setUpdateUser(BaseContextHandler.getUsername());
            crucibleFixedCastingDb.setUpdateDate(new Date());
            crucibleFixedCastingService.saveOrUpdate(crucibleFixedCastingDb);
            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) {
        crucibleFixedCastingService.delete(id);
        return ResultGenerator.success();
    }

    private CrucibleFixedCasting fromDto(CrucibleFixedCastingDto entity) {
        CrucibleFixedCasting crucibleFixedCasting = modelMapper.map(entity, CrucibleFixedCasting.class);
        return crucibleFixedCasting;
    }

    public CrucibleFixedCastingDto toEagerDto(CrucibleFixedCasting entity) {
        CrucibleFixedCastingDto crucibleFixedCastingDto = modelMapper.map(entity, CrucibleFixedCastingDto.class);
        crucibleFixedCastingDto.setEquipmentCode(entity.getEquipmentCode());
        return crucibleFixedCastingDto;
    }

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