package com.sw.mes.sap.controller;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.ServletRequest;
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.excel.util.DateUtils;
import com.alibaba.fastjson.JSONArray;
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.LogSapMesInteractiveDto;
import com.sw.mes.sap.entity.LogSapMesInteractive;
import com.sw.mes.sap.entity.ReportSapGoodsmvt;
import com.sw.mes.sap.service.LogSapMesInteractiveService;
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 springfox.documentation.annotations.ApiIgnore;

/**
 * 晶科SAP下发生产工单通信记录Controller
 * 
 * @author liru
 * @date 2023-12-29
 */
@RestController
@Jinko(value="晶科SAP下发生产工单通信记录Controller",author = "liru")
@RequestMapping("/mes/interactive")
public class LogSapMesInteractiveController
{
    @Autowired
    ModelMapper modelMapper;

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

    @ApiOperation(value = "分页查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<LogSapMesInteractiveDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
        Specification<LogSapMesInteractive> specification = DynamicSpecifications.bySearchFilter(request, LogSapMesInteractive.class);
        Page<LogSapMesInteractive> page = logSapMesInteractiveService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<LogSapMesInteractiveDto> 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("/revertData")
    public Result revertData(ServletRequest request) {
        Specification<LogSapMesInteractive> specification = DynamicSpecifications.bySearchFilter(request, LogSapMesInteractive.class);
        List<LogSapMesInteractive> LogSapMesInteractives = logSapMesInteractiveService.findByExampleSort(specification, null);
        String currentDate = DateUtil.formatDate(new Date(), DateUtil.longFormat);
        for (LogSapMesInteractive logSapMesInteractive : LogSapMesInteractives) {
        	try {
	        	String returnJson = logSapMesInteractive.getReturnContext();
	        	//1. 验证SAP返回值正确返回
	        	if(returnJson!=null) {
	        		JSONObject returnJSONObject = JSONObject.parseObject(returnJson);
	        		JSONArray ET_RETURNs = returnJSONObject.getJSONArray("ET_RETURN");
	        		
	        		JSONObject ET_RETURN = ET_RETURNs.getJSONObject(0);
	        		
	        		String MSGTY = ET_RETURN.getString("MSGTY");//返回结果
	        		if(MSGTY.equals("S")) {//正确返回
	        			String MBLNR = ET_RETURN.getString("MBLNR");//物料凭证
	        			
	        			//查询上报记录是否存在
	        			ReportSapGoodsmvt mvt = reportSapGoodsmvtService.findByZuuidOrMblnr(MBLNR);
	        			
	        			if(mvt==null) {
	        				mvt = new ReportSapGoodsmvt();
	        				String contextJson = logSapMesInteractive.getContext();
	        				//根据发送内容还原报工记录
	        				initMvt(mvt,contextJson);
	        				
	        				mvt.setMblnr(MBLNR);
	        				mvt.setStatus(true);
	        				mvt.setRemark(currentDate+"还原SAP发送记录");
	        				//保存报工记录
	        				reportSapGoodsmvtService.superSaveOrUpdate(mvt);
	        				
	        				
	        			}
	        		}
	        	}
        	}catch (Exception e) {
        		System.out.println(logSapMesInteractive.getId());
				e.printStackTrace();
			}
		}
        
        
        return ResultGenerator.success();
    }
    

    private void initMvt(ReportSapGoodsmvt mvt, String contextJson) throws ParseException {
		JSONObject returnJSONObject = JSONObject.parseObject(contextJson);
		JSONArray IT_DATA = returnJSONObject.getJSONArray("IT_DATA");
		JSONObject IS_BC_INFO = returnJSONObject.getJSONObject("IS_BC_INFO");
		
		String uuid = IS_BC_INFO.getString("UUID");
		
		JSONObject DATA = IT_DATA.getJSONObject(0);
		
		String BLDAT = DATA.getString("BLDAT");
		String ZUUID = DATA.getString("ZUUID");
		String BUDAT = DATA.getString("BUDAT");
		String ERNAM = DATA.getString("ERNAM");
		
		JSONArray GOODS_ITEMS = DATA.getJSONArray("GOODS_ITEMS");
		JSONObject GOODS_ITEM = GOODS_ITEMS.getJSONObject(0);
		
		String CHARG = GOODS_ITEM.getString("CHARG");
		String BWART = GOODS_ITEM.getString("BWART");
		String POSNR = GOODS_ITEM.getString("POSNR");
		String LGORT = GOODS_ITEM.getString("LGORT");
		String WERKS = GOODS_ITEM.getString("WERKS");
		String EBELP = GOODS_ITEM.getString("EBELP");
		String MENGE = GOODS_ITEM.getString("MENGE");
		String MEINS = GOODS_ITEM.getString("MEINS");
		String AUFNR = GOODS_ITEM.getString("AUFNR");
		String MATNR = GOODS_ITEM.getString("MATNR");
		String EBELN = GOODS_ITEM.getString("EBELN");
		String KOSTL = GOODS_ITEM.getString("KOSTL");
		String RSNUM = GOODS_ITEM.getString("RSNUM");
		String RSPOS = GOODS_ITEM.getString("RSPOS");
		String UMCHA = GOODS_ITEM.getString("UMCHA");
		String UMLGO = GOODS_ITEM.getString("UMLGO");
		String UMWRK = GOODS_ITEM.getString("UMWRK");
		String VBELN = GOODS_ITEM.getString("VBELN");
		String ZFCP_FLAG = GOODS_ITEM.getString("ZFCP_FLAG");
		
		
		mvt.setAufnr(AUFNR);
		mvt.setBldat(DateUtil.toDate(BLDAT, "yyyyMMdd"));
		mvt.setBudat(DateUtil.toDate(BUDAT, "yyyyMMdd"));
		mvt.setBwart(BWART);
		mvt.setCharg(CHARG);
		mvt.setCreateDate(new Date());
		mvt.setEbeln(EBELN);
		mvt.setEbelp(EBELP);
		mvt.setErnam(ERNAM);
		mvt.setKostl(KOSTL);
		mvt.setLgort(LGORT);
		mvt.setMatnr(MATNR);
		mvt.setMeins(MEINS);
		mvt.setMenge(MENGE);
		mvt.setPosnr(POSNR);
		mvt.setRsnum(RSNUM);
		mvt.setRspos(RSPOS);
		mvt.setSendType("REVERT");
		mvt.setUmcha(UMCHA);
		mvt.setUmlgo(UMLGO);
		mvt.setUmwrk(UMWRK);
		mvt.setUuidValue(uuid);
		mvt.setVbeln(VBELN);
		mvt.setWerks(WERKS);
		mvt.setZfcpFlag(ZFCP_FLAG);
		mvt.setZuuid(ZUUID);
	}


	@ApiOperation(value = "获取所有数据")
    @GetMapping("/listAll")
    public Result<List<LogSapMesInteractiveDto>> listAll(ServletRequest request) {
        Specification<LogSapMesInteractive> specification = DynamicSpecifications.bySearchFilter(request, LogSapMesInteractive.class);
        List<LogSapMesInteractive> LogSapMesInteractives = logSapMesInteractiveService.findByExampleSort(specification, null);
        List<LogSapMesInteractiveDto> LogSapMesInteractiveDtos = LogSapMesInteractives.stream()
                .map(LogSapMesInteractive -> toLazyDto(LogSapMesInteractive))
                .collect(Collectors.toList());
        return ResultGenerator.success(LogSapMesInteractiveDtos);
    }

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

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

    @ApiOperation(value = "更新数据")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "LogSapMesInteractive") LogSapMesInteractiveDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        LogSapMesInteractive entity = logSapMesInteractiveService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            LogSapMesInteractive entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            logSapMesInteractiveService.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) {
            logSapMesInteractiveService.delete(id);
        }
        return ResultGenerator.success();
    }

    public LogSapMesInteractiveDto toLazyDto(LogSapMesInteractive entity) {
        return modelMapper.map(entity, LogSapMesInteractiveDto.class);
    }

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

    public LogSapMesInteractive fromDto(LogSapMesInteractiveDto dto) {
        return modelMapper.map(dto, LogSapMesInteractive.class);
    }
}
