<template>
  <div class="col text-primary q-pt-md q-mb-lg">
    <div v-if="!loading">
      <div class="q-gutter-y-md">
        <q-input
          v-model="editModel.shortName"
          filled
          :label="$t('services.BasicCard.shortName')"
        />
        <q-input
          v-model="editModel.fullName"
          disable
          filled
          :label="$t('services.BasicCard.fullName')"
        />
        <q-input
          v-model="editModel.targetId"
          disable
          filled
          :label="$t('services.ServiceCart.targetId')"
        />
        <q-input
          v-model="editModel.petitionType"
          disable
          filled
          :label="$t('services.ServiceCart.petitionType')"
        />
        <q-input
          v-model="serviceIdName"
          disable
          filled
          :label="$t('additionalSettings.serviceId')"
        />
        <q-select
          v-model="editModel.socialSupportMeasureId"
          filled
          :options="measureList"
          :label="$t('additionalSettings.socialSupportMeasure')"
          emit-value
          map-options
        />
        <q-select
          v-model="editModel.registryId"
          filled
          :options="registryList"
          :disable="!registryList.length"
          :label="$t('additionalSettings.registrySolutions')"
          emit-value
          map-options
        />
        <q-checkbox
          v-model="editModel.proActive"
          :label="$t('additionalSettings.proactiveSettings')"
        />
        <div>
          <q-checkbox
            v-model="editModel.paymentSettings"
            :disable="!registryList.length"
            :label="$t('additionalSettings.payoutSettings')"
          />
        </div>
        <q-select
          v-model="editModel.goals"
          :options="goalsList"
          map-options
          use-chips
          multiple
          label="Список целей"
          filled
        />
      </div>

      <div class="q-gutter-y-md q-pb-md q-pt-sm">
        <div class="text-h6">Данные для уведомлений ЕПГУ</div>
        <div class="q-gutter-y-md">
          <q-input
            :disable="
              !$AC.haveOneOfScope([
                USER_SCOPES.SOCIAL_SETTINGS_PRO_ACTIVE_ADMIN,
              ])
            "
            v-model="editModel.guidEPGUtemplate"
            filled
            label="GUID шаблона ЕПГУ"
          />
          <q-input
            :disable="
              !$AC.haveOneOfScope([
                USER_SCOPES.SOCIAL_SETTINGS_PRO_ACTIVE_ADMIN,
              ])
            "
            v-model="editModel.guidEPGUheader"
            filled
            label="Заголовок уведомления ЕПГУ"
          />
          <q-input
            :disable="
              !$AC.haveOneOfScope([
                USER_SCOPES.SOCIAL_SETTINGS_PRO_ACTIVE_ADMIN,
              ])
            "
            :value="editModel.resendingPeriod"
            :rules="[rulesNum]"
            filled
            label="Период автоматической переотправки заявления(дни)"
            @input="changePeriod($event, 'resendingPeriod')"
          />
          <q-input
            :disable="
              !$AC.haveOneOfScope([
                USER_SCOPES.SOCIAL_SETTINGS_PRO_ACTIVE_ADMIN,
              ])
            "
            :value="editModel.allowedResendingPeriod"
            :rules="[rulesNum]"
            filled
            label="Период разрешенной переотправки заявления(дни)"
            @input="changePeriod($event, 'allowedResendingPeriod')"
          />
        </div>
      </div>

      <div class="q-gutter-y-md q-pb-md q-pt-sm">
        <div class="text-h6">Настройки выплат</div>
        <div class="q-gutter-y-md">
          <q-checkbox
            :disable="
              !$AC.haveOneOfScope([USER_SCOPES.SOCIAL_SETTINGS_PAYMENT_ADMIN])
            "
            v-model="editModel.requiresEGISSO"
            label="Требует отправки в ЕГИССО"
          />
          <q-select
            :disable="
              !$AC.haveOneOfScope([USER_SCOPES.SOCIAL_SETTINGS_PAYMENT_ADMIN])
            "
            v-model="editModel.paymentType"
            filled
            option-value="code"
            option-label="value"
            :options="paymentTypes"
            label="Тип выплаты"
            emit-value
            map-options
          />
          <q-select
            :disable="
              !$AC.haveOneOfScope([USER_SCOPES.SOCIAL_SETTINGS_PAYMENT_ADMIN])
            "
            v-model="editModel.paymentPeriod"
            filled
            option-value="code"
            option-label="value"
            :options="paymentPeriods"
            label="Период выплаты"
            emit-value
            map-options
          />
        </div>
      </div>
    </div>

    <q-inner-loading :showing="loading">
      <q-spinner-gears color="primary" size="50px" />
    </q-inner-loading>
  </div>
