const vnReport = require('../../../core/mixins/vn-report.js');
const qrcode = require('qrcode');

module.exports = {
    name: 'item-label',
    mixins: [vnReport],
    async serverPrefetch() {
        this.item = await this.findOneFromDef('item', [this.id, this.warehouseId]);
        this.checkMainEntity(this.item);
        this.tags = await this.fetchItemTags(this.id);
        this.barcode = await this.getBarcodeBase64(this.id);
    },

    computed: {
        labelPage() {
            const labelNumber = this.labelNumber ? this.labelNumber : 1;
            const totalLabels = this.totalLabels ? this.totalLabels : 1;

            return `${labelNumber}/${totalLabels}`;
        }
    },
    methods: {
        fetchItemTags(id) {
            return this.rawSqlFromDef('itemTags', [id]).then(rows => {
                const tags = {};
                rows.forEach(row => tags[row.code] = row.value);

                return tags;
            });
        },
        getBarcodeBase64(id) {
            const data = String(id);

            return qrcode.toDataURL(data, {margin: 0});
        },
        packing() {
            const stems = this.item.stems ? this.item.stems : 1;
            return `${this.item.packing}x${stems}`;
        }
    },
    props: {
        id: {
            type: Number,
            required: true,
            description: 'The item id'
        },
        warehouseId: {
            type: Number,
            required: true
        },
        labelNumber: {
            type: Number
        },
        totalLabels: {
            type: Number
        }
    }
};