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.CrucibleDto;
import com.sw.mes.crucible.entity.Crucible;
import com.sw.mes.crucible.service.CrucibleService;
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/6 14:37
 */
@Jinko(value = "坩埚管理相关接口", author = "liangfeng")
@RestController
@RequestMapping("/crucible")
@Slf4j
@Api(description = "坩埚管理接口")
public class CrucibleController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private CrucibleService crucibleService;

    @ApiOperation(value = "分页查询坩埚列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_batchNumber", value = "批次号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_code", value = "料号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_isLock", value = "是否锁定", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<CrucibleDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<Crucible> specification = DynamicSpecifications.bySearchFilter(request, Crucible.class);
        Page<Crucible> page = crucibleService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<CrucibleDto> 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<CrucibleDto> get(@PathVariable Integer id) {
        Crucible crucible = crucibleService.get(id);
        if (null == crucible) {
            return ResultGenerator.fail("该坩埚信息不存在");
        }
        CrucibleDto crucibleDto = toEagerDto(crucible);
        return ResultGenerator.success(crucibleDto);
    }

    @ApiOperation(value = "创建坩埚管理信息")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "坩埚管理对象") CrucibleDto crucibleDto,
                         BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        Crucible crucibleDb = crucibleService.findByBatchNumber(crucibleDto.getBatchNumber());
        if (null != crucibleDb) {
            return ResultGenerator.fail("坩埚批次号已存在");
        }
        Crucible crucible = fromDto(crucibleDto);
        crucible.setCreateDate(new Date());
        crucible.setCreateUser(BaseContextHandler.getUsername());
        crucibleService.saveOrUpdate(crucible);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新坩埚管理信息")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "坩埚管理信息") CrucibleDto crucibleDto,
                         BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (crucibleDto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        Crucible crucibleDb = crucibleService.get(crucibleDto.getId());
        if (crucibleDb == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        if (!crucibleDb.getBatchNumber().equals(crucibleDto.getBatchNumber())){
            return ResultGenerator.fail("批次号与原数据不一样!!!!");
        }
        Crucible crucible = fromDto(crucibleDto);
        try {
            BeanUtils.copyProperties(crucible, crucibleDb, BeanUtil.getIgnoreProperties(crucible, null, null));
            crucibleDb.setUpdateUser(BaseContextHandler.getUsername());
            crucibleDb.setUpdateDate(new Date());
            crucibleService.saveOrUpdate(crucibleDb);
            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) {
        crucibleService.delete(id);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "根据批次号查询料号信息")
    @GetMapping("/findCodeByBatchNumber")
    public Result<CrucibleDto> findCodeByBatchNumber(@ApiParam(value = "batchNumber", type = "query") @RequestParam String batchNumber) {
        CrucibleDto dto = crucibleService.findCodeByBatchNumber(batchNumber);
        if (null == dto) {
            return ResultGenerator.fail("料号信息不存在");
        }
        return ResultGenerator.success(dto);
    }

    private Crucible fromDto(CrucibleDto entity) {
        Crucible crucible = modelMapper.map(entity, Crucible.class);
        return crucible;
    }

    public CrucibleDto toEagerDto(Crucible entity) {
        CrucibleDto crucibleDto = modelMapper.map(entity, CrucibleDto.class);
        return crucibleDto;
    }

    public CrucibleDto toLazyDto(Crucible entity) {
        CrucibleDto map = modelMapper.map(entity, CrucibleDto.class);
        return map;
    }
}
