package com.sw.mes.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.*;
import com.sw.mes.domain.ProductionExceptionLog;
import com.sw.mes.scheduled.StatisticsCptInspectBalanceScheduled;
import com.sw.mes.service.ProductionExceptionLogService;
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.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.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.sw.mes.dto.ProductionExceptionLogDto;

/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/exceptionLog")
@Slf4j
@Api(description = "检验报警信息接口")
public class ExceptionLogController {
    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private ProductionExceptionLogService productionExceptionLogService;

    @Autowired
    private StatisticsCptInspectBalanceScheduled scheduled;

    @ApiOperation(value = "分页查询检验报警信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<ProductionExceptionLogDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        //分页查询
        QueryWrapper<ProductionExceptionLog> queryWrapper =  DynmaicQueryWrapper.searchFilter(request, ProductionExceptionLog.class);
        Page<ProductionExceptionLog> listPage = productionExceptionLogService.page(new Page<>(requestPage.getPage(), requestPage.getRows()), queryWrapper);
        List<ProductionExceptionLogDto> dtos = listPage.getRecords().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, listPage.getTotal());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有检验报警信息")
    @GetMapping("/listAll")
    public Result<List<ProductionExceptionLogDto>> listAll(ServletRequest request) {
        List<ProductionExceptionLogDto> exceptionLogDtos = productionExceptionLogService.list().stream()
                .map(exceptionLog -> toLazyDto(exceptionLog))
                .collect(Collectors.toList());
        return ResultGenerator.success(exceptionLogDtos);
    }

    @ApiOperation(value = "检验报警信息详细信息")
    @GetMapping("/{id}")
    public Result<ProductionExceptionLogDto> get(@PathVariable @ApiParam(value = "ExceptionLogid") Long id) {
        ProductionExceptionLog productionExceptionLog = productionExceptionLogService.getById(id);
        if (null == productionExceptionLog)
            return ResultGenerator.fail("该ExceptionLog不存在");
        return ResultGenerator.success(toEagerDto(productionExceptionLog));
    }

    @ApiOperation(value = "创建检验报警信息")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "ExceptionLog对象") ProductionExceptionLogDto exceptionLogDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        ProductionExceptionLog exceptionLog = fromDto(exceptionLogDto);
        productionExceptionLogService.saveOrUpdate(exceptionLog);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新检验报警信息")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "ExceptionLog") ProductionExceptionLogDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        ProductionExceptionLog productionExceptionLog = productionExceptionLogService.getById(dto.getId());
        if (productionExceptionLog == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            ProductionExceptionLog entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, productionExceptionLog, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            productionExceptionLog.setUserUpdate(BaseContextHandler.getUsername());
            productionExceptionLog.setGmtUpdate(new Date());
            productionExceptionLog.setStatus(true);
            productionExceptionLogService.saveOrUpdate(productionExceptionLog);
            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 Integer[] ids) {
        for (Integer id : ids) {
            productionExceptionLogService.removeById(id);
        }
        return ResultGenerator.success();
    }

    @GetMapping("/getCount")
    public Result<Integer> getCount(Integer type) {
        type = type == null ? 0 : type;
        return ResultGenerator.success(productionExceptionLogService.getCount(type));
    }

    @ApiOperation(value = "分页查询检验报警信息列表(最多2000条)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_type", value = "类型", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_gmtCreate", value = "开始时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "search_LTE_gmtCreate", value = "结束时间", dataType = "String", paramType = "query"),
    })
    @GetMapping("/export")
    public void export(HttpServletResponse response, ServletRequest request, @ApiIgnore RequestPage requestPage) {
        try {
            requestPage.setRows(2000);
            QueryWrapper<ProductionExceptionLog> productionExceptionLogQueryWrapper = DynmaicQueryWrapper.searchFilter(request, ProductionExceptionLog.class);
            Page<ProductionExceptionLog> listPage = productionExceptionLogService.page(new Page<>(requestPage.getPage(), requestPage.getRows()), productionExceptionLogQueryWrapper);
          List<ProductionExceptionLogDto> dtos = listPage.getRecords().stream()
                    .map(this::toLazyDto)
                    .collect(Collectors.toList());
            EasyExcelUtils.write(response, ProductionExceptionLogDto.class, "检验报警信息", "检验报警信息", dtos);
        } catch (Exception e) {
            throw new RuntimeException("检验报警记录导出失败，错误信息：" + e.getMessage());
        }
    }

    public ProductionExceptionLogDto toLazyDto(ProductionExceptionLog entity) {
        return modelMapper.map(entity, ProductionExceptionLogDto.class);
    }

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

    public ProductionExceptionLog fromDto(ProductionExceptionLogDto dto) {
        return modelMapper.map(dto, ProductionExceptionLog.class);
    }
}
