<template>
  <div :class="{ invisible: hidden }">
    <slot name="button" v-bind="{ open }">
      <r-btn
        dense
        negative
        :disable="disable"
        label="Отказать"
        @click="open"
        no-wrap
      />
    </slot>
    <operation-dialog
      persistent
      ref="dialog"
      :title="title"
      :process-key="processKey"
      v-model="opened"
      @hide="close"
    >
      <q-form
        ref="form"
        class="q-gutter-md CreateDecision-Form"
        :greedy="true"
        no-error-focus
        @submit.prevent
      >
        <div class="CreateDecision-FormLine">
          <em>Тип решения</em>
          <q-select
            v-model.trim="formModel.type"
            emit-value
            map-options
            borderless
            :rules="[rules.required]"
            option-value="code"
            option-label="value"
            dense
            :options="decisionTypes"
            class="r-select"
          >
            <template v-slot:selected-item="scope">
              <div class="ellipsis r-select-text">
                {{ scope.opt.value }}
              </div>
            </template>
          </q-select>
        </div>
        <div class="CreateDecision-FormLine">
          <em>Номер решения</em>
          <q-input
            v-model.trim="formModel.decisionNumber"
            :rules="[rules.required, rules.strings]"
            dense
            borderless
          />
        </div>
        <div class="CreateDecision-FormLine">
          <em>Дата решения</em>
          <x-date-input
            :value="unformatDate(formModel.date)"
            :rules="[rules.required, rules.date, dateRangeRule]"
            :options="datePickerOptions"
            :raw-value="true"
            hide-bottom-space
            @input="formModel.date = formatDate($event)"
          />
        </div>
      </q-form>
      <template #process>
        <result-block type="info" header="Решение добавляется">
          {{ fileName }}
        </result-block>
      </template>
      <template #result>
        <result-block :type="resultType" :header="resultMessage">
          Решение добавлено!
        </result-block>
      </template>
      <template #right-actions>
        <r-btn
          action
          label="Добавить"
          icon="pgs-edit"
          :disable="disable"
          @click="startProcess"
        />
      </template>
      <template #right-actions-result>
        <r-btn
          action
          label="Продолжить"
          icon-right="pgs-shevron-right-off"
          @click="finish"
        />
      </template>
    </operation-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Mixins, Watch, Prop, Ref } from 'vue-property-decorator';
import OperationDialog from '@/components/common/operation-dialog/index.vue';
import { notifyError } from '@/utils/notify';
import CryptoProSignForm from '@/components/common/cryptopro-sign-form/index.vue';
import RSelect from '@/recruits/components/common/r-select.vue';
import RInput from '@/recruits/components/common/r-input.vue';
import moment from 'moment/moment';
import ProcessStarter from '@mixins/ProcessStarter';
import XDateInput from '@/recruits/components/common/x-date-input.vue';
import { VALIDATION_RULES } from '@/recruits/utils/validation-rules';
import {
  formatDate,
  unformatDate,
  getCurrentDate,
} from '@/utils/field-validation/dates';
import { DecisionDocumentServiceApi } from '@/recruits/openapi/decision-document';

type FormModel = Record<string | symbol, unknown>;

interface ModelData extends FormModel {
  type: string;
  date: string;
  decisionNumber: string;
}

@Component({
  components: {
    RSelect,
    RInput,
    XDateInput,
    OperationDialog,
    CryptoProSignForm,
  },
  methods: {
    moment,
    formatDate,
    unformatDate,
  },
})
export default class CreateDecision extends Mixins(ProcessStarter) {
  @Prop({ default: false })
  hidden: boolean;

  @Prop({ default: [] })
  decisionTypes: { code: string; value: string }[];

  @Ref('dialog') operationDialog: OperationDialog;

  public rules = VALIDATION_RULES;
  public dateRangeRule = this.rules.dateRange({
    to: getCurrentDate(),
  });

