<template>
  <div class="manual">
    <div
      class="flex justify-start items-center bg-white q-pa-md q-mt-md q-mx-md rounded-borders"
    >
      <q-btn
        padding="xs"
        class="text-grey-7 q-mr-md"
        color="grey-3"
        icon="arrow_back"
        @click="goToCriteriaList()"
      />
      <span class="text-h5">{{
        $t('criteriaDirectory.creatingNewCriterion')
      }}</span>
    </div>
    <div
      class="q-gutter-y-md row bg-white q-px-lg q-pb-md q-pt-sm q-mt-md q-mx-md rounded-borders"
    >
      <div class="col text-primary q-pa-sm">
        <div class="q-gutter-y-md" :persistent="saving">
          <q-card class="full-width no-shadow">
            <q-form class="full-width no-shadow q-py-md" @submit="submit">
              <div class="row q-qutter-x-md">
                <div class="col">
                  <q-input
                    v-model="model.name"
                    filled
                    :label="$t('criteriaDirectory.name')"
                    :rules="[noEmptyValueRule]"
                  />
                </div>
              </div>
              <div class="row q-qutter-x-md">
                <div class="col">
                  <q-input
                    v-model="model.description"
                    filled
                    :label="$t('criteriaDirectory.description')"
                  />
                </div>
              </div>

              <q-card :bordered="criteriaTypeIsList" class="no-shadow q-my-md">
                <q-card-section
                  :class="[
                    {
                      'q-pa-none': !criteriaTypeIsList,
                      'q-pb-none': criteriaTypeIsList,
                    },
                  ]"
                >
                  <q-select
                    filled
                    v-model="model.type"
                    :options="criteriaTypes"
                    :label="$t('criteriaDirectory.type')"
                    emit-value
                    map-options
                    stack-label
                  />
                </q-card-section>
                <q-slide-transition>
                  <q-card-section v-if="criteriaTypeIsList">
                    <q-select
                      class="q-pb-none"
                      :label="$t('criteriaDirectory.value')"
                      filled
                      v-model="model.values"
                      :rules="[noEmptyValueRule, amountValuesCheck]"
                      use-input
                      use-chips
                      multiple
                      hide-dropdown-icon
                      input-debounce="0"
                      new-value-mode="add"
                    />
                  </q-card-section>
                </q-slide-transition>
              </q-card>

              <q-card bordered class="no-shadow q-my-lg">
                <q-card-section class="justify-between items-start no-wrap">
                  <span class="text-h6">
                    {{ model.processName || 'Процесс' }}
                  </span>
                  <div class="row no-wrap text-no-wrap float-right">
                    <q-btn
                      v-if="!model.processId"
                      flat
                      dense
                      size="16"
                      class="q-ml-sm"
                      color="white"
                      text-color="primary"
                      unelevated
                      icon="attach_file"
                      @click="openDownloadDialog()"
                    >
                      <q-tooltip> Загрузить процесс </q-tooltip>
                    </q-btn>
                    <q-btn
                      v-else
                      flat
                      dense
                      icon="delete"
                      color="white"
                      text-color="negative"
                      class="q-ml-sm"
                      unelevated
                      @click="toggleDeleteConfim"
                    >
                      <q-tooltip> Удалить </q-tooltip>
                    </q-btn>
                  </div>
                </q-card-section>
              </q-card>

              <filters
                class="q-mb-lg"
                :value.sync="initialData.filters"
                @changeFilter="changeFilter"
              />

              <changed-fields
                :value.sync="model.changedFields"
                class="q-mb-lg"
              />

              <div class="row q-qutter-a-md">
                <div class="col q-qutter-y-md">
                  <q-btn
                    class="q-my-md"
                    color="primary"
                    :label="$t('criteriaDirectory.save')"
                    type="submit"
                  />
                  <q-btn
                    v-if="model.processId !== ''"
                    class="q-my-md q-ml-md"
                    color="primary"
                    label="Сохранить и активировать"
                    @click="saveAndActive"
                  />
                  <q-btn
                    class="q-my-md q-mx-md"
                    label="Назад"
                    color="white"
                    text-color="primary"
                    outline
                    @click="returnToParentView('/criteria-directory')"
                  />
                </div>
              </div>
            </q-form>
          </q-card>
        </div>
      </div>
    </div>

    <q-dialog class="full-width" v-model="deleteConfim">
      <q-card class="no-shadow full-width">
        <q-card-section>
          <div class="text-h6">Вы уверены, что хотите удалить процесс?</div>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            @click="
              toggleDeleteConfim();
              unlinkProcess();
            "
            color="primary"
            :label="$t('base.delete')"
          />

          <q-btn
            color="white"
            text-color="primary"
            outline
            @click="toggleDeleteConfim"
            :label="$t('base.undo')"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <DownloadDialog
      :openFormDialog.sync="startDownloadDialog"
      @createData="addFile"
    />
  </div>
