<template>
  <q-page padding>
    <q-card class="my-card" flat v-if="currentProject">
      <q-card-section>
        <div class="text-center text-h5 text-bold text-capitalize">
          {{ currentProject.nomo.enhavo }}
        </div>
        <div class="text-center text-h7 text-bold text-capitalize">
          {{ currentProject.priskribo.enhavo }}
        </div>
        <q-card-actions align="right">
          <div class="text-subtitle2 text-brown">
            {{ projectUuid }}
          </div>
          <q-space />
          <q-btn flat round color="primary" icon="edit" @click="editProject">
            <q-tooltip> Редактирование проекта </q-tooltip>
          </q-btn>
          <q-btn flat round color="teal" icon="add" @click="addBoard">
            <q-tooltip> Добавить доску </q-tooltip>
          </q-btn>
          <q-btn flat round color="red" icon="delete" @click="deleteProject">
            <q-tooltip> Удалить проект </q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-card-section>
      <q-card-section horizontal>
        <q-card flat bordered v-for="rootNode in kanvasoTree" :key="rootNode.uuid" class="flex row">
          <tree-node class="" :node="rootNode" @edit="editNode" @add="addChild" @delete="deleteNode"></tree-node>
        </q-card></q-card-section>
    </q-card>

    <q-dialog v-model="deleteDialog" persistent @before-hide="cleanDialogs" @keyup.escape="closeDialogs">
      <q-card>
        <q-card-section class="row items-center">
          <q-avatar icon="warning" color="red" text-color="white" />
          <span class="q-ml-sm">{{ dialogMessage }}</span>
        </q-card-section>
        <q-card-actions align="right">
          <q-btn flat label="Отмена" color="positive" @click="closeDialogs" />
          <q-btn flat label="Удалить" color="negative" @click="dialogMethod(payload)" />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <q-dialog v-model="addOrEditDialog" persistent @before-hide="cleanDialogs" @keyup.escape="closeDialogs" @keyup.enter="
      !(
        !name ||
        !description ||
        (name === oldName && description === oldDescription)
      )
        ? dialogMethod(payload)
        : ''
      ">
      <q-card>
        <q-card-section class="row items-center">
          <q-avatar icon="edit" color="blue" text-color="white" />
          <span class="q-ml-sm">{{ dialogMessage }}</span>
        </q-card-section>
        <q-card-section class=" ">
          <q-input v-model="name" type="text" :label="nameLabel" />
          <q-input v-model="description" type="text" :label="descriptionLabel" />
        </q-card-section>
        <q-card-actions align="right">
          <q-btn flat label="Отмена" color="positive" @click="closeDialogs" />
          <q-btn flat :disable="!name ||
            !description ||
            (name === oldName && description === oldDescription)
            " label="Сохранить" color="negative" @click="dialogMethod(payload)" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-page>
</template>
<script lang="ts">
import { useKanvasoStore } from '../stores/kanvaso';
import { mapActions, mapState } from 'pinia';
import { defineComponent } from 'vue';
import { useCurrentUserStore } from '../stores/current-user';
import TreeNode from 'components/TreeNode.vue';

