<template>
  <v-app>
    <v-subheader
      class="titleTicket mt-2"
      v-html="ticket.title" />
    <v-divider />
    <v-contanier fluid class="grey lighten-5 pa-1">
      <v-row no-gutters>
        <v-col
          align="center"
          lg="3"
          md="4"
          sm="6">
          <cs-ticket-rate
            :rate-status="customerSatisfaction"
            :rate-reason="customerSatisfactionReason"
            :rate-loaded="infoLoaded" />
        </v-col>
        <v-col
          lg="5"
          md="4"
          sm="6">
          <v-form>
            <div>
              <v-btn
                x-small
                outlined
                fab
                color="blue darken-2"
                v-if="userSettings.canManage"
                @click="switchToEditMode"
                class="float-right mt-2">
                <v-icon>mdi-square-edit-outline</v-icon>
              </v-btn>
            </div>
            <div class="mt-6 float-right">
              <v-btn
                x-small
                outlined
                fab
                color="green darken-2"
                v-if="editMode"
                @click="switchToSaveMode"
                class="float-right mt-2 cs-pos-absolute">
                <v-icon>mdi-content-save-settings-outline</v-icon>
              </v-btn>
            </div>
            <v-row no-gutters>
              <v-col
                align="center"
                md="6"
                sm="6">
                <v-select
                  ref="status"
                  :readonly="!editMode"
                  @change="updateTicket(false)"
                  @blur="$refs.status.blur()"
                  v-model="ticket.status"
                  :items="availableStates"
                  :label="$t('cs.status')"
                  item-text="state"
                  item-value="stateValue"
                  return-object
                  standard>
                  <template v-slot:selection="{item, index}">
                    <span class="text-capitalize">{{ item }}</span>
                  </template>
                </v-select>
                <v-combobox
                  class="combo-reason"
                  :readonly="!editMode"
                  ref="reason"
                  @blur="$refs.reason.blur();"
                  @change="updateTicket(false)"
                  v-model="ticket.reason"
                  :items="availableReasons"
                  :label="$t('cs.reason')"
                  chips
                  dense>
                  <template v-slot:selection="{ attrs, item, parent, selected }">
                    <v-tooltip
                      right
                      class="sc-custom-tooltip">
                      <template v-slot:activator="{ on }">
                        <v-chip
                          pill
                          class="text-caption"
                          v-on="on"
                          color="grey">
                          {{ formatEllipsis(item, 30) }}
                        </v-chip>
                      </template>
                      <span>{{ item }}</span>
                    </v-tooltip>
                  </template>
                </v-combobox>
                <v-select
                  ref="type"
                  :readonly="!editMode"
                  @change="updateTicket(false)"
                  @blur="$refs.type.blur()"
                  v-model="ticket.type"
                  :items="ticket.availableTypes"
                  :label="$t('cs.type')"
                  item-text="type"
                  item-value="typeValue"
                  return-object
                  standard />
                <v-select
                  ref="owner"
                  :readonly="!editMode"
                  @change="updateTicket(false)"
                  @blur="$refs.owner.blur()"
                  v-model="ticket.owner"
                  :items="ticket.availableOwners"
                  :label="$t('cs.owner')"
                  item-text="owner"
                  item-value="ownerValue"
                  return-object
                  standard />
              </v-col>
              <v-col
                align="center"
                md="6"
                sm="6">
                <v-select
                  ref="severity"
                  :readonly="!editMode"
                  @change="updateTicket(false)"
                  @blur="$refs.severity.blur()"
                  v-model="ticket.severity"
                  :items="formatSeverities(ticket.availableSeverities)"
                  :label="$t('cs.ticketseverity')"
                  item-text="severity"
                  item-value="severityValue"
                  standard>
                  <template v-slot:selection="{item, index}">
                    <span>{{ $t(item.severity) }}</span>
                  </template>
                  <template v-slot:item="{item, index}">
                    <span>{{ item.severityValue }}</span>
                  </template>
                </v-select>
                <v-select
                  ref="assignee"
                  :readonly="!editMode"
                  @change="updateTicket(false)"
                  @blur="$refs.assignee.blur()"
                  v-model="ticket.assignee"
                  :items="supportAgents"
                  :label="$t('cs.assignee')"
                  item-text="assignee"
                  item-value="assigneeValue"
                  standard>
                  <template
                    v-slot:selection="{item, index}">
                    <v-chip pill>
                      <v-avatar left>
                        <v-img :src="ticket.assigneeAvatar" />
                      </v-avatar>
                      <span class="text-caption">{{ item.assignee }}</span>
                    </v-chip>
                  </template>
                </v-select>
                <v-text-field
                  :label="$t('cs.created')"
                  readonly
                  v-model="ticket.startDate" />
                <v-text-field
                  v-if="editMode"
                  @blur="updateTicket(false)"
                  v-model="ticket.attachedJira"
                  :label="$t('cs.attachedJira')" />
                <div
                  v-if="!editMode">
                  <label
                    v-if="ticket.attachedJira"
                    class="v-label v-label--active theme--light cs-custom-label"
                    for="tasks">
                    {{ $t('cs.attachedJira') }}
                  </label>
                  <span
                    id="tasks"
                    class="pa-1"
                    v-for="task in attachedTasksList"
                    :key="task">
                    <v-tooltip
                      right
                      class="cs-custom-tooltip">
                      <template v-slot:activator="{ on, attrs }">
                        <v-chip
                          v-on="on"
                          v-bind="attrs"
                          :close="userSettings.canManage"
                          class="mt-1"
                          :href="taskLink(task)"
                          target="_blank"
                          :color="taskStatusColor(ticket.attachedTasksWithStatus[task])"
                          text-color="white"
                          @click:close="removeTask(task)">
                          <v-icon left>mdi-bug</v-icon>
                          {{ task }}
                        </v-chip>
                      </template>
                      <span>{{ ticket.attachedTasksWithStatus[task] }}</span>
                    </v-tooltip>
                  </span>
                </div>
              </v-col>
            </v-row>
            <v-row
              v-if="filterSuccessors(availableSuccessors).length > 0"
              no-gutters
              class="mb-1">
              <v-col
                cols="12"
                class="mt-1">
                <span>{{ $t('cs.changeStatusTo') }} : </span>
                <span
                  v-for="successor in availableSuccessors"
                  :key="successor.state">
                  <v-btn
                    depressed
                    class="me-2"
                    color="primary"
                    v-if="evaluateStateRole(successor.state)"
                    @click="updateStatus(successor)">
                    {{ successor.state }}
                  </v-btn>
                </span>
              </v-col>
            </v-row>
          </v-form>
        </v-col>
        <v-col
          cols="12"
          lg="4"
          md="4"
          sm="12"
          xs="12">
          <cs-environment
            :environment="environment"
            :space-info="cSpaceInfo" />
        </v-col>
      </v-row>
    </v-contanier>
    <v-divider />
  </v-app>
