package com.sw.mes.sap.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
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.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 org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.sw.mes.core.annotation.Jinko;
import com.sw.mes.core.dto.sap.ReportSapChargItemDto;
import com.sw.mes.core.dto.sap.ReportSapGoodsmvtDto;
import com.sw.mes.core.dto.sap.ReportSapGoodsmvtExportDto;
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.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.core.utils.StringUtils;
import com.sw.mes.sap.dto.statistics.StatisticsDto;
import com.sw.mes.sap.entity.ReportSapGoodsmvt;
import com.sw.mes.sap.service.LogSapMesInteractiveService;
import com.sw.mes.sap.service.LogSapStockService;
import com.sw.mes.sap.service.ReportSapGoodsmvtService;

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;

/**
 * MES报工SAP货物移动接口Controller
 *
 * @author liru
 * @date 2024-01-06
 */
@RestController
@Jinko(value="MES报工SAP货物移动接口Controller",author = "liru")
@Slf4j
@RequestMapping("/sap/goodsmvt")
public class ReportSapGoodsmvtController
{
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private ReportSapGoodsmvtService reportSapGoodsmvtService;
    
    @Autowired
    private LogSapStockService logSapStockService;
    @Autowired
    private LogSapMesInteractiveService logSapMesInteractiveService;

    @ApiOperation(value = "分页查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<ReportSapGoodsmvtDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
        Specification<ReportSapGoodsmvt> specification = DynamicSpecifications.bySearchFilter(request, ReportSapGoodsmvt.class);
        Page<ReportSapGoodsmvt> page = reportSapGoodsmvtService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<ReportSapGoodsmvtDto> 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("/statistics")
//    public Result statistics(ServletRequest request) {
//        Specification<ReportSapGoodsmvt> specification = DynamicSpecifications.bySearchFilter(request, ReportSapGoodsmvt.class);
//        List<ReportSapGoodsmvt> reportSapGoodsmvts = reportSapGoodsmvtService.statistics(specification);
//        List<ReportSapGoodsmvtDto> reportSapGoodsmvtDtos = reportSapGoodsmvts.stream()
//                .map(reportSapGoodsmvt -> toLazyDto(reportSapGoodsmvt))
//                .collect(Collectors.toList());
//        return ResultGenerator.success(reportSapGoodsmvtDtos);
//    }
    
    
    @ApiOperation(value = "获取所有数据")
    @GetMapping("/listAll")
    public Result<List<ReportSapGoodsmvtDto>> listAll(ServletRequest request) {
        Specification<ReportSapGoodsmvt> specification = DynamicSpecifications.bySearchFilter(request, ReportSapGoodsmvt.class);
        List<ReportSapGoodsmvt> reportSapGoodsmvts = reportSapGoodsmvtService.findByExampleSort(specification, null);
        List<ReportSapGoodsmvtDto> reportSapGoodsmvtDtos = reportSapGoodsmvts.stream()
                .map(reportSapGoodsmvt -> toLazyDto(reportSapGoodsmvt))
                .collect(Collectors.toList());
        return ResultGenerator.success(reportSapGoodsmvtDtos);
    }
    
    
    @ApiOperation(value = "获取所有数据")
    @GetMapping("/batchSyn")
    public Result<List<ReportSapGoodsmvtDto>> batchSyn(ServletRequest request) {
    	
    	
    	List<ReportSapGoodsmvt> list = reportSapGoodsmvtService.findAll();
    	
    	for (ReportSapGoodsmvt reportSapGoodsmvt : list) {
    		reportSapGoodsmvtService.saveOrUpdate(reportSapGoodsmvt);
		}
    	
        return ResultGenerator.success();
    }
    
    
    @ApiOperation(value = "根据id获取详细信息")
    @GetMapping("/{id}")
    public Result<ReportSapGoodsmvtDto> get(@PathVariable @ApiParam(value="ReportSapGoodsmvtid") Long id) {
        ReportSapGoodsmvt reportSapGoodsmvt = reportSapGoodsmvtService.get(id);
        if (null == reportSapGoodsmvt)
            return ResultGenerator.fail("该记录不存在");
        return ResultGenerator.success(toEagerDto(reportSapGoodsmvt));
    }

    @ApiOperation(value = "创建数据")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "ReportSapGoodsmvt对象") ReportSapGoodsmvtDto reportSapGoodsmvtDto) {
        try {
	    	ReportSapGoodsmvt reportSapGoodsmvt = fromDto(reportSapGoodsmvtDto);
	        reportSapGoodsmvt.setStatus(false);
	        reportSapGoodsmvtService.saveOrUpdate(reportSapGoodsmvt);
        }catch (Exception e) {
        	ResultGenerator.fail(e.getMessage());
		}
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新数据")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "ReportSapGoodsmvt") ReportSapGoodsmvtDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        try {
            ReportSapGoodsmvt entityfromFto = fromDto(dto);
            entityfromFto.setAsyn(false);
            reportSapGoodsmvtService.saveOrUpdate(entityfromFto);
            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) {
                reportSapGoodsmvtService.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 = reportSapGoodsmvtService.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){
        	log.error("",e);
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "根据物料号和移动类型获取批次号")
    @GetMapping("/findByMatnrAndBwart")
    public Result<ReportSapGoodsmvtDto> findByMatnrAndBwart(@RequestParam String matnr,@RequestParam String bwart) {
        try {
            ReportSapGoodsmvt byMatnrAndBwart = reportSapGoodsmvtService.findByCrystalNoAndBwart(matnr, bwart);
            if (null == byMatnrAndBwart){
                return ResultGenerator.fail("未获取批次号!");
            }
            return ResultGenerator.success(toLazyDto(byMatnrAndBwart));
        }catch (Exception e){
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "根据晶编号和移动类型获取批次号")
    @GetMapping("/findByCrystalNoAndBwart")
    public Result<ReportSapGoodsmvtDto> findByCrystalNoAndBwart(@RequestParam String crystalNo,@RequestParam String bwart) {
        try {
            ReportSapGoodsmvt byMatnrAndBwart = reportSapGoodsmvtService.findByCrystalNoAndBwart(crystalNo, bwart);
            if (null == byMatnrAndBwart){
                return ResultGenerator.fail("未获取到数据!");
            }
            return ResultGenerator.success(toLazyDto(byMatnrAndBwart));
        }catch (Exception e){
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "导出报工记录列表")
    @GetMapping("/export")
    public void export(ServletRequest request, HttpServletResponse response) {
        try {
        	Specification<ReportSapGoodsmvt> specification = DynamicSpecifications.bySearchFilter(request, ReportSapGoodsmvt.class);
            List<ReportSapGoodsmvt> reportSapGoodsmvts = reportSapGoodsmvtService.findByExampleSort(specification, null);
            List<ReportSapGoodsmvtExportDto> reportSapGoodsmvtsDtos = reportSapGoodsmvts.stream()
                    .map(reportSapGoodsmvt ->{
                        ReportSapGoodsmvtExportDto dto = toLazyDto1(reportSapGoodsmvt);
                        dto.setCount(new BigDecimal(dto.getMenge()));
                        return dto;
                    }
                    )
                    .collect(Collectors.toList());
            EasyExcelUtils.write(response, ReportSapGoodsmvtDto.class, "导出报工列表", "导出报工列表", reportSapGoodsmvtsDtos);
        } catch (IOException e) {
            throw new RuntimeException("导出报工列表失败，错误信息：" + e.getMessage());
        }
    }
    
    
    @ApiOperation(value = "导入Excel")
    @PostMapping("/importExcel")
    public Result importExcel(MultipartFile file) {
        String message = reportSapGoodsmvtService.importExcel(file);
        if (null != message) {
            return ResultGenerator.fail(message);
        } else {
            return ResultGenerator.success();
        }
    }
    
    
    @ApiOperation(value = "导入SAP明细")
    @PostMapping("/importSapExcel")
    public Result importSapExcel(MultipartFile file) {
        String message = reportSapGoodsmvtService.importSAPExcel(file);
        if (null != message) {
            return ResultGenerator.fail(message);
        } else {
            return ResultGenerator.success();
        }
    }
    
    
    
    
    @ApiOperation(value = "根据物料号和移动类型获取批次号")
    @GetMapping("/ybcshdbStatistics")
    public List<StatisticsDto> ybcshdbStatistics(@RequestBody StatisticsDto dto) {
    	return reportSapGoodsmvtService.statisticYbcshdb(dto);
    }
    
    
    @ApiOperation(value = "投料量报表")
    @GetMapping("/ljStatistics")
    public List<Map<Object,Object>> ljStatistics() {
    	return reportSapGoodsmvtService.ljStatistics();
    }
    
    @ApiOperation(value = "单晶收货统计")
    @PostMapping("/djshStatistics")
    public List<Map<Object,Object>> djshStatistics(@RequestBody StatisticsDto dto) {
    	if(dto.getStartDate()==null) {
    		throw new RuntimeException("必选时间范围");
    	}
    	
    	if(dto.getEndDate()==null) {
    		throw new RuntimeException("必选时间范围");
    	}
    	
    	return reportSapGoodsmvtService.djshStatistics(dto);
    }
    
    @ApiOperation(value = "截断消耗统计")
    @PostMapping("/jdxhStatistics")
    public List<Map<Object,Object>> jdxhStatistics(@RequestBody StatisticsDto dto) {
    	if(dto.getStartDate()==null) {
    		throw new RuntimeException("必选时间范围");
    	}
    	
    	if(dto.getEndDate()==null) {
    		throw new RuntimeException("必选时间范围");
    	}
    	
    	return reportSapGoodsmvtService.jdxhStatistics(dto);
    }

    
    @ApiOperation(value = "截断收货统计")
    @PostMapping("/jdshStatistics")
    public List<Map<Object,Object>> jdshStatistics(@RequestBody StatisticsDto dto) {
    	if(dto.getStartDate()==null) {
    		throw new RuntimeException("必选时间范围");
    	}
    	
    	if(dto.getEndDate()==null) {
    		throw new RuntimeException("必选时间范围");
    	}
    	
    	return reportSapGoodsmvtService.jdshStatistics(dto);
    }

    
    @ApiOperation(value = "刀剖消耗统计")
    @PostMapping("/dpxhStatistics")
    public List<Map<Object,Object>> dpxhStatistics(@RequestBody StatisticsDto dto) {
    	if(dto.getStartDate()==null) {
    		throw new RuntimeException("必选时间范围");
    	}
    	
    	if(dto.getEndDate()==null) {
    		throw new RuntimeException("必选时间范围");
    	}
    	
    	return reportSapGoodsmvtService.dpxhStatistics(dto);
    }



    @ApiOperation(value = "修改SAP订单号")
    @PostMapping("/modifyAufnrByCrystalNo")
    public Result modifyAufnrByCrystalNo(@RequestBody String json) {

        Map map = JSON.parseObject(json, Map.class);

        String procName = (String) map.get("procName");
        Integer status = (Integer) map.get("status");
        List<String> crystalNoList = (List<String>) map.get("crystalNoList");
        if (!StringUtils.equals(procName,"刀剖消耗")){
            throw new RuntimeException("非刀剖消耗，禁止修改！");
        }
        return ResultGenerator.success(reportSapGoodsmvtService.modifyAufnrByCrystalNo(procName,crystalNoList,status));
    }
    
    
    @ApiOperation(value = "检查未自动报工SAP记录")
    @PostMapping("/startCheckNotAutoSendSap")
    public void startCheckNotAutoSendSap() {
    	reportSapGoodsmvtService.checkNotAutoSendSap();
    }

    public ReportSapGoodsmvtDto toLazyDto(ReportSapGoodsmvt entity) {
        ReportSapGoodsmvtDto dto = modelMapper.map(entity, ReportSapGoodsmvtDto.class);
        dto.setChargItems(new Gson().fromJson(entity.getChargItem(),new TypeToken<List<ReportSapChargItemDto>>(){}.getType()));
        return dto;
    }

    public ReportSapGoodsmvtExportDto toLazyDto1(ReportSapGoodsmvt entity) {
        ReportSapGoodsmvtExportDto dto = modelMapper.map(entity, ReportSapGoodsmvtExportDto.class);
        dto.setChargItems(new Gson().fromJson(entity.getChargItem(),new TypeToken<List<ReportSapGoodsmvtExportDto>>(){}.getType()));
        return dto;
    }

    public ReportSapGoodsmvtDto toEagerDto(ReportSapGoodsmvt entity) {
        ReportSapGoodsmvtDto dto = modelMapper.map(entity, ReportSapGoodsmvtDto.class);
        dto.setChargItems(new Gson().fromJson(entity.getChargItem(),new TypeToken<List<ReportSapChargItemDto>>(){}.getType()));
        return dto;
    }

    public ReportSapGoodsmvt fromDto(ReportSapGoodsmvtDto dto) {
        ReportSapGoodsmvt reportSapGoodsmvt = modelMapper.map(dto, ReportSapGoodsmvt.class);
        reportSapGoodsmvt.setChargItem(new Gson().toJson(dto.getChargItems()));
        return reportSapGoodsmvt;
    }
}
