package cn.wisenergy.service.util;

import cn.wisenergy.common.utils.DateUtil;
import org.apache.commons.lang.RandomStringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 生成防伪二维码产品编号工具类
 *
 * @author 86187
 */
public class CodeUtils {

    private static final String VALUE = "nishidamori";

    public static String createProductNo(String batchNumber, String batchNo, String produceTime) throws ParseException {
        //产品编号 =固定值+生产时间+生产批次+编号+随机数+校验规则
        String random = getRandom();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date date = format.parse(produceTime);
        String time = format.format(date);
        String ruleNumber = getVerifyNumber(batchNumber, batchNo, time, random);
        return VALUE + time + batchNumber + batchNo + random + ruleNumber;
    }

    /**
     * 获取字符串中的数字
     *
     * @param str 字符串
     * @return 数字
     */
    private static String getNumber(String str) {
        StringBuilder number = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            if (Character.isDigit(str.charAt(i))) {
                number.append(i);
            }
        }
        return number.toString();
    }

    /**
     * 获取校验规则位
     *
     * @param batchNumber 批次号
     * @param batchNo     编号
     * @param produceTime 生成时间
     * @param random      随机数
     * @return 校验规则位
     */
    private static String getVerifyNumber(String batchNumber, String batchNo, String produceTime, String random) {
        //获取随机字符串中的数字
        String number = getNumber(random);
        String str = batchNumber + batchNo + produceTime + number;
        char[] ar = str.toCharArray();
        int value = 0;
        for (char c : ar) {
            value = value + Integer.parseInt(String.valueOf(c));
        }
        int ss = value % 9;
        return String.valueOf(ss);
    }

    /**
     * 获取八位随机字符串
     *
     * @return 八位随机字符串
     */
    private static String getRandom() {
        return RandomStringUtils.random(8, "abcdefghijklmnopqrstuvwxyz1234567890");
    }


    public static void main(String[] args) {
        System.out.println(45 % 9);
    }

}
