const strftime = require('strftime');
const database = require(`${appPath}/lib/database`);
const UserException = require(`${appPath}/lib/exceptions/userException`);

module.exports = {
    name: 'rpt-receipt',
    /*     serverPrefetch() {
        console.log(arguments);
        return new Promise(accept => {
            this.client = this.getReceipt();
        });
    }, */
    async asyncData(ctx, params) {
        Object.assign(this, this.methods);

        const [[client]] = await this.fetchClient(params.receiptFk);
        const [[receipt]] = await this.fetchReceipt(params.receiptFk);

        if (!receipt)
            throw new UserException('No receipt data found');

        return {client, receipt};
    },
    created() {
        if (this.client.locale)
            this.$i18n.locale = this.client.locale;

        const embeded = [];
        this.files.map(file => {
            embeded[file] = `file://${__dirname + file}`;
        });
        this.embeded = embeded;
    },
    data() {
        return {
            files: ['/assets/images/signature.png']
        };
    },
    methods: {
        fetchClient(receiptFk) {
            return database.pool.query(
                `SELECT 
                    c.id,
                    c.socialName,
                    u.lang locale
                FROM receipt r
                    JOIN client c ON c.id = r.clientFk
                    JOIN account.user u ON u.id = c.id
                WHERE r.id = ?`, [receiptFk]);
        },
        fetchReceipt(receiptFk) {
            return database.pool.query(
                `SELECT 
                    r.id, 
                    r.amountPaid, 
                    r.amountUnpaid, 
                    r.payed, 
                    r.companyFk
                FROM receipt r
                    JOIN client c ON c.id = r.clientFk
                WHERE r.id = ?`, [receiptFk]);
        }
        /*         dated: () => {
            return strftime('%d-%m-%Y', new Date());
        }, */
    },
    components: {
        'report-header': require('../report-header'),
        'report-footer': require('../report-footer'),
    },
};