<template>
  <div class="row q-qutter-x-md">
    <div class="col">
      <q-select
        v-show="!readOnly"
        v-model="changedFieldGuidModel"
        :options="changefieldList"
        option-label="description"
        use-chips
        stack-label
        multiple
        label="Параметры перерасчета критерия"
        filled
      />
      <div v-show="readOnly" class="q-mt-sm q-mb-sm">
        <base-label-value class="base-label q-gutter-x-md">
          <template #label>{{
            $t('criteriaDirectory.changedFields')
          }}</template>
          <template #value>
            {{ changefieldListRead.join(', ') || '-' }}
          </template>
        </base-label-value>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch, PropSync, Prop } from 'vue-property-decorator';
import {
  CriteriaApi,
  ChangedFieldType,
  CriteriaChangedField,
} from '@/openapi/personal-accounts';
import { notifyError } from '@/utils/notify';

const criteriaApi = new CriteriaApi();

@Component({})
export default class CriteriChangedField extends Vue {
  @PropSync('value', { default: () => [] })
  changedFields: CriteriaChangedField[];

  @Prop({ default: false }) readOnly: boolean;

  changedFieldGuidModel: ChangedFieldType[] = [];

  changefieldList: ChangedFieldType[] = [];

  changefieldListRead: string[] = [];

  async getChangedFields(): Promise<void> {
    try {
      const { data } = await criteriaApi.listChangedFields();
      this.changefieldList = data;
      const fieldsIdList = this.changedFields.map(
        (e: CriteriaChangedField) => e.changedFieldGuid
      );

      if (this.changedFields.length) {
        this.changedFieldGuidModel = this.changefieldList.filter((field) => {
          if (field.id) {
            return fieldsIdList.indexOf(field.id) !== -1;
          }
        });
        this.changefieldListRead = this.changedFieldGuidModel.map(
          (e) => e.description
        );
      }
    } catch (error) {
      if (error instanceof Error) notifyError(error.message);
      this.changefieldList = [];
    }
  }

  @Watch('changedFieldGuidModel')
  changedFieldsWatch(): void {
    this.changedFields = this.changedFieldGuidModel.map((e) => ({
      key: e.key || '',
      value: e.value || '',
      changedFieldGuid: e.id || '',
    }));
  }

  created(): void {
    this.getChangedFields();
  }
}
</script>
