import bwipjs from "bwip-js";
import JsBarcode from "jsbarcode";
//bwipjs 配置项
export const bwipJsOptions = param => {
    let options = {
        bcid: "code128", // 条形码类型
        text: param, // 条形码内容
        scale: 3, // 缩放比例 3是最好扫描的
        height: 32, // 条形码高度 30 32 36最好扫
        includetext: false
    };
    return options;
};

//SN码
export const codeSN = code => {
    let canvas = document.createElement("canvas");
    bwipjs.toCanvas(canvas, bwipJsOptions(code, "code128"));
    let imageData = canvas.toDataURL("image/png", 1);
    return imageData;
};
//日期生成
export const dateCreate = () => {
    let date = new Date();
    // 获取当前年份
    let year = date.getFullYear();
    // 提取年份的后两位
    let lastTwoDigitsOfYear = year.toString().slice(-2);
    // 获取当前月份（注意：月份是从0开始计数的，所以要加1）
    let month = date.getMonth() + 1;
    let monthClone = (month < 10 ? "0" : "") + month;
    let dateReturn = lastTwoDigitsOfYear + "" + monthClone;
    return dateReturn;
};

//生成69碼(一个物料所有的69码都是相同的)
export const set69Code = barCode => {
    let barCode1 = barCode;
    let barCodeClone = barCode1 ? barCode1.replace(/\s/g, "") : barCode1;
    if (barCodeClone && barCodeClone.length === 13 && barCodeClone !== " ") {
        barCodeClone = Number(barCodeClone);
        if (!isNaN(barCodeClone)) {
            // 创建一个canvas
            let canvas = document.createElement("canvas");
            canvas.getContext("2d");
            // 生成条形码
            JsBarcode(canvas, barCodeClone, {
                format: "EAN13",
                width: 3,
                height: 40,
                displayValue: false
            });
            let imageData = canvas.toDataURL("image/png", 0.5);
            let image = '<img src="' + imageData + '">';

            let str = barCodeClone + "";
            let str1 = str.substring(0, 1);
            let str2 = str.substring(1, 7);
            let str3 = str.substring(7, 14);

            return {
                image,
                str1,
                str2,
                str3,
                imageData
            };
        }
    } else {
        return null;
    }
};
// EAN13（69码）非法校验函数（仅校验有值但格式错的情况）
export const isInvalidEAN13 = ean => {
    // // 空值直接返回false（不校验）
    if (!ean) return false;
    if (ean === " ") return false;
    // 过滤非数字，检查是否为13位
    const cleanEan = ean.toString().replace(/\D/g, "");
    if (cleanEan.length !== 13) return true;

    // 校验码计算
    const digits = cleanEan.split("").map(Number);
    const checkDigit = digits.pop();
    let sum = 0;
    digits.forEach((digit, index) => {
        sum += digit * (index % 2 === 0 ? 1 : 3);
    });
    const calculatedCheckDigit = (10 - (sum % 10)) % 10;

    // 校验码不一致则为非法
    return calculatedCheckDigit !== checkDigit;
};