</template>
<script>

export default {
  props: {
    ticket: {
      type: Object,
      default: function () {return {};},
    },
  },
  data: () => ({
    flowStates: [],
    availableStates: [],
    supportAgents: [],
    environment: {},
    userSettings: {},
    cSpaceInfo: {},
    editMode: false,
    infoLoaded: false
  }),
  computed: {
    availableReasons () {
      return (this.flowStates.filter(flow => flow.state === this.ticket.status)[0]) ?
        this.flowStates.filter(flow => flow.state === this.ticket.status)[0].reason : '';
    },
    availableSuccessors () {
      return (this.flowStates.filter(flow => flow.state === this.ticket.status)[0]) ?
        this.flowStates.filter(flow => flow.state === this.ticket.status)[0].successors : '';
    },
    customerSatisfaction() {
      return this.ticket.customerSatisfied;
    },
    customerSatisfactionReason() {
      return this.ticket.rateReason;
    },
    attachedTasksList() {
      return this.ticket.attachedJira && this.ticket.attachedJira.split(/(\s+)/).filter( e => e.trim().length > 0);
    },
  },
  created() {
    this.loadTicketData();
    this.getSupportMembers();
    this.initUserSettings();
    this.initCSpaceInfo();
    this.$root.$on('update-customer-rate', this.updateCustomerSatisfaction);
  },
  destroyed() {
    this.$root.$off('update-customer-rate', this.updateCustomerSatisfaction);
  },
  methods: {
    extractAvailableStates(flowStates) {
      for (let flow = 0; flow < flowStates.length; flow++ ) {
        this.availableStates.push(flowStates[flow].state);
      }
    },
    loadTicketData() {
      const locationHref = window.location.href;
      if (locationHref.indexOf('/forum/topic/') !== -1) {
        const ticketId = locationHref.substring(locationHref.indexOf('/forum/topic/') + '/forum/topic/'.length);
        this.$ticketService.getTicket(ticketId).then((data) => {
          this.ticket = data;
          this.loadTicketFlowStates(this.ticket.flow);
          this.getCustomerSpaceEnvironment(this.ticket.environmentId);
          this.infoLoaded = true;
        });
      }
    },
    loadTicketFlowStates(flowName) {
      this.$ticketService.getTicketFlowStates(flowName).then((data) => {
        this.flowStates = data;
        this.extractAvailableStates(this.flowStates);
      });
    },
    getSupportMembers() {
      this.$csInfoService.getSupportMembers().then((data) => {
        data.filter(user => {
          this.supportAgents.push({'assignee': user.fullName, 'assigneeValue': user.userName});
        });
      });
    },
    getCustomerSpaceEnvironment(id) {
      this.$csService.getCustomerSpaceEnvironment(id).then((data) => {
        this.environment = data;
      });
    },
    updateStatus(successor) {
      this.ticket.status = successor.state;
      if (this.userSettings.canManage) {
        this.ticket.reason = successor.reason[0];
      } else {
        this.ticket.reason = successor.reason[1];
      }
      this.updateTicket(false);
    },
    updateTicket(rate) {
      this.$ticketService.updateTicket(this.ticket, rate).then((updatedTicket) => {
        this.ticket = updatedTicket;
      });
    },
    initUserSettings() {
      this.$csService.getCustomerSpaceUserSettings().then((settings) => {
        this.userSettings = settings;
      });
    },
    initCSpaceInfo() {
      const spaceGroupId = eXo.env.portal.spaceGroup;
      this.$csService.getCustomerSpaceInfo(spaceGroupId).then((data) => {
        this.cSpaceInfo = data;
      });
    },
    evaluateStateRole(state) {
      const role = this.flowStates.filter(flow => flow.state === state)[0] ?
        this.flowStates.filter(flow => flow.state === state)[0].role : '';
      return (role === 'any' || this.userSettings && this.userSettings.canManage);
    },
    updateCustomerSatisfaction(status, reason) {
      if (this.ticket) {
        this.ticket.customerSatisfied = status;
        this.ticket.rateReason = reason;
        this.updateTicket(true);
      }
    },
    switchToEditMode() {
      this.editMode = true;
    },
    switchToSaveMode() {
      this.editMode = false;
    },
    removeTask(task){
      const index = this.attachedTasksList.indexOf(task);
      this.attachedTasksList.splice(index, 1);
      this.ticket.attachedJira = this.attachedTasksList.join(' ');
      this.updateTicket(false);
    },
    formatEllipsis(txt, len) {
      return txt.length >= len ? `${txt.substring(0, len)} ...` : txt;
    },
    taskLink(taskId) {
      return `${eXo.env.portal.context}/${eXo.env.portal.portalName}/tasks/taskDetail/${taskId}`;
    },
    taskStatusColor(status) {
      return status? this.$csUtils.stringToRGB(status) : 'grey';
    },
    formatSeverities(severities) {
      if (severities) {
        const arr = new Array();
        severities.filter(severity => {
          arr.push({'severity': `cs.${severity}`, 'severityValue': severity});
        });
        return arr;
      }
    },
    filterSuccessors(successors) {
      if (successors && successors !== '') {
        return this.userSettings & this.userSettings.canManage ? successors :
          successors.filter(successor => this.evaluateStateRole(successor.state));
      }
      return '';
    }
  },
};
</script>
