package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.numberrule;

import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesCustomerPartService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesCustomerSnTransformService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.util.MesPcnException;
import cn.estsh.i3plus.mes.pcn.api.iservice.busi.INumberRulePackAttributeStrategyService;
import cn.estsh.i3plus.pojo.mes.bean.MesCustomerPart;
import cn.estsh.i3plus.pojo.mes.model.GenSerialNoModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * @Description : 非排序客户条码打印
 * @Reference :
 * @Author : junsheng.li
 * @CreateDate 2024/11/16 10:56
 * @Modify:
 **/
@Component
public class MesNoSortCustSnNumberRuleStrategyService implements INumberRulePackAttributeStrategyService {

    @Autowired
    private IMesCustomerPartService customerPartService;

    @Autowired
    private IMesCustomerSnTransformService customerSnTransformService;

    @Override
    public GenSerialNoModel execute(GenSerialNoModel genSerialNoModel) {
        Map<String, Object> dataMap = genSerialNoModel.getDataMap();
        MesCustomerPart customerPart = (!CollectionUtils.isEmpty(dataMap) && dataMap.containsKey(MesCustomerPart.class.getSimpleName())) ?
                (MesCustomerPart)dataMap.get(MesCustomerPart.class.getSimpleName()) : customerPartService.getMesCustomerPart(genSerialNoModel.getOrganizeCode(), genSerialNoModel.getPartNo());
        if (null != customerPart) {
            genSerialNoModel.setCustPartNo(customerPart.getCustPartNo());
        }else {
            MesPcnException.throwMesBusiException("请检查客户零件信息,零件[%s]客户零件关系未维护", genSerialNoModel.getPartNo());
        }
        Calendar custCalendar = Calendar.getInstance();
        custCalendar.setTime(new Date());
        String partNo = customerPart.getCustPartNo();
        String prefix = partNo.substring(0, partNo.length() - 4);
        String partNo4 = partNo.substring(partNo.length() - 4).toUpperCase();
        genSerialNoModel.setPartNo(prefix+partNo4);
        String year = custCalendar.get(Calendar.YEAR)+"";
        genSerialNoModel.setYear(year.substring(2));
        genSerialNoModel.setDay(String.format("%03d",custCalendar.get(Calendar.DAY_OF_YEAR)));
        return genSerialNoModel;
    }

    @Override
    public String transform(GenSerialNoModel genSerialNoModel, String serialNo) {
        if (StringUtils.isEmpty(serialNo)) return serialNo;
        return customerSnTransformService.transformBarCodeGm(serialNo);
    }

}
