<script setup>
import { computed, ref, onMounted, onUpdated } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useQuasar } from 'quasar';

import VnInput from 'src/components/common/VnInput.vue';

import { useI18n } from 'vue-i18n';
import axios from 'axios';

onMounted(() => fetch());
onUpdated(() => fetch());

const { t } = useI18n();
const route = useRoute();
const quasar = useQuasar();
const router = useRouter();
const $props = defineProps({
    id: {
        type: Number,
        required: false,
        default: null,
    },
});
const entityId = computed(() => $props.id || route.params.id);

const wagon = ref([]);
const divisible = ref(false);
const name = ref('');
const colorPickerActive = ref(false);
let originalData = { trays: [] };
let wagonConfig;
let wagonTypeColors;
let currentTrayColorPicked;

async function fetch() {
    try {
        await axios.get('WagonConfigs').then(async (res) => {
            if (res.data) {
                wagonConfig = res.data[0];
            }
        });

        await axios.get(`WagonTypeColors`).then(async (res) => {
            if (res.data) {
                wagonTypeColors = res.data;
                if (!entityId.value)
                    wagon.value.push({
                        id: 0,
                        position: 0,
                        color: { ...wagonTypeColors[0] },
                        action: 'add',
                    });
                else {
                    await axios
                        .get(`WagonTypeTrays`, {
                            params: { filter: { where: { typeFk: entityId.value } } },
                        })
                        .then(async (res) => {
                            if (res.data) {
                                for (let i = 0; i < res.data.length; i++) {
                                    const tray = res.data[i];
                                    wagon.value.push({
                                        id: res.data.length - i - 1,
                                        position: tray.height,
                                        color: {
                                            ...wagonTypeColors.find((color) => {
                                                return color.id === tray.colorFk;
                                            }),
                                        },
                                        action: tray.height == 0 ? 'add' : 'delete',
                                    });
                                }
                                wagon.value.forEach((value) => {
                                    originalData.trays.push({ ...value });
                                });
                            }
                        });
                }
            }
        });

        if (entityId.value) {
            await axios.get(`WagonTypes/${entityId.value}`).then((res) => {
                if (res.data) {
                    originalData.name = name.value = res.data.name;
                    originalData.divisible = divisible.value = res.data.divisible;
                }
            });
        }
    } catch (e) {
        //
    }
}

function addTray() {
    if (
        wagon.value.find((tray) => {
            return tray.position == null;
        })
    ) {
        quasar.notify({
            message: t('wagon.warnings.uncompleteTrays'),
            type: 'warning',
        });
        return;
    }

    if (wagon.value.length < wagonConfig.maxTrays) {
        wagon.value.unshift({
            id: wagon.value.length,
            position: null,
            color: { ...wagonTypeColors[0] },
            action: 'delete',
        });
    } else {
        quasar.notify({
            message: t('wagon.warnings.maxTrays'),
            type: 'warning',
        });
    }
}

function deleteTray(trayToDelete) {
    wagon.value = wagon.value.filter((tray) => tray.id !== trayToDelete.id);
    reorderIds();
}

function reorderIds() {
    for (let index = wagon.value.length - 1; index >= 0; index--) {
        wagon.value[index].id = index;
    }
}

async function onSubmit() {
    try {
        const path = entityId.value
            ? 'WagonTypes/editWagonType'
            : 'WagonTypes/createWagonType';

        const params = {
            id: entityId.value,
            name: name.value,
            divisible: divisible.value,
            trays: wagon.value,
        };

        await axios.patch(path, params).then((res) => {
            if (res.status == 204) router.push({ path: `/wagon/type/list` });
        });
    } catch (error) {
        //
    }
}

function onReset() {
    name.value = entityId.value ? originalData.name : null;
    divisible.value = entityId.value ? originalData.divisible : false;
    wagon.value = entityId.value
        ? [...originalData.trays]
        : [
              {
                  id: 0,
                  position: 0,
                  color: { ...wagonTypeColors[0] },
                  action: 'add',
              },
          ];
}

function doAction(tray) {
    if (tray.action == 'add') {
        addTray();
    } else {
        deleteTray(tray);
    }
}

function showColorPicker(tray) {
    colorPickerActive.value = true;
    currentTrayColorPicked = wagon.value.findIndex((val) => {
        return val.id === tray.id;
    });
}

function updateColor(newColor) {
    wagon.value[currentTrayColorPicked].color = {
        ...wagonTypeColors.find((color) => {
            return color.rgb === newColor;
        }),
    };
}

function onPositionBlur(tray) {
    if (tray.position) {
        if (tray.position == '' || tray.position < 0) {
            tray.position = null;
            return;
        }
        tray.position = parseInt(tray.position);
        wagon.value.sort((a, b) => b.position - a.position);
        reorderIds();
        for (let index = wagon.value.length - 1; index > 0; index--) {
            if (exceedMaxHeight(index - 1)) continue;
            if (
                wagon.value[index - 1].position - wagon.value[index].position >=
                wagonConfig.minHeightBetweenTrays
            ) {
                continue;
            } else {
                wagon.value[index - 1].position +=
                    wagonConfig.minHeightBetweenTrays -
                    (wagon.value[index - 1].position - wagon.value[index].position);

                quasar.notify({
                    message:
                        t('wagon.warnings.minHeightBetweenTrays') +
                        wagonConfig.minHeightBetweenTrays +
                        ' cm',
                    type: 'warning',
                });

                exceedMaxHeight(index - 1);
            }
        }
    }
}