  public datePickerOptions = (dt: string): boolean => {
    return this.dateRangeRule(dt.replace(/\//g, '-')) === true;
  };

  public opened = false;
  public disable = true;

  // public userId = this.$route.params.id;

  public formModel: ModelData = {
    type: '',
    date: '',
    decisionNumber: '',
  };

  public loading = false;
  public isErrorSign = false;

  get resultMessage(): string {
    return this.isErrorSign ? 'Произошла ошибка' : 'Заявление отклонено';
  }

  get resultType(): string {
    return this.isErrorSign ? 'negative' : 'positive';
  }

  get title(): string {
    return 'Внесение реквизитов решений комиссии';
  }

  getNowDate(): string {
    return formatDate(new Date().toString());
  }

  // @ts-ignore
  async startProcess(): Promise<void> {
    const validationResult = await (this.$refs
      ?.form as HTMLFormElement)?.validate();
    if (!validationResult) return;
    try {
      this.loading = true;
      const payload = {
        type: this.formModel.type,
        number: this.formModel.decisionNumber,
        dateDecision: this.formModel.date + ' 00:00:00',
      };
      const decisionDocumentServiceApi = new DecisionDocumentServiceApi();
      const userId = this.$route.params.id;
      try {
        const {
          data,
        } = await decisionDocumentServiceApi.addCommissionDecisionV1(
          userId,
          payload
        );
        if (data) {
          this.finish();
        }
      } catch (e) {
        console.log(e);
      }
    } catch (error) {
      if (error instanceof Error) notifyError(error.message);
      this.showResult(true);
    }
  }

  showResult(isError = false): void {
    this.isErrorSign = isError;
    this.operationDialog.toResult();
  }

  finish(): void {
    this.close();
    this.$emit('done');
  }

  open(): void {
    this.formModel = {
      decisionNumber: '',
      date: '',
      type: '',
    };
    this.opened = true;
  }

  close(): void {
    this.$emit('close');
    this.opened = false;
  }

  @Watch('formModel', {
    immediate: true,
    deep: true,
  })
  async onFormChange(): Promise<void> {
    await this.$nextTick();
    this.disable = !(await (this.$refs?.form as HTMLFormElement)?.validate());
  }
}
</script>

<style lang="scss" scoped>
.CreateDecision {
  &-Form {
    display: flex;
    flex-direction: column;
  }
  &-FormLine {
    min-height: 84px;
    em {
      font-family: 'Golos Text', sans-serif;
      font-style: normal;
      font-weight: 600;
      font-size: 12px;
      line-height: 16px;
      color: rgba(2, 12, 18, 0.58);
      margin-bottom: 4px;
    }

    ::v-deep .q-field {
      width: 100%;
    }

    ::v-deep .q-select {
      .q-field__bottom {
        bottom: -10px;
      }
    }

    ::v-deep .q-field__control {
      input {
        padding: 0 8px;
      }
      &:focus-within {
        background-color: white;
        box-shadow: inset 0 0 2px rgba(15, 104, 160, 0.87);
        border-color: #1487cf;
      }
      padding: 0 8px !important;
      background-color: #e5edf5;
      border-radius: 4px 4px 0 0;
      background-blend-mode: multiply;
      border-bottom: 1px solid rgba(1, 72, 116, 0.18);
    }
  }
}

.r-select-label {
  font-family: 'Golos Text', sans-serif;
  font-style: normal;
  font-weight: 600;
  font-size: 12px;
  line-height: 16px;
  color: rgba(2, 12, 18, 0.58);
  margin-bottom: 4px;
}
.r-select {
  background: #e5edf5;
  border-radius: 4px 4px 0 0;
  background-blend-mode: multiply;
  border: none;
  border-bottom: 1px solid rgba(1, 72, 116, 0.18);
  padding: 8px 0;
  box-sizing: border-box;
  transition: 0.1s;
  height: 40px;

  &-text {
    max-width: 83%;
  }
}
</style>
