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;
import com.xisc.pm.infra.enums.PdEventType;
import io.choerodon.core.exception.CommonException;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @author 纪文桃 wentao.ji01@hand-china.com
 * @date 2024/12/4 18:35
 * @description
 */
@Component
public class PdEventStrategyHp06 implements PdEventStrategy {

    @Override
    public void afterPropertiesSet() throws Exception {
        PdEventStrategyFactory.register(PdEventType.HP06, this);
    }
    @Override
    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());
        // 组板工序超投件数 = 组板工序超投件数 - 件数
        // 若组板工序超投件数<件数，返回消息:合同【grderNo】的超投件数【】小于取消件数【】，不能取消超投
        if (pdOverDevoQty.compareTo(pmPdRec.getQty()) < 0) {
            throw new CommonException("pm.pro_cont_001", pmProCont.getOrderNo(), pdOverDevoQty, pmPdRec.getQty());
        }

        updatePmProCont.setPdOverDevoQty(pdOverDevoQty.subtract(pmPdRec.getQty()));
        // 组板形成总件数
//        updatePmProCont.setPdTotQty(pdTotQty.subtract(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(PmPlateConstants.EventParam.PD_OVER_DEVO_CAUSE)) {
            updatePmProCont.setPdOverDevoCause(pmPdRec.getParams().getOrDefault(PmPlateConstants.EventParam.PD_OVER_DEVO_CAUSE, "").toString());
        }
        defaultHandle(pmPdRec, pmContMscTech, pmProCont, updatePmProCont, pmProContProdTtr);
        return new PmPdEventResDTO(null, updatePmProCont, null);
    }

}