function exceedMaxHeight(pos) {
    if (wagon.value[pos].position > wagonConfig.maxWagonHeight) {
        wagon.value.splice(pos, 1);
        quasar.notify({
            message:
                t('wagon.warnings.maxWagonHeight') + wagonConfig.maxWagonHeight + ' cm',
            type: 'warning',
        });
        return true;
    }
    return false;
}
</script>

<template>
    <QPage class="q-pa-sm q-mx-xl">
        <QForm @submit="onSubmit()" @reset="onReset()" class="q-pa-sm">
            <QCard class="q-pa-md">
                <VnInput
                    filled
                    v-model="name"
                    :label="t('wagon.type.name')"
                    :rules="[(val) => !!val || t('wagon.warnings.nameNotEmpty')]"
                />
                <QCheckbox class="q-mb-sm" v-model="divisible" label="Divisible" />
                <div class="wagon-tray q-mx-lg" v-for="tray in wagon" :key="tray.id">
                    <div class="position">
                        <QInput
                            autofocus
                            filled
                            type="number"
                            :class="{ isVisible: tray.action == 'add' }"
                            v-model="tray.position"
                            @blur="onPositionBlur(tray)"
                        >
                            <QTooltip :delay="2000">
                                {{
                                    t('wagon.warnings.minHeightBetweenTrays') +
                                    wagonConfig.minHeightBetweenTrays +
                                    ' cm'
                                }}
                                <QSpace />
                                {{
                                    t('wagon.warnings.maxWagonHeight') +
                                    wagonConfig.maxWagonHeight +
                                    ' cm'
                                }}
                            </QTooltip>
                        </QInput>
                    </div>
                    <div class="shelving">
                        <div class="shelving-half">
                            <div class="shelving-up"></div>
                            <div
                                class="shelving-down"
                                :style="{ backgroundColor: tray.color.rgb }"
                                @click="showColorPicker(tray)"
                            ></div>
                        </div>
                        <div
                            class="shelving-divisible"
                            :class="{ isVisible: !divisible }"
                        ></div>
                        <div class="shelving-half">
                            <div class="shelving-up"></div>
                            <div
                                class="shelving-down"
                                :style="{ backgroundColor: tray.color.rgb }"
                                @click="showColorPicker(tray)"
                            ></div>
                        </div>
                    </div>
                    <div class="action-button">
                        <QBtn
                            flat
                            round
                            color="primary"
                            :icon="tray.action"
                            @click="doAction(tray)"
                        />
                    </div>
                </div>
                <div class="q-mb-sm wheels">
                    <QIcon color="grey-6" name="trip_origin" size="xl" />
                    <QIcon color="grey-6" name="trip_origin" size="xl" />
                </div>
                <QDialog
                    v-model="colorPickerActive"
                    position="right"
                    :no-backdrop-dismiss="false"
                >
                    <QCard>
                        <QCardSection>
                            <div class="text-h6">{{ t('wagon.type.trayColor') }}</div>
                        </QCardSection>
                        <QCardSection class="row items-center no-wrap">
                            <QColor
                                flat
                                v-model="wagon[currentTrayColorPicked].color.rgb"
                                no-header
                                no-footer
                                default-view="palette"
                                :palette="
                                    wagonTypeColors.map((color) => {
                                        return color.rgb;
                                    })
                                "
                                @change="updateColor($event)"
                            />
                            <QBtn flat round icon="close" v-close-popup />
                        </QCardSection>
                    </QCard>
                </QDialog>
            </QCard>
            <div class="q-mt-md">
                <QBtn :label="t('wagon.type.submit')" type="submit" color="primary" />
                <QBtn
                    :label="t('wagon.type.reset')"
                    type="reset"
                    color="primary"
                    flat
                    class="q-ml-sm"
                />
            </div>
        </QForm>
    </QPage>
</template>

<style lang="scss" scoped>
.q-page {
    display: flex;
    justify-content: center;
    align-items: flex-start;
}

.q-form {
    width: 70%;
}

.q-dialog {
    .q-card {
        width: 100%;
    }
}

.wheels {
    margin-left: 5%;
    display: flex;
    justify-content: space-around;
}

.wagon-tray {
    display: flex;
    height: 6rem;

    .position {
        width: 20%;
        border-right: 1rem solid gray;
        display: flex;
        align-items: flex-end;
        justify-content: flex-end;
        padding-right: 1rem;
    }

    .shelving {
        display: flex;
        width: 75%;

        .shelving-half {
            width: 50%;
            height: 100%;

            .shelving-up {
                height: 80%;
                width: 100%;
            }

            .shelving-down {
                height: 20%;
                width: 100%;
            }
        }

        .shelving-divisible {
            width: 1%;
            height: 100%;
            border-left: 0.5rem dashed grey;
            border-right: 0.5rem dashed grey;
        }
    }

    .action-button {
        width: 10%;
        border-left: 1rem solid gray;
        display: flex;
        align-items: flex-end;
        justify-content: flex-start;
        padding-left: 1rem;
    }

    .isVisible {
        display: none;
    }
}
</style>
