<i18n>
{
    "en": {
        "EmployeeDialog": {
            "employeeSelection": "Assign an employee"
        }
    },
    "ru": {
        "EmployeeDialog": {
            "employeeSelection": "Назначить сотрудника"
        }
    }
}
</i18n>

<template>
  <div>
    <q-btn
      :disable="disableAllButtons"
      class="q-ml-sm"
      padding="6px"
      flat
      v-bind="buttonProps"
      v-on="buttonActions"
    >
      <q-tooltip v-if="buttonSettings.tooltip">
        {{ buttonSettings.tooltip }}
      </q-tooltip>
    </q-btn>
    <q-dialog v-model="value">
      <q-card class="no-shadow" style="max-width: 80vw; width: 700px">
        <q-card-section>
          <div class="text-h6">
            {{ $t('EmployeeDialog.employeeSelection') }}
          </div>
        </q-card-section>
        <q-card-section class="q-p">
          <q-input
            v-model="searchText"
            dense
            filled
            debounce="1000"
            placeholder="ФИО"
            @input="onSearch"
            @keydown.enter="onSearch"
            @keydown.esc="searchText = ''"
          >
            <template #prepend>
              <q-icon name="search" />
            </template>
          </q-input>
          <q-table
            class="no-shadow text-grey-9"
            row-key="accountId"
            :columns="employeesColumns"
            :data="visibleEmployees"
            selection="single"
            :selected.sync="selectedEmployee"
          >
          </q-table>
        </q-card-section>
        <q-card-actions class="q-pa-md" align="left">
          <q-btn
            :disable="!selectedEmployee.length"
            :label="'Назначить'"
            unelevated
            color="primary"
            @click="handler"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script lang="ts">
import {
  Role,
  RoleApi,
  AccountApi,
  AccountSearchRecordSimpleDTO,
} from '@openapi/idm';
import { Component, Vue, Prop } from 'vue-property-decorator';
import { BaseCardCommon } from '@/interfaces';
import ButtonSettings from '@interfaces/entities/ButtonSettings';
import { notifyError } from '@utils/notify';

const roleApi = new RoleApi();
const accountApi = new AccountApi();

@Component({})
export default class EmployeeDialog extends Vue {
  @Prop() common: BaseCardCommon;
  @Prop() model: any;
  @Prop() disableAllButtons: boolean;
  @Prop() userTask: any;
  @Prop() buttonSettings: ButtonSettings;

  private buttonActions = {
    click: () => {
      this.$recordActivity({
        buttonCode: 'application_manager',
        extraInfo: {
          previewInfo: [
            {
              value: this.model?.common?.orderId,
              label: 'номер',
            },
          ],
        },
      });
      this.setAssignee();
    },
  };

  private employees: AccountSearchRecordSimpleDTO[] = [];
  private visibleEmployees: AccountSearchRecordSimpleDTO[] = [];
  private selectedEmployee: AccountSearchRecordSimpleDTO[] = [];
  private employeesColumns = [
    {
      name: 'accountFullName',
      label: 'ФИО',
      field: 'accountFullName',
      align: 'left',
    },
  ];

  private value = false;
  private searchText = '';

  get buttonProps() {
    return this.buttonSettings.props;
  }

  get actions(): string[] {
    return this.userTask.userTask.outData.actions || [];
  }

  private handler(): void {
    const employee = this.selectedEmployee[0];

    if (!employee?.accountId || !employee?.accountFullName) {
      notifyError('Отсутствует информация о сотруднике');
      return;
    }

    this.value = false;

    this.$recordActivity({
      buttonCode: 'application_appoint',
      extraInfo: {
        previewInfo: [
          {
            label: 'номер',
            value: this.model?.common?.orderId,
          },

          {
            label: 'ФИО',
            value: employee.accountFullName,
          },
        ],
      },
    });

    this.submit({
      buttonId: 'setAssignee',
      data: {
        assignee: {
          fullName: employee.accountFullName,
          id: employee.accountId,
        },
      },
      force: true,
    });
  }

  private async initEmployees(): Promise<void> {
    let role: Role | null = null;
    this.employees = [];
    this.selectedEmployee = [];

    try {
      const { data } = await roleApi.getAllRoles(
        'name==military_application_specialist'
      );
      if (data.length) {
        role = data[0];
      }
    } catch (e: any) {
      notifyError(e.toString());
    }
    if (!role) {
      notifyError('Отсутствует роль для поиска сотрудников');
      return;
    }

    const currentUser = this.$store.getters['oidcClient/currentUser'] || {};

    if (!currentUser?.domain_id || !currentUser?.sub) {
      notifyError('Отсутствует информация о пользователе');
      return;
    }

    try {
      const { data } = await accountApi.getAccountsByOrganizationIdV1({
        domainId: currentUser.domain_id,
        roleId: role.id,
      });

      /* Отсортировать по алфавиту */
      const employees = data
        .filter((employee) => employee?.enabled)
        .sort((employeeA, employeeB) => {
          const aName = employeeA?.accountFullName || '';
          const bName = employeeB?.accountFullName || '';
          return aName.localeCompare(bName);
        });

      /* Найти индекс собственной персоны */
      const myIndex = employees.findIndex(
        (employee) => employee?.accountId === currentUser.sub
      );
      // /* Сохранить */
      const me = employees[myIndex];
      /* Переместить в начало списка, если найден */
      if (me) {
        employees.splice(myIndex, 1);
        employees.unshift(me);
      }

      this.employees = employees;
      this.visibleEmployees = employees;
    } catch (e: any) {
      notifyError(e.toString());
    }
  }

  private submit({ buttonId, data }: SubmitParams): void {
    this.buttonProps.loading = true;

    this.$emit('submit', {
      buttonId,
      data,
      force: true,
    });
  }

  private setAssignee(): void {
    this.initEmployees();
    this.value = true;
  }

  private onSearch(): void {
    const searchTextLowerCase = this.searchText.toLowerCase();
    const filteredEmployees = this.employees.filter((employee) => {
      if (!employee?.accountFullName) {
        return false;
      }
      return employee.accountFullName
        .toLowerCase()
        .includes(searchTextLowerCase);
    });
    this.visibleEmployees = filteredEmployees;
  }
}

declare interface SubmitParams {
  buttonId: string;
  data: {
    assignee: {
      fullName: string | undefined;
      id: string;
    };
  };
  force?: boolean;
}
</script>
