<template>
  <q-card class="CreateList no-right-border-radius">
    <q-card-section class="CreateList-Content">
      <p class="text-h5 CreateList-Header">Формирование нового списка</p>
      <div class="loader" v-if="loader">
        <q-spinner-oval size="10em" color="primary" />
      </div>
      <div class="CreateList-Success" v-if="success">
        <q-icon class="CreateList-Success__Icon" name="pgs-ok" />
        <span class="CreateList-Success__Text">Успешное создание списка</span>
      </div>
      <q-card-section v-if="!loader && !success">
        <r-select-group
          dense
          options-dense
          v-model="summonObjective"
          :string-options="actionSelectGroupDataList()"
          placeholder=""
          label="Причина вызова в военкомат"
        />
        <r-date-time-input
          class="q-mt-md"
          v-model="summonDate"
          :emit-format="isoDateFormat"
          :date-options="isDateAvailable"
          :time-options="isTimeAvailable"
          :default-year-month="defaultYearMonth"
          default-time="09:00"
          label="Дата и время явки"
        />

        <div class="full-width wrapper-block">
          <span class="wrapper-block__title">Адреса и способы направления</span>
          <div class="CallListTable">
            <div class="full-width headers CallListTable-Header">
              <div class="q-pl-xs flex"><div class="self-center">Тип адреса направления</div></div>
              <div class="text-center">
                <q-checkbox
                  class="LabelSelect-Select"
                  id="meet"
                  size="sm"
                  type="checkbox"
                  :value="massCheckbox.meet"
                  @input="(v) => setCheckboxColumn('meet', v)"
                />Нарочно
              </div>
              <div class="text-center">
                <q-checkbox
                  class="LabelSelect-Select"
                  id="mail"
                  size="sm"
                  type="checkbox"
                  :value="massCheckbox.mail"
                  @input="(v) => setCheckboxColumn('mail', v)"
                />Письмо
              </div>
              <div class="flex flex-center cursor-pointer">
                <q-icon
                  color="negative"
                  size="19px"
                  name="pgs-delete"
                  @click="deleteFields"
                />
              </div>
            </div>
            <div class="full-width">
              <q-table
                  grid
                  :hidePagination="true"
                  :data="rows"
                  row-key="name"
              >
                <template v-slot:item="props">
                  <div class="full-width body CallListTable-Row">
                    <div class="CallListTable-Row__Address"><span>{{ getAddressTypesDictionary[props.row.name] }}</span></div>
                    <div class="flex justify-center">
                      <q-checkbox
                        class="LabelSelect-Select"
                        :id="props.row.name"
                        type="checkbox"
                        :value="props.row.meet"
                        @input="(v) => setInputValue(props.row.index, 'meet', v)"
                      />
                    </div>
                    <div class="flex justify-center">
                      <q-checkbox
                        class="LabelSelect-Select"
                        :id="props.row.name"
                        type="checkbox"
                        :value="props.row.mail"
                        @input="(v) => setInputValue(props.row.index, 'mail', v)"
                      />
                    </div>
                    <div class="flex flex-center cursor-pointer">
                      <q-icon
                        color="negative"
                        size="23px"
                        name="pgs-delete"
                        @click="deleteField(props.row.index)"
                      />
                    </div>
                  </div>
                </template>
              </q-table>
            </div>
            <div :class="['AddNewField-Group', {'AddNewField-Extend': getAddFieldOption}]">
              <r-select
                dense
                options-dense
                placeholder="Тип адреса направления"
                v-model="newAddressType"
                :options="getAddressTypesOptions"
              />
              <r-btn
                action
                :label="getAddFieldOption ? '' : 'Добавить адреса'"
                icon="pgs-plus"
                @click="getAddFieldOption ? addNewField() : addFieldOption = !addFieldOption"
              />
            </div>
          </div>
        </div>
      </q-card-section>
    </q-card-section>
    <q-card-actions class="CreateList-Actions">
      <r-btn
        v-if="success"
        outline
        label="Закрыть"
        icon="pgs-close"
        color="primary"
        v-close-popup
      />
      <r-btn
        v-if="!success"
        outline
        label="Отмена"
        icon="pgs-close"
        color="primary"
        v-close-popup
      />
      <q-btn
        v-if="!success"
        :disable="disableSubmitBtn"
        label="Сформировать"
        icon="pgs-sign-2"
        class="redesigned-action-btn button-text"
        @click="createList"
      />
    </q-card-actions>
  </q-card>
