<template>
  <div v-if="editModel" class="q-gutter-y-md q-mt-md">
    <div class="q-gutter-y-md">
      <q-expansion-item
        :default-opened="editModel.notificationEmails && editModel.notificationEmails.length"
      >
        <template #header>
          <q-item-section>
            <b>{{ $t('services.ServiceCart.notificationEmail') }}</b>
          </q-item-section>
        </template>
        <NotificationEmailsEditor
          class="q-mt-md"
          :emails.sync="editModel.notificationEmails"
        />
      </q-expansion-item>

      <q-input
        v-model="editModel.fullName"
        filled
        :label="$t('services.ServiceCart.fullName')"
        :readonly="editModel.kcrImport"
      />

      <q-input
        v-model="editModel.shortName"
        filled
        :label="$t('services.ServiceCart.shortName')"
        :readonly="editModel.kcrImport"
      />

      <q-input
        v-model="editModel.name"
        filled
        :label="$t('services.ServiceCart.code')"
      />

      <q-input
        v-model="editModel.petitionType"
        filled
        :label="$t('services.ServiceCart.petitionType')"
      />

      <q-input
        v-model="editModel.targetId"
        filled
        :label="$t('services.ServiceCart.targetId')"
      />

      <q-input
        v-model="editModel.epguFromTag"
        filled
        :label="$t('services.ServiceCart.epguFromTag')"
      />

      <q-input
        v-model="editModel.epguToTag"
        filled
        :label="$t('services.ServiceCart.epguToTag')"
      />

      <q-input
        v-model="editModel.numberPrefix"
        filled
        :label="$t('services.ServiceCart.numberPrefix')"
      />

      <div v-if="editModel.authority" class="q-gutter-y-md">
        <q-input
          v-model="editModel.authority.fullName"
          filled
          :label="$t('services.BasicCard.fullName')"
          :readonly="editModel.kcrImport"
        />

        <q-input
          v-model="editModel.authority.ogrn"
          filled
          :label="$t('services.BasicCard.ogrn')"
          :readonly="editModel.kcrImport"
        />
      </div>

      <q-select
        v-model="editModel.servicePresentation"
        filled
        :options="serviceLevelsList"
        :label="$t('services.BasicCard.servicePresentation')"
        :readonly="editModel.kcrImport"
        emit-value
        map-options
      />

      <q-list class="bg-grey-2">
        <q-expansion-item>
          <template #header>
            <q-item-section>
              <b>{{ $t('services.BasicCard.legalActs') }}</b>
            </q-item-section>
          </template>

          <q-card class="bg-grey-2">
            <q-card-section v-if="editModel.legalActs" class="q-gutter-y-md">
              <div
                v-for="(act, i) in editModel.legalActs"
                :key="`legal-act-${i}`"
              >
                <q-input
                  :key="`legal-act-${i}`"
                  v-model="act.value"
                  filled
                  bg-color="white"
                  :readonly="editModel && editModel.kcrImport"
                  type="textarea"
                >
                  <template v-if="!(editModel && editModel.kcrImport)" #before>
                    <q-btn
                      dense
                      color="grey-2"
                      text-color="primary"
                      icon="delete"
                      class="q-ml-auto"
                      @click="deleteField('legalActs', act)"
                    />
                  </template>
                </q-input>
              </div>
            </q-card-section>
            <q-card-actions align="right">
              <q-btn
                v-if="!editModel.kcrImport"
                color="primary"
                label="Добавить запись"
                @click="addEmptyField('legalActs')"
              />
            </q-card-actions>
          </q-card>
        </q-expansion-item>
      </q-list>

      <q-list class="bg-grey-2">
        <q-expansion-item>
          <template #header>
            <q-item-section>
              <b>{{ $t('services.BasicCard.healthStatus') }}</b>
            </q-item-section>
          </template>
          <q-card class="bg-grey-2">
            <q-card-section v-if="editModel.healthStatus" class="q-gutter-y-md">
              <div
                v-for="(act, i) in editModel.healthStatus"
                :key="`status-${i}`"
              >
                <q-input
                  v-model="act.value"
                  filled
                  :readonly="editModel && editModel.kcrImport"
                  bg-color="white"
                >
                  <template v-if="!(editModel && editModel.kcrImport)" #before>
                    <q-btn
                      dense
                      color="grey-2"
                      text-color="primary"
                      icon="delete"
                      class="q-ml-auto"
                      @click="deleteField('healthStatus', act)"
                    />
                  </template>
                </q-input>
              </div>
            </q-card-section>
            <q-card-actions align="right">
              <q-btn
                v-if="!editModel.kcrImport"
                color="primary"
                label="Добавить запись"
                @click="addEmptyField('healthStatus')"
              />
            </q-card-actions>
          </q-card>
        </q-expansion-item>
      </q-list>

      <q-list class="bg-grey-2">
        <q-expansion-item>
          <template #header>
            <q-item-section>
              <b>{{ $t('services.BasicCard.scope') }}</b>
            </q-item-section>
          </template>
          <q-card class="bg-grey-2">
            <q-card-section v-if="editModel.scope" class="q-gutter-y-md">
              <div v-for="(act, i) in editModel.scope" :key="`scope-${i}`">
                <q-input
                  v-model="act.value"
                  :readonly="editModel && editModel.kcrImport"
                  filled
                  bg-color="white"
                >
                  <template v-if="!(editModel && editModel.kcrImport)" #before>
                    <q-btn
                      dense
                      color="grey-2"
                      text-color="primary"
                      icon="delete"
                      class="q-ml-auto"
                      @click="deleteField('scope', act)"
                    />
                  </template>
                </q-input>
              </div>
            </q-card-section>
            <q-card-actions align="right">
              <q-btn
                v-if="!editModel.kcrImport"
                color="primary"
                label="Добавить запись"
                @click="addEmptyField('scope')"
              />
            </q-card-actions>
          </q-card>
        </q-expansion-item>
      </q-list>

      <q-checkbox
        v-model="editModel.checkListIsMandatory"
        :label="$t('services.BasicCard.checkListIsMandatory')"
      />
      <div>
        <q-checkbox class="db" v-model="editModel.hasSDD" :label="'hasSDD'" />
      </div>
      <div v-if="editModel.hasSDD">
        {{ `${$t('services.BasicCard.incomeConfigurationLocation')} ${$t('services.Income.tab')} `}}
      </div>
      <q-checkbox
        v-model="editModel.includeReception"
        :label="$t('services.ServiceCart.addToOchn')"
      />

      <ServicesBasicItemsList
        :header-label="$t('services.ServicesBasicGoalsList.header')"
        :column-value-label="$t('services.ServicesBasicGoalsList.column.value')"
        :column-label-label="$t('services.ServicesBasicGoalsList.column.label')"
        :button-add-label="$t('services.ServicesBasicGoalsList.btn.add')"
        :validation-label="
          $t('services.ServicesBasicGoalsList.validation.label')
        "
        :validation-value-label="
          $t('services.ServicesBasicGoalsList.validation.value')
        "
        :edit-mode="true"
        :items.sync="editModel.goalsList"
      />
      <ServicesBasicItemsList
        :header-label="$t('services.ServicesBasicSubjectsList.header')"
        :column-value-label="
          $t('services.ServicesBasicSubjectsList.column.value')
        "
        :column-label-label="
          $t('services.ServicesBasicSubjectsList.column.label')
        "
        :button-add-label="$t('services.ServicesBasicSubjectsList.btn.add')"
        :validation-label="
          $t('services.ServicesBasicSubjectsList.validation.label')
        "
        :validation-value-label="
          $t('services.ServicesBasicSubjectsList.validation.value')
        "
        :edit-mode="true"
        :items.sync="editModel.subjectsList"
      />
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import { QSelectOption } from '@/models/models-ui';
import cloneDeep from 'lodash/cloneDeep';
import type { ExtendedService } from './types/services-types';
import ServicesBasicItemsList from './components/ServicesBasicItemsList.vue';
import { BaseCardCommon } from '@/interfaces';
import SddConstructor from '@components/cards/services/components/sdd-constructor/SddConstructor.vue';
import NotificationEmailsEditor from './components/NotificationEmailsEditor.vue';

