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

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.DynamicSpecifications;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.yb.plan.dto.WaterLineManageMediumDto;
import com.sw.mes.yb.plan.entity.WaterLineManageMedium;
import com.sw.mes.yb.plan.service.WaterLineManageMediumService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
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.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @zhaoyayun
 * @20230913
 * @v1.0.0
 **/
@RestController
@RequestMapping("/WaterLineManageMedium")
@Slf4j
@Api("水位拉动配置中间信息接口")
public class WaterLineManageMediumController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private WaterLineManageMediumService waterLineManageMediumService;

    @ApiOperation(value = "分页查询水位拉动中间信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<WaterLineManageMediumDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<WaterLineManageMedium> specification = DynamicSpecifications.bySearchFilter(request, WaterLineManageMedium.class);
        Page<WaterLineManageMedium> page = waterLineManageMediumService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<WaterLineManageMediumDto> list = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(list, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有水位拉动中间信息")
    @GetMapping("/listAll")
    public Result<List<WaterLineManageMediumDto>> listAll(ServletRequest request) {
        Specification<WaterLineManageMedium> specification = DynamicSpecifications.bySearchFilter(request, WaterLineManageMedium.class);
        List<WaterLineManageMedium> WaterLineManageMediums = waterLineManageMediumService.findByExampleSort(specification, null);
        List<WaterLineManageMediumDto> WaterLineManageMediumDto = WaterLineManageMediums.stream()
                .map(WaterLineManageMedium -> toLazyDto(WaterLineManageMedium))
                .collect(Collectors.toList());
        return ResultGenerator.success(WaterLineManageMediumDto);
    }


    @ApiOperation(value = "新增水位拉动中间信息")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "水位拉动中间信息") WaterLineManageMediumDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto == null) {
            return ResultGenerator.fail("新增信息不存在");
        }
        //校验表中是否已有这种组合的记录，防止重复
        List<WaterLineManageMedium> waterLineManageMediumServiceByParams = waterLineManageMediumService.findByParams(dto.getProductType(), dto.getConductiveType(), dto.getSpecification(), dto.getDopant(),dto.getSideLengthRange(),dto.getYbProductGrade(), dto.getResistanceLevel());
        if (!waterLineManageMediumServiceByParams.isEmpty()){
            return ResultGenerator.fail("信息重复录入！");
        }

        try {
//            String uuid = UUID.randomUUID().toString();
//            if (null == dto.getUuid() || dto.getUuid().isEmpty()){
//                dto.setUuid(uuid);
//            }
            dto.setCreateTime(new Date());
            dto.setCreateUserName(BaseContextHandler.getUsername());
            waterLineManageMediumService.saveOrUpdate(fromDto(dto));
            return ResultGenerator.success();
        } catch (Exception e) {
            log.error("新增水位拉动中间信息", e);
            return ResultGenerator.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "更新水位拉动中间信息")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "水位拉动中间信息") WaterLineManageMediumDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto == null) {
            return ResultGenerator.fail("原信息不存在");
        }

        //校验表中是否已有这种组合的记录，防止重复
        List<WaterLineManageMedium> waterLineManageMediumServiceByParams = waterLineManageMediumService.findByParams(dto.getProductType(), dto.getConductiveType(), dto.getSpecification(), dto.getDopant(), dto.getSideLengthRange(),dto.getYbProductGrade(), dto.getResistanceLevel());
        if (!waterLineManageMediumServiceByParams.isEmpty()){
            return ResultGenerator.fail("信息重复录入！");
        }

        try {
            waterLineManageMediumService.saveOrUpdate(fromDto(dto));
            return ResultGenerator.success();
        } catch (Exception e) {
            log.error("更新水位拉动中间信息", e);
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "删除水位拉动中间信息")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Integer[] ids) {
        for (Integer id : ids) {
            waterLineManageMediumService.delete(id);
        }
        return ResultGenerator.success();
    }




    public WaterLineManageMediumDto toLazyDto(WaterLineManageMedium entity) {
        return modelMapper.map(entity, WaterLineManageMediumDto.class);
    }

    public WaterLineManageMedium fromDto(WaterLineManageMediumDto dto) {
        return modelMapper.map(dto, WaterLineManageMedium.class);
    }

}
