package com.sw.mes.sap.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
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.alibaba.fastjson.JSONObject;
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.DateUtil;
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.sap.dto.LogSapStockDto;
import com.sw.mes.sap.dto.WarehouseStatisticsDto;
import com.sw.mes.sap.entity.LogSapStock;
import com.sw.mes.sap.entity.WarehouseLocation;
import com.sw.mes.sap.service.LogSapStockService;
import com.sw.mes.sap.service.SAPOutputServiceService;
import com.sw.mes.sap.service.WarehouseLocationService;

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;

/**
 * SAP库存数据Controller
 * 
 * @author liru
 * @date 2024-03-04
 */
@Slf4j
@RestController
@Jinko(value="晶科SAP下发生产工单通信记录Controller",author = "liru")
@RequestMapping("/mes/sapStock")
public class LogSapStockController
{
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private LogSapStockService logSapStockService;
    @Autowired
    private SAPOutputServiceService sAPOutputServiceService;
    @Autowired
    private WarehouseLocationService warehouseLocationService;

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

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

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

    @ApiOperation(value = "更新数据")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "LogSapStock") LogSapStockDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        LogSapStock entity = logSapStockService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            LogSapStock entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            logSapStockService.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 Integer[] ids) {
        for (Integer id : ids) {
            logSapStockService.delete(id);
        }
        return ResultGenerator.success();
    }
    
    
    @ApiOperation(value = "获取Sap库存")
    @PostMapping("/getSapStock")
    public Result synSapStock(@RequestBody @ApiParam(value = "LogSapStock") LogSapStockDto dto) {
    	try {
    		LogSapStock logSapStock = logSapStockService.findByLgortAndMatnrAndCharg(dto.getLgort(),dto.getMatnr(),dto.getCharg());
    		return ResultGenerator.success(logSapStock);
		} catch (Exception e) {
			log.error("同步SAP库存错误",e);
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
    }
    
    @ApiOperation(value = "实时对账库存")
    @PostMapping("/warehouseStatistics")
    public Result warehouseStatistics(@RequestBody WarehouseStatisticsDto dto) {
    	List list = logSapStockService.realTimeReconciliationOfInventory(dto);
    	return ResultGenerator.success(list);
    }
    
    @ApiOperation(value = "实时对账库存")
    @PostMapping("/getWarehouseStatisticsParams")
    public Result getWarehouseStatisticsParams() {
    	JSONObject params = new JSONObject();
    	params.put("lgorts", logSapStockService.realTimeReconciliationOfInventoryLgorts());
    	params.put("chargs", logSapStockService.realTimeReconciliationOfInventoryChargs());
    	return ResultGenerator.success(params);
    }
    
    
    @ApiOperation(value = "同步Sap库存")
    @GetMapping("/synSapStock")
    public Result synSapStock() {
    	try {
    		List<WarehouseLocation> warehouseLocations = warehouseLocationService.findAllPWarehouse();
    		
    		if(warehouseLocations.size()==0) {
    			sAPOutputServiceService.getWarehouseLocationFromSap();
    			warehouseLocations = warehouseLocationService.findAllPWarehouse();
    		}
    		
            for (WarehouseLocation warehouseLocation : warehouseLocations) {
	    		//同步sapStock
	    		sAPOutputServiceService.getSapStock(warehouseLocation.getLgort(),null);
            }
    		
		} catch (Exception e) {
			log.error("同步SAP库存错误",e);
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
    	return ResultGenerator.success();
    }
    
    
    
    @ApiOperation(value = "导出实时对账明细记录列表")
    @GetMapping("/export")
    public void export(HttpServletRequest request, HttpServletResponse response) {
        try {
        	
        	String[] chargs = request.getParameterValues("chargs");
        	String[] lgorts = request.getParameterValues("lgorts");
        	String matnr = request.getParameter("matnr");
        	WarehouseStatisticsDto dto = new WarehouseStatisticsDto();
        	dto.setMatnr(matnr);
        	if(chargs!=null)
        	dto.setChargs(Arrays.asList(chargs));
        	if(lgorts!=null)
        	dto.setLgorts(Arrays.asList(lgorts));
        	
        	List list = logSapStockService.realTimeReconciliationOfInventory(dto);
        	String sheetName = DateUtil.formatDate(new Date(),DateUtil.longFormats);
        	
        	logSapStockService.export(response, sheetName, "实时对账库存", list);
        } catch (IOException e) {
            throw new RuntimeException("导出报工列表失败，错误信息：" + e.getMessage());
        }
    }
    
    

    public LogSapStockDto toLazyDto(LogSapStock entity) {
        return modelMapper.map(entity, LogSapStockDto.class);
    }

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

    public LogSapStock fromDto(LogSapStockDto dto) {
        return modelMapper.map(dto, LogSapStock.class);
    }
}
