<template>
  <operation-dialog
    persistent
    sign
    ref="dialog"
    :title="organizationName"
    sub="Создание подразделения"
    v-model="opened"
    @hide="$emit('close')"
    class="CreateModalForm"
  >
    <div>
      <r-input
        class="CreateModalForm__Field"
        label="Полное название подразделения*"
        v-model="department.fullname"
        validate-on-blur
        :rules="[(val) => !isEmptyVal(val) || 'Обязательное поле']"
      />
      <r-input
        class="CreateModalForm__Field"
        label="Сокращённое название подразделения*"
        validate-on-blur
        v-model="department.shortname"
        :rules="[(val) => !isEmptyVal(val) || 'Обязательное поле']"
      />
      <r-input
        class="CreateModalForm__Field"
        label="Код военного комиссариата"
        v-model="department.militaryCode"
        :rules="[
          (val) =>
            !val || val.match(/^[0-9]{8}$/) || 'Должен состоять из 8 цифр',
        ]"
      />
      <r-input
        class="CreateModalForm__Field"
        label="Часовой пояс"
        v-model="department.timezone"
        :rules="[
          (val) => !val || rulesTimezone(val) || 'Должен быть в формате +01:30',
        ]"
      />
      <div class="CreateModalForm__Field">
        <span class="CreateModalForm__FieldLabel">Адрес подразделения</span>
        <BasicMAddressComponent
          :id.sync="department.addressId"
          :value.sync="department.address"
          filled
          dense
          options-dense
          dropdown-icon="pgs-shevron-down-off"
          :showManualEnter="false"
        />
      </div>
      <div class="CreateModalForm__Field">
        <span class="CreateModalForm__FieldLabel">
          Почтовый адрес подразделения
        </span>
        <BasicMAddressComponent
          :id.sync="department.postalAddressId"
          :value.sync="department.postalAddress"
          filled
          dense
          options-dense
          dropdown-icon="pgs-shevron-down-off"
          :showManualEnter="false"
        />
      </div>
      <r-input
        class="CreateModalForm__Field"
        label="Адрес электронной почты"
        v-model="department.email"
        type="email"
      >
        <template v-slot:icon>
          <q-icon name="email" />
        </template>
      </r-input>
      <div class="CreateModalForm__Field">
        <span class="CreateModalForm__FieldLabel">Телефон</span>
        <q-input
          fill-mask
          filled
          dense
          mask="+7 (###) ###-##-##"
          unmasked-value
          v-model="department.phone"
        >
          <template v-slot:prepend>
            <q-icon name="phone" />
          </template>
        </q-input>
      </div>
      <div class="CreateModalForm__Field">
        <q-toggle
          v-model="department.reportsEnabled"
          :label="
            department.reportsEnabled
              ? 'Включать в отчеты'
              : 'Исключать из отчетов'
          "
        />
      </div>
    </div>
    <template #process>
      <result-block
        header="Создание подразделения"
        icon="pgs-document"
        type="info"
      />
    </template>
    <template #result>
      <result-block :header="resultMessage" :type="resultType" />
    </template>
    <template #left-actions-panel>
      <r-btn
        outline
        label="Закрыть"
        icon="pgs-close"
        color="primary"
        @click="$emit('close')"
      />
    </template>
    <template #right-actions-panel>
      <r-btn
        v-if="operationDialog && operationDialog.formState === 'start'"
        outline
        label="Сохранить"
        icon="pgs-save"
        positive
        :disable="!validateForm"
        @click="submit"
      />
    </template>
  </operation-dialog>
</template>

<script lang="ts">
import { Component, Prop, Mixins, Watch, Ref } from 'vue-property-decorator';
import { OrganizationWithParent } from '@/models/OrganizationWithParent';
import RInput from '@/recruits/components/common/r-input/index.vue';
import RSelect from '@/recruits/components/common/r-select.vue';
import BasicMAddressComponent from '@components/m-address/index.vue';
import { Department } from '@openapi/idm';
import get from 'lodash/get';
import ProcessStarter from '@/mixins/ProcessStarter';
import OperationDialog from '@/components/common/operation-dialog/index.vue';
import { v4 } from 'uuid';
import isString from 'lodash/isString';

@Component({
  components: {
    RInput,
    RSelect,
    BasicMAddressComponent,
  },
})
export default class CreateDepartmentModal extends Mixins(ProcessStarter) {
  @Prop({ default: null }) organization: OrganizationWithParent | null;
  @Prop({ default: 'milBaseCreateDepartmentIDMProcess' })
  declare processKey: string;

  @Ref('dialog') operationDialog: OperationDialog;

  loading = false;
  opened = false;

  department: Department = {
    id: '',
    shortname: '',
    fullname: '',
    militaryCode: '',
    timezone: '',
    addressId: '',
    address: '',
    postalAddress: '',
    postalAddressId: '',
    email: '',
    phone: '',
    dns: '',
    name: '',
    tnsDepartmentId: '',
    reportsEnabled: true,
  };

