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

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.utils.DateUtil;
import com.sw.mes.sap.dao.ReportSapMblnrQueryDao;
import com.sw.mes.sap.dto.MblnrDataParam;
import com.sw.mes.sap.entity.ReportSapGoodsmvt;
import com.sw.mes.sap.entity.ReportSapMblnrQuery;
import com.sw.mes.sap.service.ReportSapGoodsmvtService;
import com.sw.mes.sap.service.ReportSapMblnrQueryService;
import com.sw.mes.sap.service.SAPOutputServiceService;
import com.sw.mes.utils.CodeUtil;
import com.sw.mes.utils.StringUtils;
import com.xxl.job.core.handler.annotation.XxlJob;

import lombok.extern.slf4j.Slf4j;


/**
 * 物料凭证查询接口Service业务层处理
 * 
 * @author liru
 * @date 2024-04-15
 */
@Slf4j
@Service
@Transactional
public class ReportSapMblnrQueryServiceImpl extends BaseServiceImpl<ReportSapMblnrQuery> implements ReportSapMblnrQueryService
{
	@Autowired
	SAPOutputServiceService sAPOutputServiceService;
	
	@Autowired
	ReportSapGoodsmvtService reportSapGoodsmvtService;
	
    private ReportSapMblnrQueryDao dao;

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

	@Override
	public ReportSapMblnrQuery getByMblnr(String mblnr) {
		List<ReportSapMblnrQuery> list =  dao.findByMblnr(mblnr);
		if(list.size()>0) {
			return list.get(0);
		}
		return null;
	}
	
	
	@XxlJob("synPreDateSapMblnr")
    @Override
    public void synPreDateSapMblnr() {
    	log.info("==================开始同步前一天SAP物料凭证数据======================");
    	
    	Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, - 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
    	
    	MblnrDataParam param = new MblnrDataParam();
    	param.setWerkss(Arrays.asList("5041"));
    	param.setBudatStartDate(c.getTime());
    	c.add(Calendar.DATE, 1);
    	param.setBudatEndDate(c.getTime());
    	
    	sAPOutputServiceService.getMblnrDataFromSap(param);
    	
    	log.info("==================本次同步前一天SAP物料凭证数据======================");
    }

