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

export default class Controller extends Section {
    constructor($element, $) {
        super($element, $);
        this.editedColumn;
        this.checkAll = false;
        this.checkedFixedPrices = [];

        this.smartTableOptions = {
            activeButtons: {
                search: true
            },
            columns: [
                {
                    field: 'warehouseFk',
                    autocomplete: {
                        url: 'Warehouses',
                        showField: 'name',
                        valueField: 'id',
                    }
                },
                {
                    field: 'started',
                    searchable: false
                },
                {
                    field: 'ended',
                    searchable: false
                }
            ]
        };

        this.filterParams = {
            warehouseFk: this.vnConfig.warehouseFk
        };
    }

    getFilterParams() {
        return {
            warehouseFk: this.vnConfig.warehouseFk
        };
    }

    get columns() {
        if (this._columns) return this._columns;

        this._columns = [
            {field: 'rate2', displayName: this.$t('Grouping price')},
            {field: 'rate3', displayName: this.$t('Packing price')},
            {field: 'hasMinPrice', displayName: this.$t('Has min price')},
            {field: 'minPrice', displayName: this.$t('Min price')},
            {field: 'started', displayName: this.$t('Started')},
            {field: 'ended', displayName: this.$t('Ended')},
            {field: 'warehouseFk', displayName: this.$t('Warehouse')}
        ];

        return this._columns;
    }

    get checked() {
        const fixedPrices = this.$.model.data || [];
        const checkedBuys = [];
        for (let fixedPrice of fixedPrices) {
            if (fixedPrice.checked)
                checkedBuys.push(fixedPrice);
        }

        return checkedBuys;
    }

    uncheck() {
        this.checkAll = false;
        this.checkedFixedPrices = [];
    }

    get totalChecked() {
        if (this.checkedDummyCount)
            return this.checkedDummyCount;

        return this.checked.length;
    }

    saveChecked(fixedPriceId) {
        const index = this.checkedFixedPrices.indexOf(fixedPriceId);
        if (index !== -1)
            return this.checkedFixedPrices.splice(index, 1);
        return this.checkedFixedPrices.push(fixedPriceId);
    }

    reCheck() {
        if (!this.$.model.data) return;
        if (!this.checkedFixedPrices.length) return;

        this.$.model.data.forEach(fixedPrice => {
            if (this.checkedFixedPrices.includes(fixedPrice.id))
                fixedPrice.checked = true;
        });
    }

    onEditAccept() {
        const rowsToEdit = [];
        for (let row of this.checked)
            rowsToEdit.push({id: row.id, itemFk: row.itemFk});

        const data = {
            field: this.editedColumn.field,
            newValue: this.editedColumn.newValue,
            lines: rowsToEdit
        };

        if (this.checkedDummyCount && this.checkedDummyCount > 0) {
            const params = {};
            if (this.$.model.userParams) {
                const userParams = this.$.model.userParams;
                for (let param in userParams) {
                    let newParam = this.exprBuilder(param, userParams[param]);
                    if (!newParam)
                        newParam = {[param]: userParams[param]};
                    Object.assign(params, newParam);
                }
            }
            if (this.$.model.userFilter)
                Object.assign(params, this.$.model.userFilter.where);

            data.filter = params;
        }

        return this.$http.post('FixedPrices/editFixedPrice', data)
            .then(() => {
                this.uncheck();
                this.$.model.refresh();
            });
    }

    isBigger(date) {
        let today = Date.vnNew();
        today.setHours(0, 0, 0, 0);

        date = new Date(date);
        date.setHours(0, 0, 0, 0);

        const timeDifference = today - date;
        if (timeDifference < 0) return 'warning';
    }

    isLower(date) {
        let today = Date.vnNew();
        today.setHours(0, 0, 0, 0);

        date = new Date(date);
        date.setHours(0, 0, 0, 0);

        const timeDifference = today - date;
        if (timeDifference > 0) return 'warning';
    }

    add() {
        if (!this.$.model.data || this.$.model.data.length == 0) {
            this.$.model.data = [];
            this.$.model.proxiedData = [];

            const today = Date.vnNew();

            const millisecsInDay = 86400000;
            const daysInWeek = 7;
            const nextWeek = new Date(today.getTime() + daysInWeek * millisecsInDay);

            this.$.model.insert({
                started: today,
                ended: nextWeek
            });
            return;
        }

        const lastIndex = this.$.model.data.length - 1;
        const lastItem = this.$.model.data[lastIndex];
        this.$.model.insert({
            itemFk: lastItem.itemFk,
            name: lastItem.name,
            subName: lastItem.subName,
            value5: lastItem.value5,
            value6: lastItem.value6,
            value7: lastItem.value7,
            value8: lastItem.value8,
            value9: lastItem.value9,
            value10: lastItem.value10,
            warehouseFk: lastItem.warehouseFk,
            rate2: lastItem.rate2,
            rate3: lastItem.rate3,
            hasMinPrice: lastItem.hasMinPrice,
            minPrice: lastItem.minPrice,
            started: lastItem.started,
            ended: lastItem.ended,
        });
    }

    upsertPrice(price, resetMinPrice) {
        if (resetMinPrice)
            delete price['minPrice'];

        const requiredFields = ['itemFk', 'started', 'ended', 'rate2', 'rate3'];
        for (const field of requiredFields)
            if (price[field] == undefined) return;

        const query = 'FixedPrices/upsertFixedPrice';
        this.$http.patch(query, price)
            .then(res => {
                this.vnApp.showSuccess(this.$t('Data saved!'));
                Object.assign(price, res.data);
            });
    }

    removePrice($index) {
        const price = this.$.model.data[$index];
        if (price.id) {
            this.$http.delete(`FixedPrices/${price.id}`)
                .then(() => {
                    this.$.model.remove($index);
                    this.vnApp.showSuccess(this.$t('Data saved!'));
                });
        } else
            this.$.model.remove($index);
    }

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

    exprBuilder(param, value) {
        switch (param) {
        case 'name':
            return {'i.name': {like: `%${value}%`}};
        case 'itemFk':
        case 'warehouseFk':
        case 'rate2':
        case 'rate3':
            param = `fp.${param}`;
            return {[param]: value};
        case 'minPrice':
            param = `i.${param}`;
            return {[param]: value};
        }
    }
}

ngModule.vnComponent('vnFixedPrice', {
    template: require('./index.html'),
    controller: Controller
});