<template>
  <v-app>
    <v-main class="me-2 ml-2">
      <v-container>
        <v-row no-gutters>
          <v-stepper
            v-model="step"
            class="width-full ma-auto">
            <v-stepper-header>
              <v-stepper-step
                :complete="step>1"
                step="1">
                {{ $t('cs.requestPanelTitle') }}
              </v-stepper-step>
              <v-divider />
              <v-stepper-step
                :complete="step>2"
                step="2">
                <span v-if="newTicket.type === 'INCIDENT'">{{ $t('cs.giveMoreDetails') }}</span>
                <span v-if="newTicket.type === 'INFORMATION'">{{ $t('cs.selectInformationType') }}</span>
              </v-stepper-step>
              <v-divider />
              <v-stepper-step
                step="3">
                {{ $t('cs.incidentLabelForm') }}
              </v-stepper-step>
            </v-stepper-header>
            <v-stepper-items>
              <v-stepper-content
                step="1">
                <v-card
                  outlined
                  class="mb-12 pa-4 me-12"
                  height="200px">
                  <v-radio-group
                    v-model="newTicket.type">
                    <v-radio
                      :label="$t('cs.requestTechnicalChoice')"
                      value="INCIDENT" />
                    <v-radio
                      :label="$t('cs.requestInformationChoice')"
                      value="INFORMATION" />
                    <v-radio
                      v-if="false"
                      :label="$t('cs.requestProductChoice')"
                      value="PRODUCT" />
                  </v-radio-group>
                </v-card>
                <v-btn
                  color="primary"
                  @click="stepOn('o')">
                  {{ $t('cs.next') }}
                </v-btn>
              </v-stepper-content>
              <v-stepper-content
                step="2">
                <v-card
                  outlined
                  class="mb-12 pa-4 me-12"
                  min-height="200px">
                  <v-radio-group
                    v-if="newTicket.type === 'INCIDENT'"
                    v-model="newTicket.severity"
                    mandatory>
                    <v-radio
                      color="red"
                      value="SEVERITY_1">
                      <template v-slot:label>
                        <span class="red--text">{{ $t('cs.reuquetSevirity1Label') }}</span>
                      </template>
                    </v-radio>
                    <v-radio
                      color="orange"
                      value="SEVERITY_2">
                      <template v-slot:label>
                        <span class="orange--text">{{ $t('cs.reuquetSevirity2Label') }}</span>
                      </template>
                    </v-radio>
                    <v-radio
                      color="green"
                      value="SEVERITY_3">
                      <template v-slot:label>
                        <span class="green--text">{{ $t('cs.reuquetSevirity3Label') }}</span>
                      </template>
                    </v-radio>
                  </v-radio-group>
                  <v-radio-group
                    v-if="newTicket.type === 'INFORMATION'"
                    v-model="newTicket.infoType"
                    mandatory>
                    <v-radio
                      value="INFO_1">
                      <template v-slot:label>
                        <span class="font-weight-bold">{{ $t('cs.requestINFO_1Prefix') }}: </span>
                        <span>{{ $t('cs.requestINFO_1') }}</span>
                      </template>
                    </v-radio>
                    <v-radio
                      value="INFO_2">
                      <template v-slot:label>
                        <span class="font-weight-bold">{{ $t('cs.requestINFO_2Prefix') }}: </span>
                        <span>{{ $t('cs.requestINFO_2') }}</span>
                      </template>
                    </v-radio>
                    <v-radio
                      value="INFO_3">
                      <template v-slot:label>
                        <span class="font-weight-bold">{{ $t('cs.requestINFO_3Prefix') }}: </span>
                        <span>{{ $t('cs.requestINFO_3') }}</span>
                      </template>
                    </v-radio>
                    <v-radio
                      value="INFO_4">
                      <template v-slot:label>
                        <span class="font-weight-bold">{{ $t('cs.requestINFO_4Prefix') }}: </span>
                        <span>{{ $t('cs.requestINFO_4') }}</span>
                      </template>
                    </v-radio>
                    <v-radio
                      value="INFO_5">
                      <template v-slot:label>
                        <span class="font-weight-bold">{{ $t('cs.requestINFO_5Prefix') }}: </span>
                        <span>{{ $t('cs.requestINFO_5') }}</span>
                      </template>
                    </v-radio>
                    <v-radio
                      value="INFO_6">
                      <template v-slot:label>
                        <span class="font-weight-bold">{{ $t('cs.requestINFO_6Prefix') }}: </span>
                        <span>{{ $t('cs.requestINFO_6') }}</span>
                      </template>
                    </v-radio>
                    <v-radio
                      value="INFO_7">
                      <template v-slot:label>
                        <span class="font-weight-bold">{{ $t('cs.requestINFO_7Prefix') }}: </span>
                        <span>{{ $t('cs.requestINFO_7') }}</span>
                      </template>
                    </v-radio>
                  </v-radio-group>
                  <v-banner
                    max-width="800px"
                    dark
                    color="orange darken-2"
                    icon="mdi-information"
                    elevation="1"
                    v-if="this.newTicket.type === 'PRODUCT'"
                    class="text-center ma-auto mt-5">
                    {{ $t('cs.productQuestionDescription') }}
                    <span class="float-right mt-2">
                      {{ $t('cs.customerSuccessTeam') }}
                    </span>
                  </v-banner>
                </v-card>
                <v-btn
                  dark
                  color="green"
                  @click="stepOn('b')">
                  {{ $t(('cs.prev')) }}
                </v-btn>
                <v-btn
                  color="primary"
                  @click="stepOn('o')">
                  {{ $t(('cs.next')) }}
                </v-btn>
              </v-stepper-content>
              <v-stepper-content
                step="3">
                <v-form
                  ref="formTicketSave"
                  v-model="validTicketSave"
                  lazy-validation>
                  <v-container>
                    <v-row
                      v-if="this.newTicket.type === 'INCIDENT'"
                      cols="12"
                      no-gutters
                      class="me-14">
                      <v-col cols="10">
                        <v-select
                          required
                          :rules="[v => !!v || $t('cs.validateSelectEnvironment')]"
                          ref="environments"
                          v-model="newTicket.environmentId"
                          @blur="$refs.environments.blur();"
                          class="me-10 d-flex"
                          :items="this.environments"
                          item-text="name"
                          item-value="id"
                          :label="$t('cs.requestEnvironmentScope')" />
                      </v-col>
                      <v-col cols="2">
                        <v-btn
                          class="mt-8 d-flex"
                          target="_blank"
                          :href="addNewEnvironment"
                          depressed
                          color="primary">
                          <span v-if="!isMobile">{{ $t('cs.addEnvironment') }}</span>
                          <v-icon
                            dark
                            v-if="isMobile">
                            mdi-desktop-classic
                          </v-icon>
                        </v-btn>
                      </v-col>
                    </v-row>
                    <v-row
                      v-if="this.newTicket.type === 'PRODUCT'"
                      cols="12"
                      no-gutters
                      class="me-14">
                      <v-menu
                        v-model="callMenu1"
                        :close-on-content-click="false"
                        :nudge-right="40"
                        transition="scale-transition"
                        offset-y
                        min-width="auto">
                        <template v-slot:activator="{ on, attrs }">
                          <v-text-field
                            required
                            :rules="[v => !!v || $t('cs.validateAddTitle')]"
                            v-model="newTicket.startDate"
                            :label="$t('cs.requestCallMeBetween')"
                            prepend-icon="mdi-calendar"
                            readonly
                            v-bind="attrs"
                            v-on="on" />
                        </template>
                        <v-date-picker
                          :min="minStartDate"
                          v-model="newTicket.startDate"
                          @input="callMenu1 = false" />
                      </v-menu>
                      <v-menu
                        v-model="callMenu2"
                        :close-on-content-click="false"
                        :nudge-right="40"
                        transition="scale-transition"
                        offset-y
                        min-width="auto">
                        <template v-slot:activator="{ on, attrs }">
                          <v-text-field
                            v-model="newTicket.endDate"
                            :label="$t('cs.and')"
                            prepend-icon="mdi-calendar"
                            readonly
                            v-bind="attrs"
                            v-on="on" />
                        </template>
                        <v-date-picker
                          :min="newTicket.startDate"
                          v-model="newTicket.endDate"
                          @input="callMenu2 = false" />
                      </v-menu>
                    </v-row>
                    <v-row class="me-4">
                      <v-col>
                        <v-text-field
                          required
                          :rules="[v => !!v || $t('cs.validateAddTitle')]"
                          v-model="newTicket.title"
                          class="me-10"
                          :label="$t('cs.requestTitleLabel')" />
                      </v-col>
                    </v-row>
                    <v-row
                      no-gutters
                      class="me-16">
                      <v-col
                        cols="12">
                        <cs-custom-editor
                          required
                          ref="csFeedEditor"
                          id="csEditor"
                          :placeholder="$t('cs.description') + ' ...'"
                          v-model="newTicket.description" />
                      </v-col>
                      <v-col
                        id="ticket-attachments"
                        cols="12">
                        <v-btn
                          v-if="this.newTicket.type !== 'PRODUCT'"
                          class="mx-2 ma-5 float-right"
                          fab
                          dark
                          large
                          color="purple"
                          @click="openAttachmentDrawer">
                          <v-icon>
                            mdi-attachment
                          </v-icon>
                          <v-progress-circular
                            v-if="attachmentsCount"
                            :class="this.uploading ? 'uploading' : ''"
                            indeterminate>
                            {{ attachmentsCount }}
                          </v-progress-circular>
                        </v-btn>
                      </v-col>
                      <v-col>
                        <span
                          v-if="this.newTicket.type !== 'PRODUCT'"
                          class="text-caption float-right">
                          <v-icon class="blue--text pb-1">mdi-information</v-icon>
                          {{ $t('cs.logWarning') }}
                        </span>
                        <div :class="isProductRequest">
                          <v-btn
                            dark
                            color="green"
                            @click="stepOn('b')">
                            {{ $t(('cs.prev')) }}
                          </v-btn>
                          <v-btn
                            :loading="isSaving"
                            color="primary"
                            @click="saveTicket">
                            {{ $t(('cs.save')) }}
                          </v-btn>
                        </div>
                      </v-col>
                    </v-row>
                  </v-container>
                </v-form>
              </v-stepper-content>
            </v-stepper-items>
          </v-stepper>
        </v-row>
        <cs-editor-snackbar />
      </v-container>
    </v-main>
  </v-app>
