package com.sw.mes.sap.impl;

import com.sw.mes.core.dto.SapGrCDto;
import com.sw.mes.fb.turnstore.entity.FbTurnstoreTrayItem;
import com.sw.mes.sap.SapServer;
import com.sw.mes.third.entity.SapGi;
import com.sw.mes.third.entity.SapGr;
import com.sw.mes.third.service.SapGiService;
import com.sw.mes.third.service.SapGrService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Transactional
@Service
public class SapServerImpl implements SapServer {
    @Autowired
    private SapGrService sapGrService;
    @Autowired
    private SapGiService sapGiService;

    /**
     * 发送GR(冲销)
     *
     * @param turnstoreTrayItemList
     */
    @Override
    @Async
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = RuntimeException.class)
    public void sendGrc(List<FbTurnstoreTrayItem> turnstoreTrayItemList) {
        try {
            for (FbTurnstoreTrayItem turnstoreTrayItem : turnstoreTrayItemList) {
                // 查询最近一次的gi，将其关联的gr上报gi的状态恢复成未上报的状态
                SapGi sapGi = sapGiService.findBySectionno(turnstoreTrayItem.getSectionNo());
                // 查询最近的一次的gr，用来上报冲销gr
                SapGr sapGrc = sapGrService.findBySectionno(turnstoreTrayItem.getSectionNo());
                if (sapGi != null) {
                    // 将最近一次上报的gi，将其关联的gr，改为未报gi的gr
                    SapGr sapGr = sapGrService.get(sapGi.getGrId());
                    sapGr.setStatus(0);
                    sapGrService.saveOrUpdate(sapGr);

                    //将最近的一次的gr，改为已报gi的gr
                    sapGrc.setStatus(1);
                    sapGrService.saveOrUpdate(sapGrc);

                    //创建冲销状态的gr（最近的一次的gr），用来冲销gr
                    SapGr sapGrNew = new SapGr();
                    BeanUtils.copyProperties(sapGrc, sapGrNew, "id");
                    sapGrNew.setBty("2");
                    sapGrService.saveOrUpdate(sapGrNew);

                    //创建冲销状态的gi（最近一次的gi），用来冲销gi
                    SapGi sapGiNew = new SapGi();
                    BeanUtils.copyProperties(sapGi, sapGiNew, "id");
                    sapGiNew.setBty("2");
                    sapGiService.saveOrUpdate(sapGiNew);
                }
            }
        } catch (Exception e) {
            log.error("sapGr发生错误", e);
        }
    }

    /**
     * 发送GR
     *
     * @param turnstoreTrayItemList
     */
    @Override
    @Async
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = RuntimeException.class)
    public void sendGr(List<FbTurnstoreTrayItem> turnstoreTrayItemList) {
        try {
            List<SapGrCDto> sapGrCdtos = new ArrayList<>();
            List<SapGi> sapGis = new ArrayList<>();
            for (FbTurnstoreTrayItem turnstoreTrayItem : turnstoreTrayItemList) {
                SapGrCDto sapGrCdto = new SapGrCDto();
                sapGrCdto.setCheckName(turnstoreTrayItem.getCheckoutName());
                sapGrCdto.setMaterialNumber(turnstoreTrayItem.getMaterialNumber());
                sapGrCdto.setSectionNo(turnstoreTrayItem.getSectionNo());
                sapGrCdto.setWeight(turnstoreTrayItem.getTheoryWeightFb());
                sapGrCdto.setOrderNo(turnstoreTrayItem.getOrderNo());
                sapGrCdtos.add(sapGrCdto);
                SapGr sapGrYb = sapGrService.getSapGrsAndNotGi(turnstoreTrayItem.getSectionNo(), 0);
                if (sapGrYb != null) {
                    if (sapGis.stream().noneMatch(sapGi -> sapGi.getSectionno() != null && sapGi.getSectionno().equals(sapGrYb.getSectionno()))) {
                        setSapGiInfo(sapGis, turnstoreTrayItem, sapGrYb, 0);
                    }
                } else {
                    // 上报复检GI
                    SapGr sapGrFbFJ = sapGrService.getSapGrsAndNotGi(turnstoreTrayItem.getSectionNo(), 1);
                    if (sapGrFbFJ != null) {
                        if (sapGis.stream().noneMatch(sapGi -> sapGi.getSectionno() != null && sapGi.getSectionno().equals(sapGrFbFJ.getSectionno()))) {
                            setSapGiInfo(sapGis, turnstoreTrayItem, sapGrFbFJ, 1);
                        }
                    }
                }
            }
            if (sapGis.size() > 0) {
                sapGiService.saveBatch(sapGis);
            }
            sapGrService.addFbGr(sapGrCdtos);
        } catch (Exception e) {
            log.error("sapGr发生错误", e);
        }
    }

    //1、方棒GI  工厂1031、批次固定9999999999，库存地点Q026;
//2、原料GI  工厂1031、批次固定9999999999，库存地点Q023;
//2、圆棒GR  工厂1031、批次固定9999999999，库存地点Q026;
    private void setSapGiInfo(List<SapGi> sapGis, FbTurnstoreTrayItem turnstoreTrayItem, SapGr sapGr, Integer consumeType) {
        int count = sapGrService.updateStatus(sapGr.getId());
        if (count > 0) {
            SapGi sapGi = new SapGi();
            sapGi.setAufnr(turnstoreTrayItem.getOrderNo());
            sapGi.setMenge(sapGr.getMenge());
            sapGi.setMatnrmat(sapGr.getMatnr());
            sapGi.setMatnr(turnstoreTrayItem.getMaterialNumber());
            sapGi.setSectionno(sapGr.getSectionno());
            sapGi.setLgort("Q026");
            sapGi.setCharg("9999999999");
            sapGi.setWerks("1031");
            sapGi.setGrId(sapGr.getId());
            sapGi.setType(1);
            sapGi.setConsumeType(consumeType);
            sapGi.setBty("1");
            sapGis.add(sapGi);
        }
    }
}