	@Override
	public void recoveryGoodsmvt(Long id) throws ParseException {
		ReportSapMblnrQuery mblnr = get(id);
		
		
		Date _sap_budat_date = mblnr.getBudatMkpf();
		String _sap_budat_time_str = mblnr.getCputmMkpf();
		Date _sap_budat_time = DateUtil.toDate(_sap_budat_time_str, "HH:mm:ss");
		
		Calendar cd = Calendar.getInstance();
		cd.setTime(_sap_budat_date);
		cd.set(Calendar.HOUR_OF_DAY, _sap_budat_time.getHours());
		cd.set(Calendar.MINUTE, _sap_budat_time.getMinutes());
		cd.set(Calendar.SECOND, _sap_budat_time.getSeconds());
		Date _sap_budat = cd.getTime();
		
		//已存在相同记录
		ReportSapGoodsmvt reportSapGoodsmvt = reportSapGoodsmvtService.getByMblnr(mblnr.getMblnr());
		if(reportSapGoodsmvt != null) {
			return;
		}
		
		//检查数据相同未上报记录
		List<ReportSapGoodsmvt> notSendList = reportSapGoodsmvtService.findByBwartAndLgortAndMatnrAndChargAndMengeAndStatus(mblnr.getBwart(),mblnr.getLgort(),mblnr.getMatnr(),mblnr.getCharg(),mblnr.getErfmg().toString(),false);
		if(notSendList.size()>0) {
			for (ReportSapGoodsmvt notSend : notSendList) {
				//相同数据未上报记录中存在于当前记录过账日期相差5秒内数据,判定已上报,实际记录未上报
				if(Math.abs(notSend.getBudat().getTime() - _sap_budat.getTime()) < 5000) {
					notSend.setMblnr(mblnr.getMblnr());
					notSend.setStatus(true);
					saveOrUpdate(mblnr);
					return;
				}
			}
		}
		
		// 创建新报工数据
		ReportSapGoodsmvt extisMvt = null;
		List<ReportSapGoodsmvt> sendList = reportSapGoodsmvtService.findByBwartAndLgortAndMatnrAndChargAndMengeAndStatus(mblnr.getBwart(),mblnr.getLgort(),mblnr.getMatnr(),mblnr.getCharg(),mblnr.getErfmg().toString(),true);
		for (ReportSapGoodsmvt mvt : sendList) {
			if(StringUtils.isNotBlank(mvt.getProcName())) {
				extisMvt = mvt;
			}
		}
		if(extisMvt==null) {
			sendList = reportSapGoodsmvtService.findByBwartAndLgortAndMatnrAndChargAndMengeAndStatus(mblnr.getBwart(),mblnr.getLgort(),mblnr.getMatnr(),mblnr.getCharg(),mblnr.getErfmg().toString(),false);
			for (ReportSapGoodsmvt mvt : sendList) {
				if(StringUtils.isNotBlank(mvt.getProcName())) {
					extisMvt = mvt;
				}
			}
		}
		
		
		ReportSapGoodsmvt target = new ReportSapGoodsmvt();
		target.setZuuid(CodeUtil.getUniqueCode());
		target.setBudat(_sap_budat);
		
		//bldat
		Date _sap_bldat_date = mblnr.getBldat();
		cd.setTime(_sap_bldat_date);
		cd.set(Calendar.HOUR_OF_DAY, _sap_budat_time.getHours());
		cd.set(Calendar.MINUTE, _sap_budat_time.getMinutes());
		cd.set(Calendar.SECOND, _sap_budat_time.getSeconds());
		Date _sap_bldat = cd.getTime();
		target.setBldat(_sap_bldat);
		target.setErnam(mblnr.getUsnamMkpf());
		target.setBwart(mblnr.getBwart());
		target.setKostl(mblnr.getKostl());
		target.setAufnr(mblnr.getAufnr());
		target.setVbeln(mblnr.getVbelnIm());
		target.setRsnum(mblnr.getRsnum());
		target.setRspos(mblnr.getRspos()==0?null:mblnr.getRspos()+"");
		target.setWerks(mblnr.getWerks());
		target.setLgort(mblnr.getLgort());
		target.setMatnr(mblnr.getMatnr());
		target.setCharg(mblnr.getCharg());
		
		BigDecimal menge = mblnr.getMenge();
		menge = menge.setScale(3, RoundingMode.HALF_UP);
		if(mblnr.getBwart().equals("102") || mblnr.getBwart().equals("262") || mblnr.getBwart().equals("312") || mblnr.getBwart().equals("532") || mblnr.getBwart().equals("202")) {
			target.setMenge("-"+menge.toString());
		}else {
			target.setMenge(menge.toString());
		}
		
		target.setMeins(mblnr.getMeins());
		target.setUmwrk(mblnr.getUmwrk());
		target.setUmlgo(mblnr.getUmlgo());
		target.setUmcha(mblnr.getCharg());
		target.setSgtxt(mblnr.getSgtxt());
		target.setStatus(true);
		if(extisMvt!=null) {
			target.setProcName(extisMvt.getProcName());
			target.setDeviceNo(extisMvt.getDeviceNo());
		}
		target.setCreateDate(new Date());
		target.setSendType("RECOVERY");
		target.setRemark("RECOVERY数据");
		reportSapGoodsmvtService.saveOrUpdate(target);
		
		//同步完成
		mblnr.setSyned(true);
		saveOrUpdate(mblnr);
	}

	@Override
	public void contrastGoodsmvt() {
		//初始化所有记录默认同步
		List<ReportSapMblnrQuery> synedFalses = dao.findBySyned(false);
		for (ReportSapMblnrQuery reportSapMblnrQuery : synedFalses) {
			reportSapMblnrQuery.setSyned(true);
			saveOrUpdate(reportSapMblnrQuery);
		}
		
		//比对后设置非一直数据
		List<ReportSapMblnrQuery> mblnrs = dao.contrastGoodsmvt();
		for (ReportSapMblnrQuery reportSapMblnrQuery : mblnrs) {
			reportSapMblnrQuery.setSyned(false);
		}
		saveAll(mblnrs);
	}
}