</template>

<style lang="scss" scoped>
.wrapper-block {
  position: relative;
  padding-top: 23px;
  &__title {
    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);
    position: absolute;
    padding: 0 5px;
    background: #ffffff;
    top: 13px;
    left: 8px;
  }
}
.CallListTable {
  border: 1px solid rgba(2, 12, 18, 0.15);
  border-radius: 8px;
  padding: 10px 10px 0 10px;
  &-Header {
    display: grid;
    grid-template-columns: 1.4fr 0.4fr 0.4fr 0.4fr;
    padding: 5px;
    background: #e5edf5;
    border-bottom: 1px solid rgba(2, 12, 18, 0.15);
    box-sizing: border-box;
    div:not(:last-child) {
      border-right: 1px solid rgba(2, 12, 18, 0.15);
    }
  }
  &-Row {
    display: grid;
    grid-template-columns: 1.4fr 0.4fr 0.4fr 0.4fr;
    border-bottom: 1px solid rgba(2, 12, 18, 0.15);
    padding: 5px;
    div:not(:last-child) {
      border-right: 1px solid rgba(2, 12, 18, 0.15);
    }
    &__Address {
      display: flex;
      flex-direction: column;
      font-family: 'Golos UI', sans-serif;
      font-style: normal;
      font-weight: 400;
      font-size: 12px;
      line-height: 14px;
      color: rgba(2, 12, 18, 0.58);
      align-self: center;
      span:nth-child(2n) {
        color: rgba(2, 12, 18, 1);
        font-size: 14px;
      }
    }
  }
}
.headers {
  > div {
    color: rgba(2, 12, 18, 0.58);
    overflow: hidden;
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    font-weight: 600;
    font-size: 10px;
    line-height: 12px;
    letter-spacing: 0.05em;
    text-transform: uppercase;
  }
}
.loader {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}
.CreateList {
  width: 750px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  &-Content {
    padding: 5px;
  }
  &-Header {
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    font-weight: 500;
    font-size: 20px;
    line-height: 24px;
    letter-spacing: -0.015em;
    color: rgba(2, 12, 18, 0.9);
    margin-bottom: 28px;
  }
  &-Actions {
    background: rgba(15, 32, 160, 0.08);
    display: flex;
    justify-content: space-between;
    padding: 5px;
  }
  &-Success {
    margin-top: 100px;
    display: flex;
    flex-direction: column;
    align-items: center;
    &__Icon {
      border-radius: 50%;
      background-color: rgba(227, 254, 250, 1);
      color: rgba(4, 150, 125, 1);
      font-size: 60px;
    }
    &__Text {
      font-family: 'Golos UI', sans-serif;
      font-size: 16px;
      color: rgba(157, 157, 161, 1);
    }
  }
}
.MultiSelect__Form {
  ::v-deep > label {
    height: 39px;
    min-height: 39px;
    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: 0 8px !important;
    box-sizing: border-box;
    transition: 0.1s;
  }
}
.AddNewField {
  &-Group {
    will-change: width, opacity;
    display: flex;
    justify-content: space-between;
    gap: 1rem;
    padding: 8px 0;
    .RSelect {
      margin: 0;
      padding: 0;
      width: 0;
      opacity: 0;
      ::v-deep {
        .RSelect-Label {
          margin: 0;
          padding: 0;
        }
        .q-field__control {
          padding: 0!important;
        }
      }
    }
    .RButton {
      margin-left: -16px;
      width: 100%;
    }
  }
  &-Extend {
    .RSelect {
      width: 80%;
      opacity: 1;
      transition: width 0.5s;
    }
    .RButton {
      width: 20%;
      transition: width 0.5s;
    }
  }
}
</style>

<script lang="ts">
import { Component, Mixins, Prop } from 'vue-property-decorator';
import {
  AddressArrayDeliveryV1,
  SummonListRegistryApi,
} from '@/recruits/openapi/summon-list-service';
import { notifyError } from '@utils/notify';
import RDateTimeInput from '@/recruits/components/common/r-date-time-input.vue';
import RSelect from '@/recruits/components/common/r-select.vue';
import RSelectGroup from '@/recruits/components/common/r-select-group.vue';
import moment from 'moment';
import { formatDate } from '@/recruits/utils';
import { Option } from '@/recruits/models';
import SummonDate from '@/recruits/mixins/summon-date';
import ActionSelectGroupData from '@/recruits/mixins/action-select-group-data';
import RStatusSelect from '@/recruits/components/common/r-status-select.vue';
import { get } from 'lodash';

