<template>
  <div class="List">
    <q-skeleton v-if="loading" type="text" height="24px" width="100%" />
    <div v-else class="List__Settings">
      <p class="List__SettingsTitle">Типы адресов направления по умолчанию</p>
      <div class="List__SettingsTable">
        <div class="List__SettingsHeaders">
          <div class="List__SettingsHeader">
            <span>Тип адреса направления</span>
          </div>
          <div class="List__SettingsHeader List__SettingsHeader_CheckBox">
            <q-checkbox
              id="massCheckbox14"
              size="sm"
              type="checkbox"
              label="Нарочно"
              :disable="!checkListStatus"
              :value="getMassCheckbox['14']"
              @input="(v) => setCheckboxColumn('14', v)"
            />
          </div>
          <div class="List__SettingsHeader List__SettingsHeader_CheckBox">
            <q-checkbox
              id="massCheckbox15"
              size="sm"
              type="checkbox"
              label="Письмо"
              :disable="!checkListStatus"
              :value="getMassCheckbox['15']"
              @input="(v) => setCheckboxColumn('15', v)"
            />
          </div>
          <div class="List__SettingsHeader List__SettingsHeader_CheckBox">
            <q-icon
              color="negative"
              size="19px"
              name="pgs-delete"
              :disabled="!checkListStatus"
              @click="deleteFields"
            />
          </div>
        </div>
        <div :key="index" v-for="(sendType, index) in currentSendTypes">
          <div class="List__SettingsRow">
            <div class="List__SettingsField">
              <span>{{ convertAddressType(sendType.addressType) }}</span>
            </div>
            <div class="List__SettingsField List__SettingsField_CheckBox">
              <q-checkbox
                :id="index"
                type="checkbox"
                val="14"
                :disable="!checkListStatus"
                v-model="sendType.sendCode"
              />
            </div>
            <div class="List__SettingsField List__SettingsField_CheckBox">
              <q-checkbox
                :id="index"
                type="checkbox"
                val="15"
                :disable="!checkListStatus"
                v-model="sendType.sendCode"
              />
            </div>
            <div class="List__SettingsField List__SettingsField_CheckBox">
              <q-icon
                color="negative"
                size="23px"
                name="pgs-delete"
                :disabled="!checkListStatus"
                @click="deleteField(index)"
              />
            </div>
          </div>
        </div>
        <div class="AddNewField" v-if="checkListStatus">
          <div
            :class="[
              'AddNewField__Group',
              { AddNewField_Extend: getAddFieldOption },
            ]"
          >
            <r-select
              v-if="getAddressTypesOptions.length"
              dense
              options-dense
              placeholder="Тип адреса направления"
              v-model="newAddressType"
              :options="getAddressTypesOptions"
            />
            <r-btn
              v-if="getAddressTypesOptions.length"
              action
              :label="addLabelText"
              icon="pgs-plus"
              @click="addNewFieldSwitcher"
            />
          </div>
          <r-btn
            :disabled="disabledChanges"
            label="Сохранить"
            action
            @click="pushNewAddressSettings"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Watch, Vue, Prop } from 'vue-property-decorator';
import { Option } from '@/recruits/models';
import {
  ChangeAddressArrayDeliveryV1,
  ListSearchResponseV2,
  SummonListRegistryApi,
} from '@/recruits/openapi/summon-list-service';
import RSelect from '@/recruits/components/common/r-select.vue';
import { notifyError } from '@utils/notify';

const availableStatusForEdit = ['1', '5'];

@Component({
  components: {
    RSelect,
  },
})
export default class CallListSettings extends Vue {
  @Prop({ default: {} })
  data: ListSearchResponseV2;

  @Prop({ default: () => true })
  loading: boolean;

  SummonListRegistryApi = new SummonListRegistryApi();

  massCheckbox = {
    '14': false,
    '15': false,
  };

  get getMassCheckbox() {
    return this.massCheckbox;
  }

  addFieldOption = false;
  currentSendTypes: Partial<ChangeAddressArrayDeliveryV1>[] = [];
  newAddressType: Option | null = null;

  get getSendInfo() {
    return this.data?.listInfo?.sendInfo || [];
  }

  get checkListStatus() {
    return (
      this.data.listInfo?.status &&
      availableStatusForEdit.includes(this.data.listInfo.status)
    );
  }

  get getAddFieldOption() {
    return this.addFieldOption;
  }

  get addLabelText() {
    return this.getAddFieldOption ? '' : 'Добавить адреса';
  }

  get getAddressTypesDictionary(): Record<string, string> {
    return this.$store.getters['ervuDictionaries/addressTypeDictionary'] || {};
  }

  get getAddressTypesOptions() {
    return Object.keys(this.getAddressTypesDictionary).reduce((acc, el) => {
      if (
        !this.currentSendTypes.find((row) => row?.addressType === el)
          ?.addressType
      ) {
        acc.push({ value: el, label: this.getAddressTypesDictionary[el] });
      }
      return acc;
    }, [] as Record<string, string>[]);
  }

  get disabledChanges() {
    if (this.data?.listInfo?.sendInfo?.length !== this.currentSendTypes.length)
      return false;
    for (const index in this.currentSendTypes) {
      if (
        this.data?.listInfo?.sendInfo?.[index]?.sendCode?.sort().join('') !==
        this.currentSendTypes[index]?.sendCode?.sort().join('')
      ) {
        return false;
      }
    }
    return true;
  }

  @Watch('currentSendTypes', { deep: true })
  watchMassCheckBox(sendTypes: Required<ChangeAddressArrayDeliveryV1>[]) {
    const checkBox = sendTypes?.reduce<{ '14': string[]; '15': string[] }>(
      (acc, row) => {
        row?.sendCode?.includes('14') && acc['14'].push('14');
        row?.sendCode?.includes('15') && acc['15'].push('15');
        return acc;
      },
      { '14': [], '15': [] }
    );
    this.massCheckbox['14'] = checkBox['14']?.length === sendTypes?.length;
    this.massCheckbox['15'] = checkBox['15']?.length === sendTypes?.length;
  }

