<template>
  <q-dialog v-model="settingsDialog" persistent>
    <q-card class="full-width no-shadow" style="max-width: 800px">
      <q-form ref="correctionsForm" @submit="confirmSaveSettings">
        <q-card-section>
          {{ $t('services.ServiceCart.createSettingsTitle') }}
        </q-card-section>
        <q-card class="full-width no-shadow" style="max-width: 800px">
          <q-form ref="form">
            <q-card-section>
              <q-input
                :label="$t('services.ServiceCart.settingsDialogInput')"
                v-model="createModel.shortName"
                filled
                :rules="[validateRequired]"
              />
              <q-select
                :key="createModel.paymentSettings"
                v-model="createModel.goals"
                :options="cardModel.goalsList"
                :disable="!cardModel.goalsList"
                :rules="[isNotEmpty]"
                map-options
                use-chips
                multiple
                :label="$t('services.ServiceCart.settingsDialogGoals')"
                filled
              />
              <q-select
                class="q-field--with-bottom"
                v-model="createModel.socialSupportMeasureId"
                :options="measureList"
                :disable="!measureList.length"
                option-label="name"
                option-value="id"
                emit-value
                map-options
                :label="$t('services.ServiceCart.settingsDialogMeasure')"
                filled
              />
              <q-select
                v-model="createModel.registryId"
                :options="registryList"
                :disable="!registryList.length"
                :rules="[isNotEmptyRegistry]"
                option-label="name"
                option-value="id"
                emit-value
                map-options
                :label="$t('services.ServiceCart.settingsDialogRegisrty')"
                filled
              />
              <q-checkbox
                v-model="createModel.proActive"
                :label="$t('services.ServiceCart.settingsDialogProactive')"
              />
              <div></div>
              <q-checkbox
                v-model="createModel.paymentSettings"
                :disable="!registryList.length"
                :label="$t('services.ServiceCart.settingsDialogPayment')"
              />
            </q-card-section>
          </q-form>
        </q-card>
        <q-card-actions align="right">
          <q-btn
            type="button"
            color="primary"
            :label="$t('registries.objectCard.cancel')"
            @click="cancelSave"
          />
          <q-btn
            type="submit"
            icon="create"
            :loading="saving"
            :label="$t('base.actions.save')"
            color="primary"
          >
            <template #loading>
              <q-spinner-gears />
            </template>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script lang="js">
import { RegistryMappingApi, RegistryApi, ServiceApi, SettingsForServiceApi } from '@openapi/registry-service';
import { SocialSupportMeasuresApi } from '@openapi/personal-accounts';
import { notifyError, notifySuccess } from '@utils/notify';
import { isEqual, cloneDeep } from 'lodash';

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

export default {
  name: 'SettingsDialog',
  props: ['cardModel'],
  data() {
    return {
      settingsDialog: false,
      measureList: [],
      registryList: [],
      createModel: {
        shortName: '',
        goals: [],
        socialSupportMeasureId: '',
        registryId: '',
        proActive: false,
        paymentSettings: false,
      },
      createModelDouble: {},
      saving: false,
    }
  },
  methods: {
    async createSettings() {
      this.createModel.shortName = this.cardModel.shortName
      if(this.cardModel.goalsList && this.cardModel.goalsList.length) {
        this.createModel.goals = this.cardModel.goalsList.length === 1 ? [this.cardModel.goalsList[0]] : []
      }
      await socialSupportMeasuresApi.pagingSocialSupportMeasures()
        .then(response => {
          if(response.data && response.data.records.length) {
            this.measureList = response.data.records.map(e => ({
              name: `${e.code} - ${e.name}`,
              id: e.id
            }))
            this.createModel.socialSupportMeasureId = this.checkLength(this.measureList)
          }
        })
      await registryMappingApi.pagingRegistryMapping(undefined, undefined, `serviceId==${this.cardModel.id}`)
        .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(response => {
                if(response.data && response.data.records.length) {
                  this.registryList = response.data.records
                  this.createModel.registryId = this.checkLength(this.registryList)
                  this.$nextTick(() => this.$forceUpdate());
                  this.createModelDouble = cloneDeep(this.createModel)
                }
              })
          }
          this.createModelDouble = cloneDeep(this.createModel)
        })
      this.settingsDialog = true;
    },

    checkLength(list) {
      return list.length === 1 ? list[0].id : '';
    },
    validateRequired(val) {
      return !!val || this.$t('registries.fieldIsRequired').toString();
    },
    isNotEmpty(val) {
      return !val.length && this.createModel.paymentSettings === true ? this.$t('registries.fieldIsRequired').toString() : true;
    },
    isNotEmptyRegistry(val) {
      return !val.length && this.registryList.length === true ? this.$t('registries.fieldIsRequired').toString() : true;
    },

    confirmSaveSettings() {
      this.$q
        .dialog({
          title: this.$t('registries.objectCard.save'),
          message: this.$t('registries.objectCard.saveInfo'),
          cancel: true,
        })
        .onOk(() => {
          this.saveSettings();
        });
    },
    async saveSettings() {
      this.saving = true;
      const { fullName, targetId, petitionType, id } = { ...this.cardModel }
      const params = [{
        state: 'DRAFT',
        version: '1.0',
        fullName,
        targetId,
        petitionType,
        serviceId: id,
        ...this.createModel
      }]
      await settingsForServiceApi.saveSettingsForService(params)
        .then(response => {
          console.log(response);
          serviceApi.updateService([{id: response.data.document.serviceId, settingsId: response.data.document.id}])
            .then(() => {
              notifySuccess(this.$t('services.ServiceCart.settingsDialogSuccess'));
              this.confirmСancelSave();
              this.$emit('init');
            })
            .catch((e) => {
              notifyError(e.message.toString());
            })
        })
        .catch((e) => {
          notifyError(e.message.toString());
        })
        .finally(() =>{
          this.saving = false
        })
    },

    cancelSave() {
      if(isEqual(this.createModelDouble, this.createModel)) {
        this.confirmСancelSave();
      } else {
        this.$q.dialog({
          title: this.$t('services.ServiceCart.settingsDialogCancel'),
          message: this.$t('services.ServiceCart.settingsDialogNosave'),
          ok: this.$t('base.actions.save'),
          cancel: {
            push: true,
            label:  this.$t('services.ServiceCart.settingsСancelSave')
          },
        })
        .onCancel(() => {
          this.confirmСancelSave();
        })
        .onOk(() => {
          this.saveSettings();
        });
      }
    },
    confirmСancelSave() {
      this.settingsDialog = false
      this.createModel = {
        shortName: '',
        goals: [],
        socialSupportMeasureId: '',
        registryId: '',
        proActive: false,
        paymentSettings: false,
      }
    },
  },
}
</script>
