<template>
  <div class="Registered">
    <div class="Registered__Content">
      <div class="Registered__FullWidth">
        <search-bar
          :main-filter="filter"
          @search="executeSearch"
          :loading="loading"
          @change="changeFilter"
        />
      </div>
      <div class="Registered__FullWidth">
        <sort-bar
          v-model="sortButtons"
          :pagination="pagination"
          @click="requestHandler"
          :loading="loading"
        />
      </div>
      <data-table
        :loading="loading"
        :data="data.data"
        :selected="selected"
        :list-info="data.listInfo"
        @pagination-handler="paginationHandler"
        :pagination.sync="pagination"
        @request="callRequest"
        @row-selected="rowSelected"
        @toggle-row="toggleRow"
        @set-new-send-info="setNewSendInfo"
        :resetSelect="resetSelect"
        :rows-per-page-options="[10, 25, 50]"
      />
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Watch, Emit, Prop, Vue } from 'vue-property-decorator';
import DataTable from './data-table.vue';
import { Option } from '@/recruits/models';
import {
  ChangeAddressArrayDeliveryV1,
  ListElementV2,
  ListSearchResponseV2,
  SummonListRegistryApi,
} from '@/recruits/openapi/summon-list-service';
import SortBar from '@/recruits/components/common/sort-bar.vue';
import SearchBar from '../search-bar.vue';
import { RecruitsFromListSearchFilter } from '../recruits-from-list-search-filter';
import { notifyError } from '@utils/notify';
import { QPagination } from '@models/models-ui';

interface ListElementV2WithShow extends ListElementV2 {
  showOptions: boolean;
}

@Component({
  components: {
    DataTable,
    SortBar,
    SearchBar,
  },
})
export default class CallList extends Vue {
  @Prop()
  resetSelect: boolean;

  @Prop({ default: () => [] })
  data: ListSearchResponseV2;

  @Prop({ default: () => [] })
  sortButtons: Array<Option>;

  @Prop({ default: () => null })
  pagination: QPagination;

  @Prop()
  selected: string[];

  @Prop()
  loading: boolean;

  @Prop()
  filter: RecruitsFromListSearchFilter;

  currentFilter: RecruitsFromListSearchFilter | null = null;

  @Watch('filter', { deep: true })
  setNewFilter(filter: RecruitsFromListSearchFilter) {
    this.currentFilter = filter;
  }

  SummonListRegistryApi = new SummonListRegistryApi();

  toggleRow(id: string) {
    (this.data?.data as ListElementV2WithShow[])?.forEach((row) => {
      if (row.id === id) {
        row.showOptions = !row.showOptions;
      }
    });
  }

  executeSearch() {
    this.$emit('execute-search');
  }

  requestHandler(e: Pick<QPagination, 'sortBy' | 'descending'>) {
    this.$emit('request-handler', e);
  }

  async setNewSendInfo({
    id,
    sendInfo,
  }: {
    id: string;
    sendInfo: ChangeAddressArrayDeliveryV1[];
  }) {
    if (this.data?.listInfo?.id) {
      const data = await this.SummonListRegistryApi.changeAddressSettingsV1(
        this.data.listInfo.id,
        [{ recruitId: id, sendInfo }]
      );
      if (data.status === 200) {
        (this.data?.data as ListElementV2WithShow[])?.forEach((row) => {
          if (row.id === id) {
            row.sendInfo = sendInfo.map(e=>({...e}));
          }
        });
      } else {
        notifyError('Не удалсь внести изменения');
      }
    }
  }

  @Watch('pagination')
  setNewPagination(pagination: QPagination) {
    this.$emit('update-pagination', pagination)
  }

  // пока оставлю, но вроде и без него все норм работает
  callRequest(e: any) {
    // console.log(e, 'callRequest')
    // this.$emit('request', e);
  }

  paginationHandler(pagination: QPagination) {
    this.$emit('update-pagination', pagination);
  }

  changeFilter(data: RecruitsFromListSearchFilter) {
    this.$emit('change-filter', data);
  }

  rowSelected(val: string[]): void {
    this.$emit('row-selected', val);
  }

  @Watch('loading')
  @Emit('data-loading')
  private loadingWatcher(): { loading: boolean; data: ListSearchResponseV2 } {
    return {
      loading: this.loading,
      data: this.data,
    };
  }
}
</script>

<style lang="scss" scoped>
.Registered {
  padding: 16px;
  &__Content {
    display: flex;
    flex-wrap: wrap;
  }
  &__FullWidth {
    width: 100%;
  }
  &__Header {
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    font-weight: 500;
    font-size: 28px;
    line-height: 32px;
    letter-spacing: -0.02em;
    color: rgba(2, 12, 18, 0.9);
  }
}
.flip-icon::v-deep {
  i {
    transform: scaleX(-1);
  }
}
</style>
