import ngModule from '../../module';
import Section from 'salix/components/section';
import './style.scss';

class Controller extends Section {
    constructor($element, $) {
        super($element, $);
        this.import = {
            file: '',
            invoice: null,
            buys: []
        };
    }

    onFileChange($event) {
        const input = $event.target;
        const file = input.files[0];

        const reader = new FileReader();
        reader.onload = event =>
            this.fillData(event.target.result);
        reader.readAsText(file, 'UTF-8');
    }

    fillData(raw) {
        const data = JSON.parse(raw);
        const [invoice] = data.invoices;

        this.$.$applyAsync(() => {
            this.import.observation = invoice.tx_awb;

            const companyName = invoice.tx_company;
            const boxes = invoice.boxes;
            const buys = [];
            for (let box of boxes) {
                const boxVolume = box.nu_length * box.nu_width * box.nu_height;
                for (let product of box.products) {
                    const packing = product.nu_stems_bunch * product.nu_bunches;
                    buys.push({
                        description: product.nm_product,
                        companyName: companyName,
                        size: product.nu_length,
                        packing: packing,
                        grouping: product.nu_stems_bunch,
                        buyingValue: parseFloat(product.mny_rate_stem),
                        volume: boxVolume,
                    });
                }
            }

            const boxesId = boxes.map(box => box.id_box);
            this.import.ref = boxesId.join(', ');

            this.fetchBuys(buys);
        });
    }

    fetchBuys(buys) {
        const params = {buys};
        const query = `Entries/${this.$params.id}/importBuysPreview`;
        this.$http.post(query, params).then(res => {
            this.import.buys = res.data;
        });
    }

    onSubmit() {
        try {
            const params = this.import;
            const hasAnyEmptyRow = params.buys.some(buy => {
                return buy.itemFk == null;
            });

            if (hasAnyEmptyRow)
                throw new Error(`Some of the imported buys doesn't have an item`);

            const query = `Entries/${this.$params.id}/importBuys`;
            return this.$http.post(query, params)
                .then(() => this.vnApp.showSuccess(this.$t('Data saved!')))
                .then(() => this.$state.go('entry.card.buy.index'));
        } catch (e) {
            this.vnApp.showError(this.$t(e.message));
            return false;
        }
    }

    itemSearchFunc($search) {
        return /^\d+$/.test($search)
            ? {id: $search}
            : {name: {like: '%' + $search + '%'}};
    }

    showFilterDialog(buy) {
        this.activeBuy = buy;
        this.itemFilterParams = {};
        this.itemFilter = {
            include: [
                {
                    relation: 'producer',
                    scope: {
                        fields: ['name']
                    }
                },
                {
                    relation: 'ink',
                    scope: {
                        fields: ['name']
                    }
                }
            ]
        };

        this.$.filterDialog.show();
    }

    selectItem(id) {
        this.activeBuy['itemFk'] = id;
        this.$.filterDialog.hide();
    }

    filter() {
        const filter = this.itemFilter;
        const params = this.itemFilterParams;
        const where = {};

        for (let key in params) {
            const value = params[key];
            if (!value) continue;

            switch (key) {
            case 'name':
                where[key] = {like: `%${value}%`};
                break;
            case 'producerFk':
            case 'typeFk':
            case 'size':
            case 'inkFk':
                where[key] = value;
            }
        }

        filter.where = where;
        this.$.itemsModel.applyFilter(filter);
    }

    onKeyPress($event) {
        if ($event.key === 'Enter')
            this.filter();
    }
}

Controller.$inject = ['$element', '$scope'];

ngModule.vnComponent('vnEntryBuyImport', {
    template: require('./index.html'),
    controller: Controller,
    bindings: {
        worker: '<'
    }
});