package com.xisc.pm.app.service.strategy.pdevent;

import com.xisc.pm.api.dto.PmPdEventResDTO;
import com.xisc.pm.app.service.strategy.PdEventStrategyFactory;
import com.xisc.pm.domain.entity.PmContMscTech;
import com.xisc.pm.domain.entity.PmPdRec;
import com.xisc.pm.domain.entity.PmProCont;
import com.xisc.pm.domain.entity.PmProContProdTtr;
import com.xisc.pm.infra.constant.PmPlateConstants.EventParam;
import com.xisc.pm.infra.enums.PdEventType;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * 组板合同超投事件，策略处理类
 * @author jun.zeng
 *
 */
@Component
public class PdEventStrategyHp03 implements PdEventStrategy {
    
    @Override
    public void afterPropertiesSet() throws Exception {
        PdEventStrategyFactory.register(PdEventType.HP03 , this);
    }

    /**
     * 修改生产合同主表的组板工序超投件数PD_OVER_DEVO_QTY，组板工序超投量PD_OVER_DEVO_WT，组板形成总件数PD_TOT_QTY：
     * 组板工序超投件数 = 组板工序超投件数 + 件数；
     * 组板工序超投量 = 组板工序超投件数 * 目标单重；
     * 组板形成总件数 = 原组板形成总件数 + 件数；
     * 其中目标单重根据合同号从生产合同产品属性表获取订货单件目标重量ORDER_UNIT_AIM_WT;
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PmPdEventResDTO handleEvent(PmPdRec pmPdRec, PmContMscTech pmContMscTech, PmProCont pmProCont , PmProContProdTtr pmProContProdTtr) {
        // 组板工序超投件数
        BigDecimal pdOverDevoQty = pmProCont.getPdOverDevoQty() == null ? BigDecimal.ZERO : pmProCont.getPdOverDevoQty();
        // 组板形成总件数PD_TOT_QTY
        BigDecimal pdTotQty = pmProCont.getPdTotQty() == null ? BigDecimal.ZERO : pmProCont.getPdTotQty();
        
        PmProCont updatePmProCont = new PmProCont();
        updatePmProCont.setObjectVersionNumber(pmProCont.getObjectVersionNumber());
        updatePmProCont.setProContId(pmProCont.getProContId());
        updatePmProCont.setPdOverDevoQty(pdOverDevoQty.add(pmPdRec.getQty()));
//        updatePmProCont.setPdTotQty(pdTotQty.add(pmPdRec.getQty()));
        
        BigDecimal ordderUnitAimWt = BigDecimal.ZERO;
        if(pmProContProdTtr != null && pmProContProdTtr.getOrderUnitAimWt() != null) {
            ordderUnitAimWt = pmProContProdTtr.getOrderUnitAimWt();
        }
        // 组板工序超投量 = 组板工序超投件数 * 目标单重；
        updatePmProCont.setPdOverDevoWt(updatePmProCont.getPdOverDevoQty().multiply(ordderUnitAimWt));
        if(pmPdRec.getParams() != null && pmPdRec.getParams().containsKey(EventParam.PD_OVER_DEVO_CAUSE)) {
            updatePmProCont.setPdOverDevoCause(pmPdRec.getParams().getOrDefault(EventParam.PD_OVER_DEVO_CAUSE, "").toString());
        }
        defaultHandle(pmPdRec, pmContMscTech, pmProCont, updatePmProCont, pmProContProdTtr);
        return new PmPdEventResDTO(null, updatePmProCont, null);
    }

}
