<i18n>
{
  "en": {
    "OrganizationsFormsSolutions": {
      "solutions": "Solutions",
      "choose": "Choose",
      "title": "Title",
      "description": "Description",
      "cancel": "Сancel",
      "recordsSelected": "{n} record selected of {allRecords} | {n} records selected of {allRecords}"
    }
  },
  "ru": {
    "OrganizationsFormsSolutions": {
      "solutions": "Решения",
      "choose": "Выбрать",
      "title": "Название",
      "description": "Описание",
      "cancel": "Отмена",
      "recordsSelected": "{n} записей выбрано из {allRecords} | {n} запись выбрана из {allRecords} | {n} записи выбрано из {allRecords} | {n} записей выбрано из {allRecords}"
    }
  }
}
</i18n>

<template>
  <q-form @submit="submit">
    <div v-if="readonly" class="q-gutter-y-xs">
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsSolutions.solutions') }}
        </div>
        <div class="col text-grey-7">{{ selectedSolutionsNameView }}</div>
      </div>
    </div>
    <div v-else>
      <q-table
        :grid="$q.screen.xs"
        :title="$t('OrganizationsFormsSolutions.solutions')"
        :data="data"
        :columns="columns"
        row-key="id"
        :selected-rows-label="getSelectedString"
        selection="multiple"
        :selected.sync="selected"
      >
        <template v-slot:item="props">
          <div
            class="q-pa-xs col-xs-12 col-sm-6 col-md-4 col-lg-3 grid-style-transition"
            :style="props.selected ? 'transform: scale(0.95);' : ''"
          >
            <q-card :class="props.selected ? 'bg-grey-2' : ''">
              <q-card-section>
                <q-checkbox
                  dense
                  v-model="props.selected"
                  :label="props.row.name"
                />
              </q-card-section>
              <q-separator />
              <q-list dense>
                <q-item
                  v-for="col in props.cols.filter((col) => col.name !== 'desc')"
                  :key="col.name"
                >
                  <q-item-section>
                    <q-item-label>{{ col.label }}</q-item-label>
                  </q-item-section>
                  <q-item-section side>
                    <q-item-label caption>{{ col.value }}</q-item-label>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-card>
          </div>
        </template>
      </q-table>
      <div class="q-mt-md row q-gutter-y-md">
        <q-btn
          class="col-xs-12 col-sm-auto"
          color="primary"
          :label="$t('OrganizationsFormsSolutions.cancel')"
          @click="cancelProcess"
          type="button"
          outline
        />
        <q-btn
          class="col-xs-12 col-sm-auto q-ml-sm-md"
          color="primary"
          :label="$t('OrganizationsFormsSolutions.choose')"
          type="submit"
        />
      </div>
    </div>
  </q-form>
</template>

<script lang="ts">
// @ts-nocheck
import { USER_SCOPES } from '@/constants/entities/Scope';
import { Component, Prop, Watch, Vue } from 'vue-property-decorator';
import InputData from '@/types/wf/InputData';
import { Solution, Organization } from '@openapi/idm';

const SOLUTION_PGS_ID = 'e9a16be1-a46a-4f2d-96e3-a9430c8dafae';

@Component({})
export default class OrganizationsFormsSolutions extends Vue {
  @Prop() inputData: FormInputData;
  @Prop() readonly: boolean;

  private selectedSolutionsName = [];
  private selected = [];
  private data = [];
  private activeSolutionsIds = [];

  @Watch('inputData', { immediate: true })
  handler(val: FormInputData) {
    if (val) {
      let activeSolutionsIds = [];
      const solutions = [];
      if (val.activeApplications) {
        activeSolutionsIds = val.activeApplications?.map(
          (itemSolution) => itemSolution.id
        );
        val.activeApplications?.forEach((el) => solutions.push(el));
        val.applications?.forEach((el) => {
          if (!activeSolutionsIds.includes(el.id)) {
            solutions.push(el);
          }
        });
      } else {
        val.applications?.forEach((el) => {
          solutions.push(el);
        });
      }
      this.data = !this.$AC.haveScope(USER_SCOPES.CLOUD_ADMIN)
        ? solutions.filter((item) => item.id !== SOLUTION_PGS_ID)
        : solutions;

      if (val.solutionsName) {
        this.selectedSolutionsName = val.solutionsName;
      }
      if (
        val.activeApplications &&
        val.activeApplications instanceof Array &&
        val.activeApplications.length > 0
      ) {
        this.activeSolutionsIds = activeSolutionsIds;
        this.selected = val.activeApplications;
      }
    }
  }

  private getSelectedString() {
    return this.$tc(
      'OrganizationsFormsSolutions.recordsSelected',
      this?.selected.length,
      { allRecords: this.data.length }
    );
  }

  private submit(e) {
    this.$emit('submit', e, this.outputData);
  }

  private cancelProcess(e) {
    this.$emit('submit', e, { transExit: true });
  }

  get selectedSolutionsNameView() {
    if (
      this.selectedSolutionsName &&
      this.selectedSolutionsName instanceof Array
    ) {
      return this.selectedSolutionsName.join(', ') || '';
    }

    return '';
  }

  get selectedSolutionsIds() {
    return (
      this.selected.map((currentApplication) => currentApplication.id) || []
    );
  }

  get outputData() {
    return {
      appsList: this.selectedSolutionsIds.filter(
        (currentApplicationId) =>
          !this.activeSolutionsIds.includes(currentApplicationId)
      ),
      solutionsName: this.selected.map(
        (currentApplication) => currentApplication.name
      ),
      removeApps: this.activeSolutionsIds.filter(
        (currentApplicationId) =>
          !this.selectedSolutionsIds.includes(currentApplicationId)
      ),
      transExit: false,
    };
  }

  get columns() {
    return [
      {
        name: 'name',
        required: true,
        label: this.$t('OrganizationsFormsSolutions.title'),
        align: 'left',
        field: 'name',
        sortable: true,
      },
      {
        name: 'description',
        required: true,
        label: this.$t('OrganizationsFormsSolutions.description'),
        align: 'left',
        field: 'description',
        sortable: true,
      },
    ];
  }
}

declare interface FormInputData extends InputData {
  activeApplications: Solution[];
  applications: Solution[];
  organization: Organization;
}
</script>
