import JsBarcode from 'jsbarcode';
import { field, input, select, number, value, encode, result } from '../../src/io.js';
export default {
controls: field('编码格式', select('format', [['CODE128', 'CODE128'], ['EAN13', 'EAN-13']])) + field('内容', '<input name="text" value="LSJY2026" maxlength="80" required>') + field('条宽(px)', input('width', 2, 1, 5)) + field('条高(px)', input('height', 100, 30, 500)) + '<label class="check-field"><input type="checkbox" name="display" checked>显示文本</label>',
async run({ form }) {
const text = value(form, 'text'); const format = value(form, 'format');
if (format === 'EAN13' && !/^\d{12,13}$/.test(text)) throw new Error('EAN-13 需输入 12 位数字,或含正确校验位的 13 位数字。');
if (format === 'CODE128' && !/^[\x20-\x7e]{1,80}$/.test(text)) throw new Error('CODE128 支持 1–80 个可打印 ASCII 字符。');
const node = document.createElement('canvas'); let valid = false;
JsBarcode(node, text, { format, width: number(form, 'width'), height: number(form, 'height'), margin: 20, displayValue: form.elements.display.checked, valid: (v) => { valid = v; }, background: '#ffffff', lineColor: '#000000' });
if (!valid) throw new Error('条码内容或校验位无效。');
return [result(await encode(node), 'barcode.png', `${node.width} × ${node.height}`)];
},
};