package com.sw.mes.yb.plan.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.transaction.Transactional;
import javax.xml.namespace.QName;

import com.sw.mes.core.utils.WbServiceUtils;
import com.sw.mes.third.entity.Teco;
import com.sw.mes.third.entity.WebServiceApiName;
import com.sw.mes.third.entity.WebServiceUri;
import com.sw.mes.third.service.SendWebService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.yb.plan.dao.FbProductionOrderDao;
import com.sw.mes.yb.plan.entity.FbProductionOrder;
import com.sw.mes.yb.plan.service.FbProductionOrderService;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Service
@Slf4j
@Transactional
public class FbProductionOrderServiceImpl extends BaseServiceImpl<FbProductionOrder> implements FbProductionOrderService {
    @Autowired
    private SendWebService sendWebService;

    FbProductionOrderDao dao;
    @Autowired
    public void setDao(FbProductionOrderDao dao) {
        super.setBaseDao(dao);
        this.dao=dao;
    }

    @Override
    public void close(FbProductionOrder sapProductionOrder) {
        dao.save(sapProductionOrder);
        //向SAP发送订单关闭信息
        try {
            List<Teco> list = new ArrayList<>();
            Teco teco = new Teco();
            teco.setZMESID(UUID.randomUUID().toString());
            teco.setWERKS("1011");
            teco.setSTATUS("1");
            teco.setCOMMENT("");
            teco.setAUART(sapProductionOrder.getAuart());
            teco.setAUFNR(sapProductionOrder.getAufnr());
            teco.setMATNR(sapProductionOrder.getMatnr());
            teco.setISSUEDATE(WbServiceUtils.getSapDate(new Date()));//日期 yyyymmdd
            teco.setISSUETIME(WbServiceUtils.getSapTime(new Date()));//时间 HHmmss
            list.add(teco);
            Map map = sendWebService.mesToSap(list, WebServiceUri.WSDL_URL, WebServiceApiName.TECO, 4000);
            String sapResult = map.get(new QName("ZTYPE")).toString();
            if (!sapResult.equals("S")) {
                String sapError = map.get(new QName("ZMESSAGE")).toString();
                throw new RuntimeException("向SAP发送订单关闭信息异常:" + sapError);
            }
        } catch (Exception e) {
            log.error("向SAP发送订单关闭信息异常:" + e.getMessage());
            throw new RuntimeException("向SAP发送订单关闭信息异常:" + e.getMessage());
        }
    }

    @Override
    public FbProductionOrder findByAufnr(String code) {
    	List<FbProductionOrder> list = dao.findByAufnr(code);
    	if(list.size()>0) {
    		return list.get(0);
    	}
        return null;
    }
}
