<template>
  <div ref="popup" class="upload-contest-work popup" @click.prevent="hide">
    <div class="popup__wrap popup__wrap_md" @click.stop>
      <button class="popup__close" @click.prevent="hide">
        <svg class="icon icon-close">
          <use v-bind="{'xlink:href': $root.store.staticUrl + 'img/sprite.svg' + '#icon-close' }"></use>
        </svg>
      </button>
      <div class="popup__body">
        <form class="form">
          <div class="title">
            Чтобы принять участие<br>в конкурсе, заполните поля<br>и прикрепите изображение
            <img src="/static/img/curve-1.svg" class="text__curve">
          </div>
          <div class="field"
               v-bind:class="{ error: $v.contestWork.child_full_name.$dirty && $v.contestWork.child_full_name.$invalid }">
            <div class="field__label">ИМЯ И ФАМИЛИЯ РЕБЕНКА</div>
            <div class="field__wrap">
              <input class="field__input" type="text" v-model="contestWork.child_full_name">
            </div>
            <div class="field__error"></div>
          </div>
          <div class="field"
               v-bind:class="{ error: $v.contestWork.age.$dirty && $v.contestWork.age.$invalid }">
            <div class="field__label">ВОЗРАСТ</div>
            <div class="field__wrap">
              <input class="field__input" type="number" v-model="contestWork.age" style="width: 100px;">
            </div>
            <div class="field__error"></div>
          </div>
          <div class="field">
            <lil-image :image-id.sync="contestWork.imageId" :image-url.sync="contestWork.imageUrl"
                       v-on:update:imageId="onUpdateImageId" :access-token="$root.store.accessToken" />
          </div>

          <div class="field" style="text-align: center;">
            <button class="btn" tabindex="3" @click.prevent="save">Отправить на конкурс</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
  import {api} from "../js/modules/api";
  import LilImage from './blocks/Image';
  import {showNotification} from "../js/modules/notification";
  import {required, minValue, numeric, url } from 'vuelidate/lib/validators';
  import $ from 'jquery';

  export default {
    name: 'upload-contest-work',
    props: ['contestId'],
    data() {
      return {
        fields: {
          image: "Изображение",
          child_full_name: "Имя и фамилия ребенка",
          age: 'Возраст',
        },
        contestWork: {
          contest: this.contestId,
          image: null,
          imageId: null,
          imageUrl: '',
          child_full_name: '',
          age: '',
        }
      }
    },
    validations() {
      return {
        contestWork: {
          image: {
            required
          },
          child_full_name: {
            required
          },
          age: {
            required, numeric
          },
        },
      };
    },
    mounted() {
      $('[data-show-upload-contest-work]').click((e) => {
        e.preventDefault();
        e.stopPropagation();
        this.clear();
        this.show();
      });
    },
    methods: {
      clear() {
        Object.assign(this.$data, this.$options.data.apply(this))
      },
      onUpdateImageId(imageId) {
        this.contestWork.image = imageId;
      },
      show() {
        const $popup = $(this.$refs.popup)
        $('body').addClass('no-scroll');
        $popup.addClass('visible');
        setTimeout(() => {
          $popup.addClass('open');
        }, 300);
      },
      hide() {
        const $popup = $(this.$refs.popup)
        $('body').removeClass('no-scroll');
        $popup.removeClass('visible');
        setTimeout(() => {
            $popup.removeClass('open');
        }, 300);
      },
      validate() {
        if (this.$v.contestWork.$invalid) {
          for(let i in this.$v.contestWork) {
            if(this.$v.contestWork[i].$invalid) {
              showNotification("error", "Ошибка валидации поля " + this.fields[i]);
            }
          }
          return false;
        }

        return true;
      },
      save() {
        if(! this.validate()) {
          return false;
        }
        let data = this.contestWork;
        data.contest = this.contestId;
        data.user = this.$root.store.user.id;
        const request = api.post(`/api/v1/contest-works/`, data, {
          headers: {
            'Authorization': `Token ${this.$root.store.accessToken}`,
          }
        });
        request.then((response) => {
          if(+response.data.id){
              this.$emit('add:contest-work', response.data);
              this.hide();
              window.location.reload();
          }
        });
      }
    },
    components: {
      'lil-image': LilImage,
    }
  }
</script>
