<template>
  <div>
    <q-card
      class="no-shadow q-pb-md q-gutter-y-md q-mx-md q-mt-md"
      v-if="card && !loading"
    >
      <div
        class="bg-grey-1 items-center justify-between row q-pa-md"
        style="border-radius: 0; padding: 16px"
      >
        <q-btn
          padding="xs"
          class="text-grey-7 q-mr-md"
          color="grey-3"
          icon="arrow_back"
          @click="goToSettingsList()"
        />
        <div class="text-h6 text-grey-9 col q-pr-md">
          {{ cardModel.shortName }}
        </div>
        <div
          v-if="$AC.haveScope(USER_SCOPES.SOCIAL_SETTINGS_GENERAL_ADMIN)"
          class="gt-xs"
        >
          <q-btn
            v-if="cardModel.state === 'DRAFT'"
            :loading="editLoading"
            color="primary"
            class="q-mr-md"
            :label="$t('additionalSettings.takeToWork')"
            type="button"
            icon="how_to_reg"
            @click="goTo('IN_PROCESS')"
          />
          <q-btn
            v-if="cardModel.state === 'IN_PROCESS'"
            :loading="editLoading"
            color="primary"
            class="q-mr-md"
            outline
            type="button"
            icon="save"
            @click="save"
          >
            <q-tooltip :delay="500">
              {{ $t('base.actions.save') }}
            </q-tooltip>
          </q-btn>
          <q-btn
            v-if="cardModel.state === 'READY_FOR_PUBLISH'"
            :loading="editLoading"
            label="Редактировать"
            color="primary"
            class="q-mr-md"
            outline
            type="button"
            icon="create"
            @click="goTo('IN_PROCESS')"
          />
          <q-btn
            @click="dialogDeleteConfim = true"
            v-if="cardModel.state === 'DRAFT'"
            :loading="editLoading"
            color="negative"
            icon="delete_forever"
            class="q-mr-md"
            :label="$t('services.ServiceCart.delete')"
            type="button"
          />
        </div>
      </div>

      <div class="q-mx-md">
        <div class="q-py-md q-px-lg">
          <base-label-value class="q-pa-xs">
            <template v-slot:label>
              {{ $t('services.ServiceCart.fullName') }}
            </template>
            <template v-slot:value>
              {{ cardModel.fullName }}
            </template>
          </base-label-value>
          <base-label-value
            class="q-pa-xs service-base-label"
            v-if="stateColorMapSet"
          >
            <template v-slot:label>
              {{ $t('services.ServiceCart.state') }}
            </template>
            <template v-slot:value>
              <q-chip
                square
                :color="stateColorMapSet[cardModel.state]"
                size="md"
                dense
                text-color="white"
              >
                {{
                  cardModel.state
                    ? $t(`additionalSettings.${cardModel.state}`)
                    : $t(`additionalSettings.DRAFT`)
                }}
              </q-chip>
            </template>
          </base-label-value>
          <base-label-value
            v-if="card.version"
            class="q-pa-xs service-base-label"
          >
            <template v-slot:label>
              {{ $t('base.version') }}
            </template>
            <template v-slot:value>
              {{ card.version }}
            </template>
          </base-label-value>
        </div>
      </div>
      <q-dialog class="full-width" v-model="dialogDeleteConfim">
        <q-card class="no-shadow full-width">
          <q-card-section>
            <div class="text-h6">
              {{ $t('services.ServiceCart.confirmationMessage') }}
            </div>
          </q-card-section>

          <q-card-actions align="right">
            <q-btn @click="deleteSettings" color="primary" label="Удалить" />
            <q-btn
              color="white"
              text-color="primary"
              outline
              @click="dialogDeleteConfim = false"
              label="Отменить"
            />
          </q-card-actions>
        </q-card>
      </q-dialog>
    </q-card>

    <base-tabs v-if="!loading" :currentTab="tabs.current" :tabs="tabs.list" />
    <q-inner-loading :showing="loading">
      <q-spinner-gears color="primary" size="50px" />
    </q-inner-loading>
  </div>
</template>

<script lang="js">
import ReturnToParentView from '@mixins/ReturnToParentView';
import { SettingsForServiceApi, ServiceApi } from '@openapi/registry-service';
import { notifyError, notifySuccess } from '@utils/notify';
import { USER_SCOPES } from '@constants/entities/Scope';
import cloneDeep from 'lodash/cloneDeep';
import axios from 'axios'

const settingsForServiceApi = new SettingsForServiceApi();
const serviceApi = new ServiceApi();