</template>

<script>

export default {
  data: () => ({
    step: 1,
    newTicket: {
      title: null,
      environmentId: null,
      attachments: [],
      description: null,
      infoType: null,
      type: 'INCIDENT',
      severity: 'SEVERITY_3',
      spaceGroupId: eXo.env.portal.spaceGroup,
      startDate: (new Date(Date.now() - (new Date()).getTimezoneOffset() * 60000)).toISOString().substr(0, 10),
      endDate: null,
      uploads: []
    },
    minStartDate: (new Date(Date.now() - (new Date()).getTimezoneOffset() * 60000)).toISOString().substr(0, 10),
    cSpaceInfo: {},
    environments: [],
    initialized: false,
    uploading: false,
    callMenu1: false,
    callMenu2: false,
    validTicketSave: true,
    errorMessage: '',
    isSaving: false
  }),
  computed: {
    csSpaceId() {
      return eXo.env.portal.spaceId;
    },
    csSpaceGroupId() {
      return eXo.env.portal.spaceGroup;
    },
    attachmentsCount() {
      return this.newTicket.attachments && this.newTicket.attachments.length;
    },
    addNewEnvironment() {
      return `${eXo.env.portal.context}/g/:spaces:${eXo.env.portal.spaceGroup}/${eXo.env.portal.spaceName}/environments?new=true`;
    },
    isProductRequest() {
      return this.newTicket.type === 'PRODUCT' ? 'mt-2': 'mt-0';
    },
    isEnvironmentSet() {
      return this.newTicket.environmentId;
    },
    isTicketSummarySet() {
      return this.newTicket.title && this.newTicket.title.length !== 0;
    },
    isTicketDescriptionSet() {
      return this.newTicket.description && this.newTicket.description.length !== 0;
    },
    uploadsIds() {
      return this.newTicket.attachments && this.newTicket.attachments.map(attachment => {
        return attachment.uploadId? attachment.uploadId : attachment.id ;
      });
    },
    isMobile() {
      return this.$vuetify.breakpoint.name === 'xs' || this.$vuetify.breakpoint.name === 'sm' ;
    }
  },
  watch: {
    step: function (val) {
      if (val === 3) {
        const message = localStorage.getItem('exo-activity-composer-message');
        const attachments = JSON.parse(localStorage.getItem('exo-activity-composer-attachments'));
        if (message) {
          this.$refs.csFeedEditor.initCKEditorData(message);
          localStorage.removeItem('exo-activity-composer-message');
        }
        if (attachments) {
          this.newTicket.attachments = attachments;
          localStorage.removeItem('exo-activity-composer-attachments');
        }
      }
    },
  },
  created() {
    this.getCustomerSpaceInfo();
    this.getCSpaceSavedEnvironments();
  },
  methods: {
    openAttachmentDrawer() {
      const attachmentDrawerParams = {
        'sourceApp': 'customerSpaceApp',
        'attachToEntity': false,
        'attachments': this.newTicket.attachments
      };
      if (this.newTicket.attachments.length === 0) {
        document.dispatchEvent(new CustomEvent('open-attachments-app-drawer', {detail: attachmentDrawerParams}));
      }
      else {
        document.dispatchEvent(new CustomEvent('open-attachments-list-drawer', {detail: attachmentDrawerParams}));
      }
    },
    setUploadingCount: function(uploadingCount) {
      this.uploading = uploadingCount > 0;
    },
    getCSpaceSavedEnvironments(){
      this.$csService.getCustomerSpaceEnvironments(this.csSpaceGroupId).then(data => {
        data.forEach(env => {
          this.environments.push({'name': env.name,'id': env.id});
        });
      });
    },
    saveTicket() {
      if (this.isSaving) {
        this.$root.$emit('show-validation-error', true, 'cs.ticket.is.being.saved', 'warning', true, null);
        return;
      }
      this.$refs.formTicketSave.validate();
      if ( this.newTicket.type === 'INCIDENT' && !this.isEnvironmentSet) {
        this.$root.$emit('show-validation-error', true, 'cs.validateSelectEnvironment', 'error', true, null);
        return;
      }
      if (!this.isTicketSummarySet){
        this.$root.$emit('show-validation-error', true, 'cs.validateAddTitle', 'error', true, null);
        return;
      }
      if (!this.isTicketDescriptionSet) {
        this.$root.$emit('show-validation-error', true, 'cs.validateAddDescription', 'error', true, null);
        return;
      }
      if (this.newTicket) {
        this.newTicket.startDate = (new Date(Date.now() - (new Date()).getTimezoneOffset() * 60000))
          .toUTCString().replace('GMT','').trim();
        if (this.newTicket.type === 'INFORMATION') {
          const descriptionTitle = `<blockquote><b>${this.$t(`cs.request${this.newTicket.infoType}Prefix`)}</b>${this.$t(`cs.request${this.newTicket.infoType}`)}</blockquote>`;
          this.newTicket.description = descriptionTitle + this.newTicket.description;
        }
        this.newTicket.uploads = this.uploadsIds;
        this.isSaving = true;
        this.$ticketService.createTicket(this.newTicket).then( createdTicket => {
          if (createdTicket) {
            const link = `${eXo.env.portal.context}/g/:spaces:${eXo.env.portal.spaceGroup}/${eXo.env.portal.spaceName}/forum/topic/${createdTicket.id}`;
            this.$root.$emit('show-validation-error', true, 'cs.ticketSubmitted', 'success', false, link);
            this.clearTicketForm();
          }
        }).catch(() => {
          this.$root.$emit('show-validation-error', true, 'cs.ticketSubmitionError', 'error', true, null);
        }).finally( () => {
          this.isSaving = false;
        });
      }
    },
    clearTicketForm() {
      this.$refs.formTicketSave.reset();
      this.$refs.csFeedEditor.initCKEditorData('');
      this.newTicket.attachments = [];
    },
    getCustomerSpaceInfo() {
      this.$csService.getCustomerSpaceInfo(this.csSpaceGroupId).then(data => {
        this.cSpaceInfo = data;
      });
    },
    init() {
      this.$nextTick().then(() => {
        this.$refs.csFeedEditor.initCKEditor(false);
        this.initialized = true;
      });
    },
    reset() {
      if (this.$refs.csFeedEditor) {
        this.$refs.csFeedEditor.destroyCKEditor();
        this.initialized = false;
      }
    },
    stepOn(s) {
      if (s === 'o' && this.step <= 3) {
        this.step++;
      }
      if (s === 'b' && this.step >= 1) {
        this.step--;
      }
    }
  },
  beforeDestroy() {
    this.reset();
  },
};
</script>