export default defineComponent({
  // name: 'PageName'
  components: {
    TreeNode,
  },
  data() {
    return {
      deleteDialog: false,
      dialogMessage: '',
      addOrEditDialog: false,
      name: '',
      nameLabel: '',
      oldName: '',
      description: '',
      oldDescription: '',
      descriptionLabel: '',
      dialogMethod: null,
      payload: {},
      deleteProjectFlag: false,
      wsSubscribe: null,
    };
  },

  computed: {
    ...mapState(useKanvasoStore, {
      project: 'getKanvaso',
      kanvasoTree: 'getTree',
    }),
    ...mapState(useCurrentUserStore, { userId: 'getUserId' }),

    currentProject() {
      return this.project ? this.project[0]?.node : null;
    },
    projectUuid() {
      return this.$route?.params?.uuid || '';
    },
  },
  watch: {
    name(val) {
      this.name = val.trim();

      if ('nomo' in this.payload) {
        this.payload.nomo = val;
      }
    },
    description(val) {
      this.description = val.trim();

      if ('priskribo' in this.payload) {
        this.payload.priskribo = val;
      }
    },
  },
  methods: {
    ...mapActions(useKanvasoStore, [
      'onGetKanvasoFull',
      'onEditKanvasoObjekto',
      'onEditKanvaso',
      'onEditKanvasoLigilo',
      'onGetKanvasoObjekto',
      'onKanvasoSubscribe',
    ]),

    editNode(node) {
      this.dialogMessage = 'Редактирование элемента';
      this.nameLabel = 'Название';
      this.descriptionLabel = 'Описание';
      this.name = this.oldName = node.name;
      this.description = this.oldDescription = node.description;
      this.payload = {
        nomo: this.name,
        priskribo: this.description,
        kanvasoUuid: this.projectUuid,

        // posedantoUzantoId: this.userId,
        uuid: node.uuid,
      };
      this.dialogMethod = this.updateKanvasoObjekto;
      this.addOrEditDialog = true;
    },
    addBoard() {
      this.dialogMessage = 'Добавление доски';
      this.nameLabel = 'Название';
      this.descriptionLabel = 'Описание';
      this.payload = {
        nomo: this.name,
        priskribo: this.description,
        kanvasoUuid: this.projectUuid,
        posedantoUzantoId: this.userId,
        tipoId: 1,
      };
      this.dialogMethod = this.updateKanvasoObjekto;
      this.addOrEditDialog = true;
    },
    addChild(node) {
      this.dialogMessage = 'Добавление';
      this.nameLabel = 'Название';
      this.descriptionLabel = 'Описание';
      let typeId = 0;

      switch (node.typeId) {
        case 0:
          typeId = 1;
          break;
        case 1:
          typeId = 3;
          break;
        default:
          typeId = 4;
          break;
      }

      this.payload = {
        nomo: this.name,
        priskribo: this.description,
        kanvasoUuid: this.projectUuid,
        posedantoUzantoId: this.userId,
        tipoId: typeId,
        ligiloPosedantoUuid: node?.uuid,
      };
      this.dialogMethod = this.updateKanvasoObjekto;
      this.addOrEditDialog = true;
    },
    deleteNode(node) {
      this.dialogMessage = 'Удаление элемента';
      this.payload = {
        posedantoUzantoId: this.userId,
        uuid: node.uuid,
        forigo: true,
      };
      this.dialogMethod = this.deleteKanvasoObjekto;
      this.deleteDialog = true;
    },

    editProject() {
      this.dialogMessage = 'Редактирование проекта';
      this.nameLabel = 'Название проекта';
      this.descriptionLabel = 'Описание проекта';
      this.name = this.oldName = this.currentProject?.nomo?.enhavo || '';
      this.description = this.oldDescription =
        this.currentProject?.priskribo?.enhavo || '';
      this.payload = {
        nomo: this.name,
        priskribo: this.description,
        uuid: this.projectUuid,
        posedantoUzantoId: this.userId,
      };
      this.dialogMethod = this.updateKanvaso;
      this.addOrEditDialog = true;
    },

    deleteProject() {
      this.deleteProjectFlag = true;
      this.dialogMessage = 'Удаление проекта';
      this.nameLabel = 'Название проекта';
      this.descriptionLabel = 'Описание проекта';
      this.payload = {
        uuid: this.projectUuid,
        posedantoUzantoId: this.userId,
        forigo: true,
      };
      this.dialogMethod = this.updateKanvaso;
      this.deleteDialog = true;
    },

    cleanDialogs() {
      this.dialogMessage = '';
      this.name = '';
      this.nameLabel = '';
      this.oldName = '';
      this.description = '';
      this.descriptionLabel = '';
      this.oldDescription = '';
      this.dialogMethod = null;
      this.payload = {};
    },
    closeDialogs() {
      this.deleteDialog = false;
      this.addOrEditDialog = false;
    },
    async updateKanvaso(payload) {
      this.closeDialogs();
      await this.onEditKanvaso(payload)
        .then(() => {
          this.$q.notify({
            message: 'Успешно',
            color: 'positive',
          });
          if (this.deleteProjectFlag) {
            this.$router.replace({ name: 'projects' });
            return;
          }
          return;
        })
        .catch((err) => {
          this.$q.notify({
            message: 'Ошибка',
            color: 'negative',
          });
          console.log('error update kanvaso :>> ', err);
        });
      this.onGetKanvasoFull({ uuid: this.projectUuid });
      this.cleanDialogs();
    },
    async updateKanvasoObjekto(payload) {
      this.closeDialogs();
      await this.onEditKanvasoObjekto(payload)
        .then(() => {
          this.$q.notify({
            message: 'Успешно',
            color: 'positive',
          });
          return;
        })
        .catch((err) => {
          this.$q.notify({
            message: 'Ошибка',
            color: 'negative',
          });
          console.log('error update kanvaso objekto :>> ', err);
        });
      this.cleanDialogs();
    },

    async deleteKanvasoObjekto() {
      this.closeDialogs();
      await this.onEditKanvasoObjekto(this.payload)
        .then(() => {
          this.$q.notify({
            message: 'Успешно',
            color: 'positive',
          });
          return;
        })
        .catch((err) => {
          this.$q.notify({
            message: 'Ошибка',
            color: 'negative',
          });
          console.log('error delete objekto :>> ', err);
        });
      this.cleanDialogs();
    },
  },

  async mounted() {
    await this.onGetKanvasoFull({ uuid: this.projectUuid })
      .then((result) => {
        if (result.data.kanvasojKanvaso.edges.length === 0) {
          throw new Error(result);
        }
        this.onKanvasoSubscribe({
          kanvasoj: [this.currentProject.objId],
        }).then((data) => {
          this.wsSubscribe = data;
        });
      })
      .catch((err) => {
        console.log('error get kanvaso full :>> ', err);
        this.$router.replace({ name: 'projects' });
      });
    this.onGetKanvasoObjekto({ kanvaso_Uuid: this.projectUuid });

    this.deleteProjectFlag = false;
  },
  beforeUnmount() {
    if (this.wsSubscribe) {
      this.wsSubscribe.unsubscribe();
    }
  },
});
</script>
