package com.sw.mes.sap.controller;

import java.io.IOException;
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.dto.wms.ReportSapWorkinghoursDto;
import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultCode;
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.entity.ReportSapWorkinghours;
import com.sw.mes.sap.service.ReportSapWorkinghoursService;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

/**
 * MES报工SAP工时接口Controller
 *
 * @author liru
 * @date 2024-01-07
 */
@RestController
@Jinko(value="MES报工SAP工时接口Controller",author = "liru")
@RequestMapping("/sap/workinghours")
public class ReportSapWorkinghoursController
{
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private ReportSapWorkinghoursService reportSapWorkinghoursService;

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

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

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

    @ApiOperation(value = "更新数据")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "ReportSapWorkinghours") ReportSapWorkinghoursDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        ReportSapWorkinghours entity = reportSapWorkinghoursService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            ReportSapWorkinghours entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
                reportSapWorkinghoursService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "查询工时报工数据")
    @GetMapping("/findData")
    public Result fnidData(@RequestParam(value = "remark") String remark, @RequestParam(value = "procName") String procName, @RequestParam(value = "crystalNo") String crystalNo) {
        List<ReportSapWorkinghoursDto> byRemarkAndBwartAndProcName = reportSapWorkinghoursService.findByRemarkAndProcNameAndCrystalNo(remark, procName, crystalNo);
        return ResultGenerator.success(byRemarkAndBwartAndProcName);
    }

    @ApiOperation(value = "删除记录")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        for (Long id : ids) {
                reportSapWorkinghoursService.delete(id);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "发送报工")
    @PostMapping("/send")
    public Result send(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        try {
        	List<Result> results = reportSapWorkinghoursService.sendReportWord(ids,"Manual");
        	int successNum = 0;
        	int faultNum = 0;
        	String errormsg = "";
        	for (Result rt : results) {
        		if(rt.getCode().equals(ResultCode.SUCCESS.getCode())) {
        			successNum++;
        		}else {
        			faultNum ++;
        			errormsg = "["+rt.getMessage()+"]";
        		}
			}
        	
        	if(errormsg.equals("")) {
        		return ResultGenerator.success("请求记录"+ids.length+"条,成功("+successNum+")条,失败("+faultNum+")条.失败原因:"+errormsg);
        	}else {
        		return ResultGenerator.fail("请求记录"+ids.length+"条,成功("+successNum+")条,失败("+faultNum+")条.失败原因:"+errormsg);
        	}
        }catch (Exception e){
            return ResultGenerator.fail("报工失败,请稍后再试");
        }
    }
    
    @ApiOperation(value = "导出工时报工列表")
    @GetMapping("/export")
    public void export(ServletRequest request, HttpServletResponse response) {
        try {
        	Specification<ReportSapWorkinghours> specification = DynamicSpecifications.bySearchFilter(request, ReportSapWorkinghours.class);
            List<ReportSapWorkinghours> reportSapWorkinghourses = reportSapWorkinghoursService.findByExampleSort(specification, null);
            List<ReportSapWorkinghoursDto> reportSapWorkinghoursesDtos = reportSapWorkinghourses.stream()
                    .map(reportSapWorkinghours -> toLazyDto(reportSapWorkinghours))
                    .collect(Collectors.toList());
            EasyExcelUtils.write(response, ReportSapWorkinghoursDto.class, "导出工时报工列表", "导出工时报工列表", reportSapWorkinghoursesDtos);
        } catch (IOException e) {
            throw new RuntimeException("导出工时报工列表失败，错误信息：" + e.getMessage());
        }
    }

    public ReportSapWorkinghoursDto toLazyDto(ReportSapWorkinghours entity) {
        return modelMapper.map(entity, ReportSapWorkinghoursDto.class);
    }

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

    public ReportSapWorkinghours fromDto(ReportSapWorkinghoursDto dto) {
        return modelMapper.map(dto, ReportSapWorkinghours.class);
    }
}
