<i18n>
{
  "en": {
    "regions": {
      "AccountsCard": {
        "tab": "Accounts"
      },
      "CalendarCard": {
        "tab": "Production calendar"
      },
      "CommonCard": {
        "block": "Block",
        "unblock": "Unblock",
        "delete": "Delete",
        "region": "Region",
        "questionToDelete": "Are you sure you want to delete the region?",
        "yes": "Yes",
        "no": "No",
        "confirmation": "Confirmation"
      },
      "DataCard": {
        "tab": "Data"
      },
      "OrganizationsCard": {
        "tab": "Organizations"
      },
      "PaymentsCard": {
        "tab": "Payments"
      },
      "NotificationsCard": {
        "tab": "Notifications"
      }
    }
  },
  "ru": {
    "regions": {
      "AccountsCard": {
        "tab": "Сотрудники"
      },
      "CalendarCard": {
        "tab": "Производственный календарь"
      },
      "CommonCard": {
        "block": "Заблокировать",
        "unblock": "Разблокировать",
        "delete": "Удалить",
        "region": "Субъект",
        "questionToDelete": "Вы действительно хотите удалить субъект?",
        "yes": "Да",
        "no": "Нет",
        "confirmation": "Подтвердите"
      },
      "DataCard": {
        "tab": "Основные данные"
      },
      "OrganizationsCard": {
        "tab": "Организации"
      },
      "PaymentsCard": {
        "tab": "Платежи"
      },
       "NotificationsCard": {
        "tab": "Уведомления"
      }
    }
  }
}
</i18n>

<template>
  <div>
    <div
      class="flex justify-between items-center bg-white q-pa-md q-mt-md q-mx-md rounded-borders"
    >
      <div
        class="column justify-center text-h5 q-mr-auto"
        style="min-height: 36px"
      >
        <div class="text-h6 flex items-center text-grey-9 col q-pr-md">
          <q-btn
            padding="xs"
            class="text-grey-7 q-mr-md"
            color="grey-3"
            icon="arrow_back"
            @click="returnToParentView('/regions')"
          />
          <span class="text-h5">{{ subTitle }} {{ get(model, 'name') }}</span>
        </div>
      </div>
      <div class="row">
        <q-skeleton type="QBtn" v-if="loading" />
        <template v-else>
          <q-btn
            :label="
              get(model, 'enabled')
                ? $t('regions.CommonCard.block')
                : $t('regions.CommonCard.unblock')
            "
            @click="startBlockProcess"
            class="q-ml-sm"
            color="primary"
            outline
          />
          <q-btn
            v-if="$AC.haveScope(USER_SCOPES.CLOUD_ADMIN)"
            :label="$t('regions.CommonCard.delete')"
            @click="dialogDelete = true"
            class="q-ml-sm"
            color="primary"
            outline
          />
        </template>
      </div>
    </div>

    <q-dialog v-model="dialogDelete">
      <q-card class="no-shadow">
        <q-card-section>
          <div class="text-h6">{{ $t('regions.CommonCard.confirmation') }}</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          {{ $t('regions.CommonCard.questionToDelete') }}
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            flat
            @click="dialogDelete = false"
            :label="$t('regions.CommonCard.no')"
            color="primary"
          />
          <q-btn
            flat
            @click="startDeleteProcess"
            :label="$t('regions.CommonCard.yes')"
            color="red"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <base-tabs :currentTab="tabs.current" :tabs="tabs.list" />
  </div>
</template>

<script lang="ts">
// @ts-nocheck
import ReturnToParentView from '@mixins/ReturnToParentView';
import { CardNeedToUpdateType } from '@constants/models/Card';
import { USER_SCOPES } from '@constants/entities/Scope';
import get from 'lodash/get';
import { RegionApi } from '@openapi/idm';

const regionApi = new RegionApi();

export default {
  props: ['common', 'model', 'userTask'],
  mixins: [ReturnToParentView],
  computed: {
    loading() {
      return !this.model;
    },
    country() {
      return this.$store.getters['idm/regions/country'];
    },
    subTitle() {
      return this.model?.code !== this.country.code
        ? this.$t('regions.CommonCard.region')
        : '';
    },
  },
  data() {
    return {
      USER_SCOPES: USER_SCOPES,
      dialogDelete: false,
      tabs: {
        current: this.common.active,
        list: [],
      },
    };
  },
  created() {
    this.init();
  },
  methods: {
    get,
    init() {
      const initModel = () => {
        return this.initModel().then(() => {
          this.initTabsList();
        });
      };

      initModel();
    },
    initModel() {
      return new Promise((resolve, reject) => {
        try {
          regionApi
            .getRegion(this.common.id, 'calendar,parent')
            .then(({ data: model }) => {
              this.$store.commit(`utils/cards/addModel`, {
                model,
                path: this.common.path,
              });
              return resolve();
            })
            .catch((e) => {
              return reject(e);
            });
        } catch (e) {
          return reject(e);
        }
      });
    },
    initTabsList() {
      this.tabs.list = [
        {
          name: this.$t('regions.DataCard.tab'),
          path: 'data',
          visible: true,
        },
        {
          name: this.$t('regions.OrganizationsCard.tab'),
          path: 'organizations',
          visible: true,
        },
        {
          name: this.$t('regions.AccountsCard.tab'),
          path: 'accounts',
          visible: true,
        },
        {
          name: this.$t('regions.CalendarCard.tab'),
          path: 'calendar',
          visible: true,
        },
        {
          name: this.$t('regions.PaymentsCard.tab'),
          path: 'payments',
          visible: true,
        },
        {
          name: this.$t('regions.NotificationsCard.tab'),
          path: 'notifications',
          visible: () => this.$AC.haveOneOfScope([USER_SCOPES.CLOUD_ADMIN, USER_SCOPES.REGION_ADMIN]),
        },
      ];
    },
    startBlockProcess() {
      this.$store.dispatch('wf/processes/dispatchProcess', {
        processKey: 'BlockRegionProcess',
        data: {
          regionId: this.model.id,
          redirectUrl: this.$route.fullPath,
        },
      });
    },
    startDeleteProcess() {
      this.$store.dispatch('wf/processes/dispatchProcess', {
        processKey: 'DeleteRegionProcess',
        data: {
          regionId: this.model.id,
          redirectUrl: '/regions',
        },
      });
    },
  },

  watch: {
    'common.active': function (val) {
      this.tabs.current = val;
    },
    'common.needToUpdate': {
      handler: function () {
        this.$store.commit(
          `utils/cards/needToUpdate`,
          CardNeedToUpdateType.FALSE
        );

        this.init();
      },
    },
  },
  beforeDestroy() {
    this.$store.commit(`utils/cards/removeModel`, {
      path: this.common.path,
    });
  },
};
</script>