const DELIVERY_METHOD_DICT = 'deliveryMethod';
const addressForSendDictionaryPath = 'ervuDictionaries/addressTypeDictionary';

interface IRow {
  index: number;
  name: string;
  meet: boolean;
  mail: boolean;
}

const initialFields = ['residenceAddress', 'actualAddress', 'residentialAddress'];

@Component({
  components: {
    RDateTimeInput,
    RSelect,
    RSelectGroup,
    RStatusSelect,
  },
  methods: {
    moment,
    formatDate,
    get,
  },
})
export default class CreateList extends Mixins(
  SummonDate,
  ActionSelectGroupData
) {
  @Prop() activityRecorderOptions: any;

  SummonListRegistryApi = new SummonListRegistryApi();

  summonObjective: Option | null = null;
  loader = false;
  success = false;

  newAddressType: Option | null = null;
  addFieldOption = false;
  massCheckbox = {
    meet: false,
    mail: false,
  };

  localRows: IRow[] = [];

  get rows() {
    return this.localRows;
  }

  get getAddFieldOption() {
    return this.addFieldOption;
  }

  setInputValue(index: number, field: string, value: boolean) {
    this.localRows[index][field as keyof Pick<IRow, 'meet' | 'mail'>] = value;
  }

  setCheckboxColumn(field: string, value: boolean) {
    this.massCheckbox[field as keyof Pick<IRow, 'meet' | 'mail'>] = value;
    this.localRows.forEach(row =>{
      row[field as keyof Pick<IRow, 'meet' | 'mail'>] = value;
    });
  }

  get statusOptions(): Array<string> {
    return Object.keys(this.$store.getters[addressForSendDictionaryPath]);
  }

  get disableSubmitBtn() {
    return !this.summonObjective || !this.summonDate || !this.rows?.filter(el=> (( el.mail )||( el.meet )))?.length;
  }

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

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

  addNewField() {
    if (this.newAddressType?.value) {
      if (this.rows.find((el: IRow) => this.newAddressType && (el.name === this.newAddressType.value))?.name) {
        notifyError('Поле уже имеется');
        return;
      }
      this.localRows.push({
        index: this.rows.length,
        name: this.newAddressType.value,
        meet: false,
        mail: false,
      });
      this.newAddressType = null;
    }
  }

  deleteField(index: number) {
    this.localRows.splice(index, 1);
  }

  deleteFields() {
    this.localRows.splice(0, this.rows.length);
  }

  async initDeliveryDictionary(): Promise<void> {
    await this.$store.dispatch(
      'registryService/referenceBooks/initReferenceBooks',
      [
        {
          id: DELIVERY_METHOD_DICT,
        },
      ]
    );
  }

  createList(): void {
    if (!this.summonObjective || !this.summonDate) return;
    if (!this.isDateAndTimeValid()) return;
    this.loader = true;
    const sendInfo = this.rows.reduce((acc: AddressArrayDeliveryV1[], row: IRow)=>{
        const sendCode = [];
        row.meet && sendCode.push('14');
        row.mail && sendCode.push('15');
        acc.push({ sendCode, addressType: row.name });
        return acc;
    }, [])
    this.SummonListRegistryApi.newListV3({
      recruitIds: [],
      summonObjective: this.summonObjective.value,
      listTitle: this.summonObjective.label,
      turnoutDate: this.summonDate,
      sendInfo,
    })
      .then((res) => {
        const listInfo = res.data?.listInfo || {};
        this.success = true;
        this.loader = false;
        this.$recordActivity({
          ...this.activityRecorderOptions,
          extraInfo: {
            previewInfo: [
              {
                label: 'номер',
                value: listInfo?.number,
              },
            ],
            detailedInfo: [
              {
                label: 'цель вызова',
                value: this.summonObjective?.label,
              },
              {
                label: 'дата и время вызова',
                value: this.summonDate,
                type: 'date',
              },
            ],
          },
        });
        this.$emit('onReload');
      })
      .catch((err) => {
        notifyError(err.message.toString());
        this.loader = false;
      });
  }

  mounted(): void {
    this.initDeliveryDictionary();
    if (!this.localRows.length) {
      this.statusOptions.forEach(key => {
        initialFields.includes(key) &&
          this.localRows.push({
            index: this.rows.length,
            name: key,
            meet: false,
            mail: false,
          });
      });
    }
  }
}
</script>
