package cn.estsh.i3plus.core.apiservice.util;

import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.platform.bean.SysBarcodeRule;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description : 字符串解析
 * @Reference :
 * @Author : yunhao
 * @CreateDate : 2019-03-12 14:41
 * @Modify:
 **/
public class BarcodeParseUtil {

    /**
     * 按指定规则解析条码
     * @param barcodeRule
     * @param barcode
     * @return
     */
    public static Map<String,String> parse(SysBarcodeRule barcodeRule,String barcode){
        // 数据有效性校验
        if(barcodeRule == null || barcode == null){
            return null;
        }else if(barcodeRule.getBarcodeRule() == null || barcodeRule.getBarcodeSeparator() == null){
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("条码规则不完善！")
                    .build();
        }

        //特殊分隔符处理
        barcodeRule.setBarcodeSeparator(barcodeRule.getBarcodeSeparator().replaceAll("\\\\","\\\\\\\\"));
        barcodeRule.setBarcodeSeparator(barcodeRule.getBarcodeSeparator().replaceAll("\\|","\\\\|"));
        barcodeRule.setBarcodeSeparator(barcodeRule.getBarcodeSeparator().replaceAll("\\.","\\\\."));

        // 分隔条码信息
        String[] barcodeKey = barcodeRule.getBarcodeRule().split(barcodeRule.getBarcodeSeparator());
        String[] barcodeValue = barcode.split(barcodeRule.getBarcodeSeparator());

        if(barcodeKey.length != barcodeValue.length){
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("条码与规则不匹配！")
                    .build();
        }

        // 匹配条码数据
        HashMap<String,String> barcodeMap = new HashMap<>();
        for (int i = 0; i < barcodeKey.length; i++) {
            barcodeMap.put(barcodeKey[i],barcodeValue[i]);
        }
        return barcodeMap;
    }

    public static void main(String[] args) {
        SysBarcodeRule barcodeRule = new SysBarcodeRule();
        barcodeRule.setName("测试条码规则");
        barcodeRule.setBarcodeRuleCode("Barcode");
        barcodeRule.setBarcodeRule("SN\\ORGANIZE_CODE\\PART_NO\\QTY\\UNIT");
        barcodeRule.setBarcodeSeparator("\\");
        barcodeRule.setBarcodeRuleDescription("描述");

        Map barcode= parse(barcodeRule,"99\\99\\99\\99\\99");

        System.out.println(barcode);
    }

}
