import ngModule from '../../module';
import Component from 'core/lib/component';
import './style.scss';

class Controller extends Component {
    $onInit() {
        this.basicData.registerChild(this);
    }

    get ticket() {
        return this._ticket;
    }

    set ticket(value) {
        this._ticket = value;

        if (!value || !value.id) return;

        this.clientAddressesList(value.clientFk);
    }

    get clientId() {
        return this.ticket && this.ticket.clientFk;
    }

    set clientId(value) {
        this.ticket.clientFk = value;
        this.ticket.addressFk = null;

        if (!value) return;

        this.getClientDefaultAddress(value);
        this.clientAddressesList(value);
    }

    get addressId() {
        return this.ticket && this.ticket.addressFk;
    }

    set addressId(value) {
        if (value != this.ticket.addressFk) {
            this.ticket.addressFk = value;
            this.onChangeAddress(value);
            this.getShipped({
                landed: this.ticket.landed,
                addressFk: value,
                agencyModeFk: this.ticket.agencyModeFk,
                warehouseFk: this.ticket.warehouseFk
            });
        }
    }

    get warehouseId() {
        return this.ticket && this.ticket.warehouseFk;
    }

    set warehouseId(value) {
        if (value != this.ticket.warehouseFk) {
            this.ticket.warehouseFk = value;

            this.getShipped({
                landed: this.ticket.landed,
                addressFk: this.ticket.addressFk,
                agencyModeFk: this.ticket.agencyModeFk,
                warehouseFk: value
            }).then(() => {
                if (this.zoneId == null)
                    this.ticket.agencyModeFk = null;
            });
        }
    }

    get shipped() {
        return this.ticket && this.ticket.shipped;
    }

    set shipped(value) {
        if (new Date(this.ticket.shipped).toDateString() != value.toDateString())
            value.setHours(0, 0, 0, 0);

        this.ticket.shipped = value;
        this.getLanded({
            shipped: value,
            addressFk: this.ticket.addressFk,
            agencyModeFk: this.ticket.agencyModeFk,
            warehouseFk: this.ticket.warehouseFk
        });
    }

    get landed() {
        return this.ticket && this.ticket.landed;
    }

    set landed(value) {
        this.ticket.landed = value;
        this.getShipped({
            landed: value,
            addressFk: this.ticket.addressFk,
            agencyModeFk: this.ticket.agencyModeFk,
            warehouseFk: this.ticket.warehouseFk
        });
    }

    get agencyModeId() {
        return this.ticket && this.ticket.agencyModeFk;
    }

    set agencyModeId(value) {
        if (value != this.ticket.agencyModeFk) {
            this.ticket.agencyModeFk = value;

            if (!value) return;

            const agencyMode = this.$.agencyMode.selection;
            this.ticket.warehouseFk = agencyMode.warehouseFk;

            this.getLanded({
                shipped: this.ticket.shipped,
                addressFk: this.ticket.addressFk,
                agencyModeFk: value,
                warehouseFk: this.ticket.warehouseFk
            });
        }
    }

    get zoneId() {
        return this.ticket && this.ticket.zoneFk;
    }

    set zoneId(value) {
        if (value != this.ticket.zoneFk) {
            this.ticket.zoneFk = value;
            this.onChangeZone(value);
        }
    }

    /*
     * Autocompletes address on client change
     */
    clientAddressesList(value) {
        let filter = {
            include: [
                {
                    relation: 'province',
                    scope: {
                        fields: ['name']
                    }
                },
                {
                    relation: 'agencyMode',
                    scope: {
                        fields: ['name']
                    }
                }
            ]
        };
        filter = encodeURIComponent(JSON.stringify(filter));

        let query = `Clients/${value}/addresses?filter=${filter}`;
        this.$http.get(query).then(res => {
            if (res.data)
                this.addresses = res.data;
        });
    }

    getClientDefaultAddress(value) {
        let query = `Clients/${value}`;
        this.$http.get(query).then(res => {
            if (res.data)
                this.addressId = res.data.defaultAddressFk;
        });
    }

    /*
     * Gets an agency from an specified zone
     */
    onChangeZone(zoneId) {
        this.ticket.agencyModeFk = null;
        const query = `Zones/${zoneId}`;
        this.$http.get(query).then(res => {
            this.ticket.agencyModeFk = res.data.agencyModeFk;
        });
    }

    onChangeAddress(addressId) {
        this.ticket.nickname = null;
        const query = `Addresses/${addressId}`;
        this.$http.get(query).then(res => {
            this.ticket.nickname = res.data.nickname;
        });
    }

    async onStepChange() {
        if (this.isFormInvalid()) {
            return this.vnApp.showError(
                this.$t('Some fields are invalid')
            );
        }

        const query = `tickets/${this.ticket.id}/priceDifference`;
        const params = {
            landed: this.ticket.landed,
            addressId: this.ticket.addressFk,
            agencyModeId: this.ticket.agencyModeFk,
            zoneId: this.ticket.zoneFk,
            warehouseId: this.ticket.warehouseFk,
            shipped: this.ticket.shipped
        };

        return this.$http.post(query, params).then(res => {
            if (res.data)
                this.ticket.sale = res.data;

            return true;
        }, err => {
            this.vnApp.showError(
                this.$t(err.data.error.message)
            );
        });
    }

    /*
     * Returns a landing date
     */
    getLanded(params) {
        const validParams = this.shipped && this.addressId
            && this.agencyModeId && this.warehouseId;
        if (!validParams) return this.$q.resolve();

        this.ticket.zoneFk = null;
        const query = `Agencies/getLanded`;
        return this.$http.get(query, {params}).then(res => {
            if (res.data) {
                this.ticket.zoneFk = res.data.zoneFk;
                this.ticket.landed = res.data.landed;
                this.ticket.shipped = params.shipped;
            } else {
                return this.vnApp.showError(
                    this.$t(`No delivery zone available for this landing date`)
                );
            }
        });
    }

    /*
     * Returns a shipment date
     */
    getShipped(params) {
        const validParams = this.landed && this.addressId
            && this.agencyModeId && this.warehouseId;
        if (!validParams) return this.$q.resolve();

        this.ticket.zoneFk = null;
        const query = `Agencies/getShipped`;
        return this.$http.get(query, {params}).then(res => {
            if (res.data) {
                this.ticket.zoneFk = res.data.zoneFk;
                this.ticket.landed = params.landed;
                this.ticket.shipped = res.data.shipped;
            } else {
                return this.vnApp.showError(
                    this.$t(`No delivery zone available for this landing date`)
                );
            }
        });
    }

    isFormInvalid() {
        return !this.ticket.clientFk || !this.ticket.addressFk || !this.ticket.agencyModeFk
            || !this.ticket.companyFk || !this.ticket.shipped || !this.ticket.landed
            || !this.ticket.zoneFk;
    }

    zoneWhere() {
        if (this.ticket.agencyModeFk) {
            return {
                shipped: this.ticket.shipped,
                addressFk: this.ticket.addressFk,
                agencyModeFk: this.ticket.agencyModeFk,
                warehouseFk: this.ticket.warehouseFk
            };
        }
        return {};
    }

    agencyModeWhere() {
        if (this.warehouseId) {
            return {
                warehouseFk: this.warehouseId
            };
        }
        return {};
    }
}

ngModule.vnComponent('vnTicketBasicDataStepOne', {
    template: require('./index.html'),
    controller: Controller,
    bindings: {
        ticket: '<'
    },
    require: {
        basicData: '^vnTicketBasicData'
    }
});