  get organizationName(): string {
    return (
      this.organization?.fullname ||
      this.organization?.shortname ||
      this.organization?.name ||
      ''
    );
  }

  resultType: 'positive' | 'negative' | '' = '';
  resultMessage = '';

  @Watch('organization')
  private async organizationHandler(): Promise<void> {
    // organizationHandler приходит null - значит надо закрыть окно
    this.opened = false;
    this.resultType = '';
    this.clearForm();

    this.operationDialog.reset();
    if (!this.organization?.id) return;
    this.opened = true;
  }

  clearForm(): void {
    this.department.id = v4();
    this.department.shortname = '';
    this.department.fullname = '';
    this.department.militaryCode = '';
    this.department.timezone = '';
    this.department.addressId = '';
    this.department.address = '';
    this.department.postalAddress = '';
    this.department.postalAddressId = '';
    this.department.email = '';
    this.department.phone = '';
    this.department.dns = '';
    this.department.name = '';
    this.department.tnsDepartmentId = '';
    this.department.reportsEnabled = true;
  }

  rulesTimezone(timezone: string): string | boolean {
    const regex = /^[+|-]((0[0-9]|1[0-1]):([0-5][0-9])|12:00)$/;
    const regexMinusZero = /^-00:00$/;
    return regex.test(timezone) && !regexMinusZero.test(timezone);
  }

  isEmptyVal(val: string | null): boolean {
    return isString(val) ? !val.trim().length : true;
  }

  removeSpaces(val: string): string {
    return val.trim().replace(/ {1,}/g, ' ');
  }

  get validateForm(): boolean {
    return (
      !this.isEmptyVal(this.department.fullname) &&
      !this.isEmptyVal(this.department.shortname) &&
      (!this.department.militaryCode?.length ||
        !!this.department.militaryCode.match(/^[0-9]{8}$/)) &&
      (!this.department.timezone?.length ||
        !!this.rulesTimezone(this.department.timezone))
    );
  }

  async submit(): Promise<void> {
    if (this.validateForm && this.organization?.id) {
      this.operationDialog.toProcess();
      const dataObject: {
        department: Department;
        organizationId: string;
      } = {
        department: {
          id: this.department.id,
          shortname: this.removeSpaces(this.department.shortname),
          fullname: this.removeSpaces(this.department.fullname),
          timezone: this.department.timezone,
          addressId: this.department.addressId,
          address: this.department.address,
          postalAddress: this.department.postalAddress,
          postalAddressId: this.department.postalAddressId,
          email: this.department.email,
          phone: this.department.phone,
          dns: '',
          name: this.department.fullname,
          tnsDepartmentId: '',
          reportsEnabled: this.department.reportsEnabled,
          militaryCode: this.department.militaryCode || 'emptyValue',
        },
        organizationId: this.organization.id,
      };

      try {
        const traceId = await this.startProcess({
          ...dataObject,
        });

        this.registerListener((message, removeListener) => {
          if (traceId !== message.traceId) return;
          if (message?.body?.type === 'finish') {
            this.resultType = 'positive';
            this.resultMessage = 'Подразделение успешно создано';
            removeListener();
            this.$emit('refresh');
          }

          if (message?.body?.type === 'error') {
            this.resultType = 'negative';
            // get т.к. message может быть Task | PushMessage, а в Task нет поля msg
            this.resultMessage = get(
              message,
              'body.msg.message',
              'Произошла непредвиденная ошибка'
            );
            removeListener();
          }
        });
      } catch (error: any) {
        this.resultType = 'negative';
        this.$q.notify({
          message: error.message,
          color: 'negative',
        });
      } finally {
        this.operationDialog.toResult();
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.CreateModalForm {
  &__FieldLabel {
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    display: inline-block;
    cursor: pointer;
    font-size: 12px;
    line-height: 16px;
    margin-bottom: 4px;
    font-weight: 600;
    color: rgba(2, 12, 18, 0.58);
    transition: 0.3s;
  }

  &__Field {
    margin-bottom: 15px;
    &::v-deep {
      .q-field--with-bottom {
        padding-bottom: 0;
      }

      .q-field--auto-height .q-field__control {
        background: #e5edf5;
        border-bottom: 1px solid rgba(1, 72, 116, 0.18);
        padding: 0 8px;
      }

      .q-field--filled.q-field--highlighted .q-field__control:before {
        opacity: 0;
      }

      .q-field--filled .q-field__control:after {
        height: 0;
      }

      .q-field--focused {
        &.q-field--filled .q-field__control {
          background: white;
          border: 1px solid #0148742e;
        }
      }

      .q-field--filled .q-field__control {
        background: #e5edf5;
        // border-bottom: 1px solid rgba(1, 72, 116, 0.18);
      }
    }
  }

  &__FieldIcon {
    cursor: pointer;
  }
}
</style>