  async setNewSendInfo(sendInfo: ChangeAddressArrayDeliveryV1[]) {
    if (this.data?.listInfo?.id) {
      try {
        await this.SummonListRegistryApi.changeAddressListSettingsV1(
          this.data.listInfo.id,
          sendInfo
        );
        this.$emit('execute-search');
      } catch (e) {
        notifyError('Не удалсь внести изменения');
      }
    } else {
      notifyError('Не удалсь внести изменения');
    }
  }

  addNewFieldSwitcher() {
    this.getAddFieldOption
      ? this.addNewField()
      : (this.addFieldOption = !this.addFieldOption);
  }

  pushNewAddressSettings() {
    this.setNewSendInfo(this.currentSendTypes);
  }

  convertAddressType(type: string) {
    return this.getAddressTypesDictionary[type];
  }

  addNewField() {
    if (this.newAddressType?.value) {
      if (
        this.currentSendTypes.find(
          (el) =>
            this.newAddressType && el?.addressType === this.newAddressType.value
        )
      ) {
        notifyError('Поле уже имеется');
        return;
      }
      const addableField = !this.currentSendTypes.find(
        (info) => info.addressType === this.newAddressType?.value
      )?.addressType;
      if (addableField) {
        this.currentSendTypes.push({
          addressType: this.newAddressType.value,
          sendCode: [],
        });
        this.newAddressType = null;
      } else {
        notifyError(
          'Нет адреса соответствующему выбранному типу, либо он уже выбран'
        );
      }
    }
  }

  setCheckboxColumn(field: string, value: boolean) {
    if (this.checkListStatus) {
      this.massCheckbox[field as '14' | '15'] = value;
      this.currentSendTypes =
        this.currentSendTypes?.map((row) => {
          if (value) {
            row?.sendCode?.push(field);
          } else if (!value) {
            row.sendCode = row.sendCode?.filter((info) => info !== field);
          }
          return row;
        }) || [];
    }
  }

  @Watch('getSendInfo')
  changeCurrentSendInfo() {
    this.currentSendTypes = this.getSendInfo?.map((e) => ({
      addressType: e.addressType || '',
      sendCode: Object.assign([], e?.sendCode),
    }));
  }

  deleteFields() {
    if (this.checkListStatus) {
      this.currentSendTypes.splice(0, this.currentSendTypes.length);
    }
  }

  async deleteField(index: number) {
    if (this.checkListStatus) {
      this.currentSendTypes.splice(index, 1);
    }
  }

  created() {
    if (!this.data?.listInfo) {
      this.$emit('refresh-data');
    }
  }
}
</script>

<style lang="scss" scoped>
.List {
  margin: 0;
  padding: 0;
  list-style: none;
  color: rgba(2, 12, 18, 0.9);
  font-family: 'Golos UI', sans-serif;
  font-style: normal;
  font-weight: 400;
  font-size: 14px;
  line-height: 14px;
  &__Settings {
    padding: 10px 20px;
  }
  &__SettingsTitle {
    font-family: 'Golos text', sans-serif;
    font-weight: 500;
    font-size: 20px;
    line-height: 24px;
    letter-spacing: -0.015em;
    color: rgba(2, 12, 18, 0.9);
    padding-bottom: 12px;
    margin-bottom: 26px;
    border-bottom: 1px solid rgba(1, 72, 116, 0.11);
  }

  &__SettingsTable {
    border: 1px solid rgba(1, 72, 116, 0.11);
    border-radius: 8px;
  }
  &__SettingsHeaders {
    display: grid;
    grid-template-columns: 0.8fr 0.2fr 0.2fr 0.2fr;
    border-bottom: 1px solid rgba(1, 72, 116, 0.11);
    color: rgba(2, 12, 18, 0.58);
    font-weight: 600;
  }
  &__SettingsHeader {
    display: flex;
    align-items: center;
    padding: 0 5px;
    &:not(:first-child) {
      justify-content: center;
    }
    &:not(:last-child) {
      border-right: 1px solid rgba(1, 72, 116, 0.11);
    }
    &_CheckBox {
      display: flex;
      justify-content: center;
      cursor: pointer;
    }
  }
  &__SettingsRow {
    display: grid;
    grid-template-columns: 0.8fr 0.2fr 0.2fr 0.2fr;
    border-bottom: 1px solid rgba(1, 72, 116, 0.11);
  }
  &__SettingsField {
    display: flex;
    align-items: center;
    padding: 0 5px;
    &:not(:last-child) {
      border-right: 1px solid rgba(1, 72, 116, 0.11);
    }
    &_CheckBox {
      display: flex;
      justify-content: center;
      cursor: pointer;
    }
  }
}
.AddNewField {
  display: flex;
  justify-content: flex-end;
  padding: 0.5rem 0;
  gap: 0.5rem;
  &__Group {
    will-change: width, opacity;
    display: flex;
    justify-content: space-between;
    gap: 0.5rem;
    .RSelect {
      margin: 0;
      padding: 0;
      width: 0;
      opacity: 0;
      ::v-deep {
        .RSelect-Label {
          margin: 0;
          padding: 0;
        }
        .q-field__control {
          border-radius: 20px;
        }
      }
    }
  }
  &_Extend {
    width: 500px;
    .RSelect {
      width: 80%;
      opacity: 1;
      transition: width 0.5s;
    }
    .RButton {
      width: 20%;
      transition: width 0.5s;
    }
  }
}
</style>
