package com.sw.mes.sap.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

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.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 com.sw.mes.core.annotation.Jinko;
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.EasyExcelUtils;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.sap.dto.ReportErpInputRecordDetailDto;
import com.sw.mes.sap.dto.ReportSapMblnrQueryDto;
import com.sw.mes.sap.entity.ReportSapGoodsmvt;
import com.sw.mes.sap.entity.ReportSapMblnrQuery;
import com.sw.mes.sap.service.ReportSapMblnrQueryService;

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 springfox.documentation.annotations.ApiIgnore;

/**
 * 物料凭证查询接口Controller
 * 
 * @author liru
 * @date 2024-04-15
 */
@Slf4j
@RestController
@RequestMapping("/sap/reportSapMblnrQuery")
@Jinko(value="晶科库存位置信息Controller",author = "liru")
public class ReportSapMblnrQueryController
{
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private ReportSapMblnrQueryService reportSapMblnrQueryService;

    @ApiOperation(value = "分页查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<ReportSapMblnrQueryDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
        Specification<ReportSapMblnrQuery> specification = DynamicSpecifications.bySearchFilter(request, ReportSapMblnrQuery.class);
        Page<ReportSapMblnrQuery> page = reportSapMblnrQueryService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<ReportSapMblnrQueryDto> 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("/listAll")
    public Result<List<ReportSapMblnrQueryDto>> listAll(ServletRequest request) {
        Specification<ReportSapMblnrQuery> specification = DynamicSpecifications.bySearchFilter(request, ReportSapMblnrQuery.class);
        List<ReportSapMblnrQuery> reportSapMblnrQuerys = reportSapMblnrQueryService.findByExampleSort(specification, null);
        List<ReportSapMblnrQueryDto> reportSapMblnrQueryDtos = reportSapMblnrQuerys.stream()
                .map(reportSapMblnrQuery -> toLazyDto(reportSapMblnrQuery))
                .collect(Collectors.toList());
        return ResultGenerator.success(reportSapMblnrQueryDtos);
    }

    @ApiOperation(value = "根据id获取详细信息")
    @GetMapping("/{id}")
    public Result<ReportSapMblnrQueryDto> get(@PathVariable @ApiParam(value="ReportSapMblnrQueryid") Long id) {
        ReportSapMblnrQuery ReportSapMblnrQuery = reportSapMblnrQueryService.get(id);
        if (null == ReportSapMblnrQuery)
            return ResultGenerator.fail("该记录不存在");
        return ResultGenerator.success(toEagerDto(ReportSapMblnrQuery));
    }

    @ApiOperation(value = "创建数据")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "ReportSapMblnrQuery对象") ReportSapMblnrQueryDto ReportSapMblnrQueryDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        ReportSapMblnrQuery ReportSapMblnrQuery = fromDto(ReportSapMblnrQueryDto);
        reportSapMblnrQueryService.saveOrUpdate(ReportSapMblnrQuery);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新数据")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "ReportSapMblnrQuery") ReportSapMblnrQueryDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        ReportSapMblnrQuery entity = reportSapMblnrQueryService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            ReportSapMblnrQuery entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            reportSapMblnrQueryService.saveOrUpdate(entity);
            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 Long[] ids) {
        for (Long id : ids) {
            reportSapMblnrQueryService.delete(id);
        }
        return ResultGenerator.success();
    }
    
    
    @ApiOperation(value = "恢复报工记录")
    @PostMapping("/recoveryGoodsmvt")
    public Result recoveryGoodsmvt(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        for (Long id : ids) {
            try {
				reportSapMblnrQueryService.recoveryGoodsmvt(id);
			} catch (ParseException e) {
				e.printStackTrace();
			}
        }
        return ResultGenerator.success();
    }
    
    
    @ApiOperation(value = "对比报工记录")
    @PostMapping("/contrastGoodsmvt")
    public Result contrastGoodsmvt() {
        reportSapMblnrQueryService.contrastGoodsmvt();
        return ResultGenerator.success();
    }
    
    
    @ApiOperation(value = "导出SAP物料凭证")
    @GetMapping("/export")
    public void export(ServletRequest request, HttpServletResponse response) {
        try {
        	Specification<ReportSapMblnrQuery> specification = DynamicSpecifications.bySearchFilter(request, ReportSapMblnrQuery.class);
            List<ReportSapMblnrQuery> reportSapMblnrQuerys = reportSapMblnrQueryService.findByExampleSort(specification, null);
            List<ReportSapMblnrQueryDto> reportSapMblnrQuerysDtos = reportSapMblnrQuerys.stream().map(entity -> toLazyDto(entity)).collect(Collectors.toList());
            EasyExcelUtils.write(response, ReportSapMblnrQueryDto.class, "导出SAP物料凭证列表", "导出SAP物料凭证列表", reportSapMblnrQuerysDtos);
        } catch (IOException e) {
            throw new RuntimeException("导出记录列表失败，错误信息：" + e.getMessage());
        }
    }

    public ReportSapMblnrQueryDto toLazyDto(ReportSapMblnrQuery entity) {
        return modelMapper.map(entity, ReportSapMblnrQueryDto.class);
    }

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

    public ReportSapMblnrQuery fromDto(ReportSapMblnrQueryDto dto) {
        return modelMapper.map(dto, ReportSapMblnrQuery.class);
    }
}