</template>

<script lang="ts">
import ReturnToParentView from '@mixins/ReturnToParentView';
import { mixins } from 'vue-class-component';
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import {
  CriteriaApi,
  CriteriaTypeEnum,
  Criteria,
  CriteriaStatusEnum,
} from '@/openapi/personal-accounts';
import { notifyError, notifySuccess } from '@/utils/notify';
import { noEmptyValueRule } from '@utils/field-validation/basic';
import DownloadDialog from '@components/criteria-directory/download_dialog.vue';
import { BaseCardCommon } from '@interfaces/components';
import Filters from './components/Filters.vue';
import ChangedFields from '@components/criteria-directory/components/ChangedFields.vue';
import { cloneDeep, isEqual } from 'lodash';

const criteriaApi = new CriteriaApi();

@Component({
  components: {
    Filters,
    DownloadDialog,
    ChangedFields,
  },
  methods: {
    noEmptyValueRule,
  },
})
export default class createCriteriaCategoryDialog extends mixins(
  ReturnToParentView
) {
  @Prop({}) private common?: BaseCardCommon;
  startDownloadDialog = false;
  deleteConfim = false;
  initialData: Criteria | null = null;
  model: Criteria = {
    schema: 'Criteria',
    name: '',
    type: CriteriaTypeEnum.List,
    values: [],
    status: CriteriaStatusEnum.Draft,
    processId: '',
    processName: '',
    filters: [],
    changedFields: [],
  };

  saving = false;

  criteriaTypes: any = [
    { value: 'BOOLEAN', label: 'Флаг' },
    { value: 'NUMBER', label: 'Числовой ' },
    { value: 'TEXT', label: 'Текстовый' },
    { value: 'LIST', label: 'Список значений' },
  ];

  get criteriaTypeIsList(): boolean {
    return this.model.type === CriteriaTypeEnum.List;
  }

  created() {
    this.initialData = cloneDeep(this.model);
  }

  amountValuesCheck(values: string[]): true | string {
    if (values !== undefined && values.length > 30) {
      return 'Нельзя вносить больше 30ти';
    }
    return true;
  }

  clearModel(): void {
    this.model = {
      schema: 'Criteria',
      name: '',
      description: '',
      type: CriteriaTypeEnum.List,
      values: [],
      status: CriteriaStatusEnum.Draft,
      processId: '',
      processName: '',
      changedFields: [],
    };
  }

  saveAndActive(): void {
    if (!this.model.name) {
      this.$q.notify({
        color: 'negative',
        icon: 'error',
        message: 'Все поля должны быть заполнены',
      });
      return;
    }
    const activate = {
      status: 'ACTIVATED',
      reqCalculation: true,
    };
    this.submit(activate);
  }

  async submit(activate: any): Promise<void> {
    if (activate.status) {
      this.model = { ...this.model, ...activate };
    } else {
      delete this.model.reqCalculation;
      this.model.status = 'DRAFT';
    }
    this.saving = true;
    try {
      const {
        data: { success },
      } = await criteriaApi.createCriteria([this.model], {});
      if (success) {
        notifySuccess('Успешно создано.');
        this.clearModel();
        this.$router.push({ name: 'criteria-directory' });
        this.saving = false;
      }
    } catch (error) {
      if (error instanceof Error) notifyError(error.message);
    }
  }

  addFile(val?: Criteria): void {
    this.startDownloadDialog = false;
    if (val) {
      this.model.processId = val.id;
      this.model.processName = val.name;
    }
  }

  changeFilter(filters: []) {
    this.model.filters = filters;
  }

  openDownloadDialog(): void {
    this.startDownloadDialog = true;
  }

  toggleDeleteConfim(): void {
    this.deleteConfim = !this.deleteConfim;
  }

  async unlinkProcess(): Promise<void> {
    this.model.processId = '';
    this.model.processName = '';
  }

  goToCriteriaList() {
    if (!isEqual(this.model, this.initialData)) {
      this.$q
        .dialog({
          message: 'На странице есть несохраненные изменения. Продолжить?',
          cancel: {
            push: true,
            label: 'Отмена',
          },
          ok: 'ОК',
        })
        .onOk(() => {
          this.returnToParentView('/criteria-directory');
        });
    } else {
      this.returnToParentView('/criteria-directory');
    }
  }
}
</script>

<style lang="scss">
.file-cell {
  white-space: pre-line;
}
.document-card {
  width: 100%;
  max-width: 350px;
}

.create-criteria-validation {
  margin-top: 0;
  font-size: 12px;
  color: #c10015;
}

.grid-item-value {
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