@Component({
  components: {
    SddConstructor,
    ServicesBasicItemsList,
    NotificationEmailsEditor,
  },
})
export default class ServicesBasicEditCard extends Vue {
  @Prop() common: BaseCardCommon;
  @Prop() model: ExtendedService;

  editModel: ExtendedService | null = null;

  emptyField = {
    value: '',
  };

  created(): void {
    this.editModel = cloneDeep(this.model);
    if (!this.editModel.notificationEmails?.length) {
      this.editModel.notificationEmails = [];
    }
  }

  @Watch('editModel', { deep: true, immediate: true })
  onModelChange() {
    this.updateModel();
  }

  get toggleBtnOptions(): QSelectOption[] {
    return [
      {
        label: this.$t('services.BasicCard.jsonEditorMode') as string,
        value: true,
      },
      {
        label: this.$t('services.BasicCard.formMode') as string,
        value: false,
      },
    ];
  }

  // todo статусы
  get states(): QSelectOption[] {
    return [
      {
        label: 'Черновик',
        value: 'draft',
      },
      {
        label: 'В работе',
        value: 'inProgress',
      },
      {
        label: 'Готова к подписанию',
        value: 'readyToPublish',
      },
      {
        label: 'Подписана',
        value: 'signed',
      },
      {
        label: 'Опубликована',
        value: 'published',
      },
    ];
  }

  // territorial_levels dictionary
  get serviceLevelsList(): string[] {
    return ['Федеральный', 'Региональный', 'Муниципальный'];
  }

  addEmptyField(attr: 'legalActs' | 'healthStatus' | 'scope') {
    if (!this.editModel) return;

    if (!this.editModel[attr]) {
      this.editModel[attr] = [];
    }

    // @ts-ignore todo typings
    this.editModel[attr].push(cloneDeep(this.emptyField));

    this.updateModel();
  }

  deleteField<KeyOfService extends keyof ExtendedService>(
    attr: KeyOfService,
    item: ExtendedService[KeyOfService]
  ): void {
    if (!this.editModel) return;

    // @ts-ignore todo typings
    this.editModel[attr] = this.editModel[attr].filter(
      (entry: ExtendedService[KeyOfService]) => entry !== item
    );

    this.updateModel();
  }

  updateModel(): void {
    this.$store.dispatch(
      'registryService/services/setCardForJson',
      this.editModel
    );
  }
}
</script>