export default {
  name: 'additional-settings',
  mixins: [ReturnToParentView],
  props: ['common'],
  data() {
    return {
      USER_SCOPES: USER_SCOPES,
      tabs: {
        current: this.common.active,
        list: [],
      },
      state: 'IN_PROCESS',
      cardModel: null,
      editLoading: false,
      dialogDeleteConfim: false,
      modelDump: [],
    }
  },
  computed: {
    unsavedChanges() {
      return (
        this.$store.getters['registryService/additionalSettings/unsavedChanges']
      );
    },
    loading() {
      return (
        this.$store.getters['registryService/additionalSettings/settingsLoading'] || false
      );
    },
    card() {
      return (
        this.$store.getters['registryService/additionalSettings/settingsForServiceCard'] || null
      );
    },
    stateColorMapSet() {
      return this.$store.getters['registryService/additionalSettings/stateColorMapSet'];
    },
  },
  created() {
    this.$store.dispatch('registryService/additionalSettings/setunsavedChanges', '');
    this.init();
  },
  watch: {
    'common.active': function (tab) {
      this.tabs.current = tab;
    },
    card: {
      handler: function (cardState) {
        if (cardState) {
          this.cardModel = cardState;
          if (cardState.state) {
            this.state = cardState.state;
          }
        }
      },

      immediate: true,
      deep: true
    },
    cardModel: {
      handler: function () {
        if (this.unsavedChanges !== '') {
          const item = this.tabs.list.find(e => e.path === this.unsavedChanges)
          item.unsaved = true
        }
      },
    },
  },
  methods: {
    init() {
      this.initTabsList();
      this.initResource();
    },
    async initResource() {
      await this.$store.dispatch('registryService/additionalSettings/getSettingsForServicePersonMeta', {
        id: this.common.id,
        opts: {
          noCommit: this.$route.params.noCommit,
          expand: [
            'settingsforserviceprocess',
            'settingsforservicetemplate',
            'settingsforservicecriteria',
            'settingsforserviceevent'
          ],
        },
      })
    },
    async save() {
      const params = {...this.cardModel}
      if (this.cardModel.settingsforserviceprocess) {
        const processes = this.cardModel.settingsforserviceprocess.map(e => e.id)
        params.settingsforserviceprocess = processes
      }
      if (this.cardModel.settingsforservicetemplate) {
        const templates = this.cardModel.settingsforservicetemplate.map(e => e.id)
        params.settingsforservicetemplate = templates
      }
      if (this.cardModel.settingsforservicecriteria) {
        const criteria = this.cardModel.settingsforservicecriteria
        params.settingsforservicecriteria = criteria.map(e => e.id)
      }
      if (this.cardModel.settingsforserviceevent) {
        const event = this.cardModel.settingsforserviceevent
        params.settingsforserviceevent = event.map(e => e.id)
      }
      // TODO: запроса нет в опенапи и ямле
      await axios.put('/service/registry/service/settings-for-service/update-settings-for-service', params)
        .then(() => {
          this.$store.dispatch(
            'registryService/additionalSettings/setCardForJsonInitial',
            this.cardModel
          );
          this.$store.dispatch('registryService/additionalSettings/setunsavedChanges', '');
          this.initTabsList();
          notifySuccess(this.$t('services.ServiceCart.saveSuccess'))
        })
        .catch((err) => {
          notifyError(err.response.data.message);
        })
    },
    initTabsList() {
      this.tabs.list = [
        {
          name: this.$t('services.Basic.tab'),
          path: 'basic',
          unsaved: false,
          visible: () => this.$AC.haveOneOfScope([
            USER_SCOPES.SOCIAL_SETTINGS_GENERAL_VIEWER,
            USER_SCOPES.SOCIAL_SETTINGS_GENERAL_ADMIN,
          ]),
        },
        {
          name: this.$t('services.ProcessesCard.tab'),
          path: 'processes',
          unsaved: false,
          visible: () => this.$AC.haveOneOfScope([
            USER_SCOPES.SOCIAL_SETTINGS_PRO_ACTIVE_VIEWER,
            USER_SCOPES.SOCIAL_SETTINGS_PRO_ACTIVE_ADMIN,
            USER_SCOPES.SOCIAL_SETTINGS_PAYMENT_VIEWER,
            USER_SCOPES.SOCIAL_SETTINGS_PAYMENT_ADMIN,
          ]),
        },
        {
          name: 'Шаблоны документов',
          path: 'documents_template',
          unsaved: false,
          visible: () => this.$AC.haveOneOfScope([
            USER_SCOPES.SOCIAL_SETTINGS_PAYMENT_VIEWER,
            USER_SCOPES.SOCIAL_SETTINGS_PAYMENT_ADMIN,
          ]),
        },
        {
          name: 'Критерии и события',
          path: 'criteria',
          unsaved: false,
          visible: () => this.$AC.haveOneOfScope([
            USER_SCOPES.SOCIAL_SETTINGS_PRO_ACTIVE_VIEWER,
            USER_SCOPES.SOCIAL_SETTINGS_PRO_ACTIVE_ADMIN,
          ]),
        },
      ];
    },
    goToSettingsList() {
      if(this.unsavedChanges) {
        this.$q.dialog({
          message: 'На странице есть несохраненные изменения. Продолжить?',
          cancel: {
            push: true,
            label: 'Отмена'
          },
          ok: 'ОК',
        })
        .onOk(() => {
          this.returnToParentView('/additional-settings');
        });
      } else {
        this.returnToParentView('/additional-settings');
      }
    },
    async deleteSettings() {
      try {
        await settingsForServiceApi.deleteSettingsForService([this.cardModel.id])
          .then(() => {
            serviceApi.updateService([{id: this.cardModel.serviceId, settingsId: ''}])
            notifySuccess(this.$t('services.ServiceCart.deleteSuccess'));
              this.$router.push({
                path: `/additional-settings`,
              });
          })
      } catch (e) {
        notifyError(e.message.toString());
      }
    },
    goTo(state) {
      this.saveSettings(state);
    },
    async saveSettings(state) {
      this.editLoading = true;
      await this.$store.dispatch('registryService/additionalSettings/updateStatus', (this.cardModel.id))
        .then(() => {
          this.cardModel.state = state;
          this.$nextTick(() => this.$forceUpdate());
        })
        .finally(() => {
          this.editLoading = false;
        });
    },
  },
};
</script>
