<template>
  <div
    class="ExtendForm"
    :id="recruitId"
  >
    <q-card>
      <q-card-section>
        <div class="ExtendForm__Headers">
          <div class="ExtendForm__HeaderTitle">
            <span>Адрес направления</span>
          </div>
          <div class="ExtendForm__HeaderTitle ExtendForm__HeaderTitle_Center">
            <span>Тип адреса</span>
          </div>
          <div class="ExtendForm__HeaderTitle ExtendForm__HeaderTitle_Center">
            <q-checkbox
              class="ExtendForm__HeaderTitle_Pointer"
              id="massCheckbox14"
              size="sm"
              type="checkbox"
              :disable="!availableActions"
              :value="massCheckbox['14']"
              @input="(v) => setCheckboxColumn('14', v)"
            />Нарочно
          </div>
          <div class="ExtendForm__HeaderTitle ExtendForm__HeaderTitle_Center">
            <q-checkbox
              class="ExtendForm__HeaderTitle_Pointer"
              id="massCheckbox15"
              size="sm"
              type="checkbox"
              :disable="!availableActions"
              :value="massCheckbox['15']"
              @input="(v) => setCheckboxColumn('15', v)"
            />Письмо
          </div>
          <div class="ExtendForm__HeaderTitle ExtendForm__HeaderTitle_Center">
            <q-icon
              color="negative"
              class="ExtendForm__HeaderTitle_Pointer"
              size="19px"
              name="pgs-delete"
              :disabled="!availableActions"
              @click="deleteFields"
            />
          </div>
        </div>
        <div :key="index" v-for="(sendType, index) in currentSendTypes">
          <div class="ExtendForm__Rows">
            <div class="ExtendForm__Cell">
              <span>{{ get(sendType, 'address.reg') || '' }}</span>
            </div>
            <div
              class="ExtendForm__Cell ExtendForm__Cell_Center ExtendForm__Cell_Gray"
            >
              <span>{{ convertAddressType(sendType.addressType) }}</span>
            </div>
            <div
              class="ExtendForm__Cell ExtendForm__Cell_Center ExtendForm__Cell_Pointer"
            >
              <q-checkbox
                class="ExtendForm__Cell_Pointer"
                :id="index"
                type="checkbox"
                val="14"
                v-model="sendType.sendCode"
                :disable="
                  !get(sendType, 'address.reg', '') || !availableActions
                "
              />
            </div>
            <div class="ExtendForm__Cell ExtendForm__Cell_Center">
              <q-checkbox
                class="ExtendForm__Cell_Pointer"
                :id="index"
                type="checkbox"
                val="15"
                v-model="sendType.sendCode"
                :disable="
                  !get(sendType, 'address.reg', '') || !availableActions
                "
              />
            </div>
            <div class="ExtendForm__Cell ExtendForm__Cell_Center">
              <q-icon
                color="negative"
                class="ExtendForm__Cell_Pointer"
                size="23px"
                name="pgs-delete"
                :disabled="!availableActions"
                @click="deleteField(index)"
              />
            </div>
          </div>
        </div>
        <div class="AddNewField" v-if="availableActions">
          <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="getAddFieldOption ? '' : 'Добавить адреса'"
              icon="pgs-plus"
              @click="
                getAddFieldOption
                  ? addNewField()
                  : (addFieldOption = !addFieldOption)
              "
            />
          </div>
          <r-btn
            :disabled="disabledChanges"
            label="Сохранить"
            class="RButton__Action"
            @click="pushNewAddressSettings"
          />
        </div>
      </q-card-section>
    </q-card>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { get } from 'lodash';
import { Option } from '@/recruits/models';
import { notifyError } from '@utils/notify';
import RSelect from '@/recruits/components/common/r-select.vue';
import {
  Address,
  ChangeAddressArrayDeliveryV1,
} from '@/recruits/openapi/summon-list-service';
@Component({
  components: {
    RSelect,
  },
  methods: {
    get,
  },
})
export default class ExtendRecruitAddress extends Vue {
  @Prop({ default: () => [] }) sendInfo: any[];
  @Prop({ default: [] }) address: Address[];
  @Prop({ default: false }) availableActions: boolean;
  @Prop({ default: () => '' }) recruitId: string;

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

  addFieldOption = false;
  currentSendTypes: Partial<
    ChangeAddressArrayDeliveryV1 & { address: Address }
  >[] = [];

  newAddressType: Option | null = null;

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

  @Watch('currentSendTypes', { deep: true })
  watchMassCheckBox(sendTypes: any[]) {
    const checkBox = sendTypes?.reduce(
      (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;
  }

  get getCurrentSendTypes() {
    return this.currentSendTypes;
  }

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

  get getRecruitId() {
    return this.recruitId || '';
  }

  get getAddFieldOption() {
    return this.addFieldOption;
  }

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

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

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

  get freshSendInfo() {
    return this.getCurrentSendTypes?.map((info) => {
      return { addressType: info?.addressType, sendCode: info?.sendCode };
    });
  }

  deleteFields() {
    if (this.availableActions) {
      this.currentSendTypes.splice(0, this.currentSendTypes.length);
      this.$emit('set-address-settings', {
        id: this.getRecruitId,
        sendInfo: this.freshSendInfo,
      });
    }
  }

  deleteField(index: number) {
    if (this.availableActions) {
      this.currentSendTypes.splice(index, 1);
      this.$emit('set-address-settings', {
        id: this.getRecruitId,
        sendInfo: this.freshSendInfo,
      });
    }
  }

  setCheckboxColumn(field: string, value: boolean) {
    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;
      }) || [];
  }

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

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

  pushNewAddressSettings() {
    if (this.recruitId) {
      this.$emit('set-address-settings', {
        id: this.getRecruitId,
        sendInfo: this.freshSendInfo,
      });
    }
  }

  created() {
    this.changeCurrentSendInfo();
  }
}
</script>

<style lang="scss" scoped>
@mixin font-style-expand-form {
  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;
}
.ExtendForm {
  &__Headers {
    display: grid;
    grid-template-columns: 0.8fr 0.4fr 0.2fr 0.2fr 0.2fr;
    border-bottom: 1px solid rgba(1, 72, 116, 0.11);
    @include font-style-expand-form;
    font-weight: 600;
    color: rgba(2, 12, 18, 0.58);
  }
  &__HeaderTitle {
    display: flex;
    align-items: center;
    &:not(:last-child) {
      border-right: 1px solid rgba(1, 72, 116, 0.11);
    }
    &_Center {
      justify-content: center;
    }
    &_Pointer {
      cursor: pointer;
    }
  }
  &__Rows {
    display: grid;
    grid-template-columns: 0.8fr 0.4fr 0.2fr 0.2fr 0.2fr;
    border-bottom: 1px solid rgba(1, 72, 116, 0.11);
    @include font-style-expand-form;
  }
  &__Cell {
    display: flex;
    align-items: center;
    &:not(:last-child) {
      border-right: 1px solid rgba(1, 72, 116, 0.11);
    }
    &_Center {
      justify-content: center;
    }
    &_Gray {
      color: rgba(2, 12, 18, 0.58);
    }
    &_Pointer {
      cursor: pointer;
    }
  }
}

.AddNewField {
  display: flex;
  justify-content: flex-end;
  padding: 0.5rem 0 0 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>