</template>

<script>
import { USER_SCOPES } from '@constants/entities/Scope';
import { cloneDeep, isEqual, set } from 'lodash';
import { SocialSupportMeasuresApi } from '@openapi/personal-accounts';
import {
  RegistryApi,
  ServiceApi,
  RegistryMappingApi,
} from '@openapi/registry-service';

const socialSupportMeasuresApi = new SocialSupportMeasuresApi();
const registryApi = new RegistryApi();
const serviceApi = new ServiceApi();
const registryMappingApi = new RegistryMappingApi();

export default {
  props: ['common', 'model'],
  data() {
    return {
      USER_SCOPES: USER_SCOPES,
      editModel: {},
      loading: true,
      initialModel: {},
      measureList: [],
      registryList: [],
      goalsList: [],
    };
  },
  computed: {
    serviceIdName() {
      return (
        this.$store.getters[
          'registryService/additionalSettings/setServiceIdName'
        ].fullName || '-'
      );
    },
    paymentPeriods() {
      return (
        this.$store.getters[
          'registryService/additionalSettings/setSettingsDictionary'
        ].DictPaymentPeriodForSettingForService || []
      );
    },
    paymentTypes() {
      return (
        this.$store.getters[
          'registryService/additionalSettings/setSettingsDictionary'
        ].DictPaymentTypeForSettingForService || []
      );
    },
    card() {
      return cloneDeep(
        this.$store.getters['registryService/additionalSettings/settingsForServiceCard']
      );
    },
  },
  watch: {
    editModel: {
      handler(editModel) {
        if (!isEqual(editModel, this.initialModel)) {
          this.$store.dispatch(
            'registryService/additionalSettings/setunsavedChanges',
            'basic'
          );
        }
        this.updateModel();
      },
      deep: true,
      immediate: true,
    },
  },
  async created() {
    this.editModel = cloneDeep(this.card);
    this.initialModel = cloneDeep(this.card);
    await socialSupportMeasuresApi
      .searchSocialSupportMeasures()
      .then((response) => {
        this.measureList = response.data.map((e) => ({
          value: e.id,
          label: e.name,
        }));
      });

    await registryMappingApi
      .pagingRegistryMapping(
        undefined,
        undefined,
        `serviceId==${this.editModel.serviceId}`
      )
      .then((response) => {
        if (response.data && response.data.records.length) {
          const records = response.data.records.map((e) => e.registryCode);
          registryApi
            .pagingRegistry(undefined, undefined, `code =in= (${records})`)
            .then((regisrties) => {
              if (regisrties.data && regisrties.data.records.length) {
                this.registryList = regisrties.data.records.map((e) => ({
                  value: e.id,
                  label: e.name,
                }));
              }
            });
        }
      });

    await serviceApi
      .getService(this.editModel.serviceId)
      .then((response) => {
        this.goalsList = response.data.goalsList;
      })
      .finally(() => {
        this.loading = false;
      });
  },
  methods: {
    updateModel() {
      this.$store.dispatch(
        'registryService/additionalSettings/setCardForJson',
        {...this.card, ...this.editModel}
      );
    },
    changePeriod(valueString, field) {
      const value = parseInt(valueString);
      set(this.editModel, field, isNaN(value) ? 0 : value);
    },
    rulesNum(value) {
      return (
        /^(?!-|0[0-9])[0-9]+$/.test(value.toString()) ||
        'Введите целое положительное количество дней'
      );
    },
  },
};
</script>
