/**
 * @Title: SendYieldAndHourToSapServiceImpl.java
 * @Package com.sw.mes.webservice.service.impl
 * @Description: TODO(用一句话描述该文件做什么)
 * @author 中环 keily
 * @date 2022年2月28日 下午1:45:18
 * @version V1.0
 */

package com.sw.mes.webservice.service.impl;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.xml.namespace.QName;

import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.third.config.CallWebServiceConfig;
import com.sw.mes.third.entity.SoapInDto;
import com.sw.mes.third.enums.SapStaticEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.sw.mes.webservice.dao.SapRequestGrLogDao;
import com.sw.mes.webservice.dao.SendSapWarehousingStatisticsInfoYbDao;
import com.sw.mes.webservice.entity.SapRequestGrLog;
import com.sw.mes.webservice.entity.SendSapWarehousingStatisticsInfoYb;
import com.sw.mes.webservice.service.SendGrToSapService;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: SendYieldAndHourToSapServiceImpl
 * @Description: 调用sap接口，传送GR(圆棒入库量)数据
 * @author 中环 keily
 * @date 2022年2月28日 下午1:45:18
 *
 */
@Service
@Transactional
@Slf4j
public class SendGrToSapServiceImpl implements SendGrToSapService {

	private static final String SUCCESS = "1"; // 成功
	private static final String FAILURE = "0"; // 失败

	@Autowired
	private SapRequestGrLogDao sapRequestGrLogDao; // 请求日志记录dao

	@Autowired
	private SendSapWarehousingStatisticsInfoYbDao sendSapWarehousingStatisticsInfoYbDao; //

	@Autowired
	private DictionaryItemService dictionaryItemService;

	@Override
	public Map mesToSap(List listInfo, Integer timeOut, List<SendSapWarehousingStatisticsInfoYb> sendRecordlist)
			throws Exception {
		log.debug("请求信息:" + JSON.toJSONString(listInfo));
		Map<String, String> sapConfMap = querySapConfigInfo();
		if(null == sapConfMap) {
			throw new RuntimeException("sapConfigInfo字典未配置");
		}
		String bskey = UUID.randomUUID().toString();
        String zData = JSON.toJSON(listInfo).toString();
        SoapInDto soapInDto = new SoapInDto();
        soapInDto.setSYSID(SapStaticEnum.SapFactoryId.六期工厂ID.getValue() + "MES"); // 1031MES
        soapInDto.setBSKEY(bskey);
        soapInDto.setIFYWID(sapConfMap.get("grInterfaceName"));
        soapInDto.setZDATA(zData);
        try {
        	Map map = CallWebServiceConfig.sendWebService(sapConfMap.get("url"),
					sapConfMap.get("namespaceURI"),sapConfMap.get("localPart"),
					sapConfMap.get("username"),sapConfMap.get("password"),
					soapInDto,timeOut);
            String sapResult =  map.get(new QName( "ZTYPE")).toString();
            SapRequestGrLog entityErro = new SapRequestGrLog();
            entityErro.setId(null);
			entityErro.setRequestBody(JSON.toJSONString(soapInDto));
            entityErro.setResponseBody(JSON.toJSON(map).toString());
            entityErro.setReqTime(new Date());
            entityErro.setStatus(FAILURE);

            List<SendSapWarehousingStatisticsInfoYb> saveGrRecList = null;
            if(sapResult.equals("S")){
                entityErro.setStatus(SUCCESS);
                saveGrRecList = sendRecordlist.stream().map(
                		grData -> {grData.setStatus("1");
                		return grData;
                }).collect(Collectors.toList());

            }
            else {
            	//失败
            	saveGrRecList = sendRecordlist.stream().map(
                		grData -> {grData.setStatus("0");
                		return grData;
                }).collect(Collectors.toList());
            }

            //保存发送记录数据
            if(null != saveGrRecList && 0 < saveGrRecList.size() ) {
            	sendSapWarehousingStatisticsInfoYbDao.saveAll(saveGrRecList);
            }
            sapRequestGrLogDao.save(entityErro);

            return map;
        }  catch (Exception e) {
        	e.printStackTrace();
            SapRequestGrLog entityErro = new SapRequestGrLog();
            entityErro.setId(null);
            entityErro.setRequestBody(JSON.toJSON(soapInDto).toString());
            entityErro.setResponseBody(e.getMessage());
            entityErro.setReqTime(new Date());
            entityErro.setStatus(FAILURE);
            sapRequestGrLogDao.save(entityErro);
            throw new Exception(e.getMessage());
        }
	}


	@Override
	public Map mesToSap(List listInfo, Integer timeOut) throws Exception {
		log.debug("请求信息:" + JSON.toJSONString(listInfo));
		Map<String, String> sapConfMap = querySapConfigInfo();
		if(null == sapConfMap) {
			throw new RuntimeException("sapConfigInfo字典未配置");
		}
		String bskey = UUID.randomUUID().toString();
        String zData = JSON.toJSON(listInfo).toString();
        SoapInDto soapInDto = new SoapInDto();
        soapInDto.setSYSID(SapStaticEnum.SapFactoryId.六期工厂ID.getValue() + "MES"); // 1031MES
        soapInDto.setBSKEY(bskey);
        soapInDto.setIFYWID(sapConfMap.get("grInterfaceName"));
        soapInDto.setZDATA(zData);
        try {
        	Map map =CallWebServiceConfig.sendWebService(sapConfMap.get("url"),
					sapConfMap.get("namespaceURI"),sapConfMap.get("localPart"),
					sapConfMap.get("username"),sapConfMap.get("password"),
					soapInDto,timeOut);
            String sapResult =  map.get(new QName( "ZTYPE")).toString();
            SapRequestGrLog entityErro = new SapRequestGrLog();
            entityErro.setId(null);
			entityErro.setRequestBody(JSON.toJSONString(soapInDto));
            entityErro.setResponseBody(JSON.toJSON(map).toString());
            entityErro.setReqTime(new Date());
            entityErro.setStatus(FAILURE);

            List<SendSapWarehousingStatisticsInfoYb> saveGrRecList = null;
            if(sapResult.equals("S")){
                entityErro.setStatus(SUCCESS);
            }

            sapRequestGrLogDao.save(entityErro);

            return map;
        }  catch (Exception e) {
        	e.printStackTrace();
            SapRequestGrLog entityErro = new SapRequestGrLog();
            entityErro.setId(null);
            entityErro.setRequestBody(JSON.toJSON(soapInDto).toString());
            entityErro.setResponseBody(e.getMessage());
            entityErro.setReqTime(new Date());
            entityErro.setStatus(FAILURE);
            sapRequestGrLogDao.save(entityErro);
            throw new Exception(e.getMessage());
        }

	}



	/**
	 * @Title: querySapConfigInfo
	 * @Description: 获取sap配置信息
	 * @param @return    设定文件
	 * @return Map<String,String>    返回类型
	 * @throws
	 */
	private Map<String, String> querySapConfigInfo(){
		List<DictionaryItem> itemList = dictionaryItemService.findItemByThemeValue("sapConfigInfo", true);
		if(0 == itemList.size()) {
			return null;
		}
		Map<String, String> map = new LinkedHashMap<String, String>(10);
		for(DictionaryItem item : itemList) {
			map.put(item.getName(), item.getValue());
		}

		return map;
	}


}
