<template>
  <v-app>
    <cs-sticky-mini-ticket-menu
      :status="ticket.status"
      :available-states="availableStates"
      :available-severities="this.ticket.availableSeverities"
      :severity="ticket.severity"
      :edit-mode="editMode"
      :rate-status="customerSatisfaction"
      :rate-reason="customerSatisfactionReason"
      :is-rate-allowed="isRateAllowed"
      :is-current-assigned="isCurrentAssigned"
      :rate-loaded="infoLoaded"
      :attached-task="this.ticket.attachedJira"
      :attached-tasks-list="attachedTasksList"
      :attached-tasks-with-status="this.ticket.attachedTasksWithStatus"
      :reason="this.ticket.reason"
      :available-reasons="availableReasons"
      :can-manage="userSettings.canManage"
      :is-full-ticket-menu="isFullTicketMenu" />
    <v-subheader
      v-if="isFullTicketMenu"
      class="titleTicket mt-2"
      v-html="ticket.title" />
    <v-divider
      v-if="isFullTicketMenu" />
    <v-contanier
      v-if="isFullTicketMenu"
      fluid
      :class="warningStyle + ' pa-1 ml-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"
            :is-rate-allowed="isRateAllowed"
            :is-current-assigned="isCurrentAssigned"
            :cs-space-info="this.cSpaceInfo"
            :is-full-ticket-menu="isFullTicketMenu" />
        </v-col>
        <v-col
          lg="5"
          md="4"
          sm="6">
          <v-form>
            <cs-ticket-edit-mode-action
              :edit-mode="editMode"
              :can-manage="userSettings.canManage" />
            <v-row no-gutters>
              <v-col
                align="center"
                md="6"
                sm="6">
                <cs-ticket-statuses
                  :edit-mode="editMode"
                  :status="this.ticket.status"
                  :available-states="availableStates" />
                <cs-ticket-status-reason
                  :edit-mode="editMode"
                  :reason="this.ticket.reason"
                  :available-reasons="availableReasons" />
                <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">
                <cs-ticket-severities
                  :edit-mode="editMode"
                  :severity="this.ticket.severity"
                  :available-severities="this.ticket.availableSeverities" />
                <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" />
                <cs-ticket-attached-tasks
                  :edit-mode="editMode"
                  :can-manage="userSettings.canManage"
                  :attached-task="this.ticket.attachedJira"
                  :attached-tasks-list="attachedTasksList"
                  :attached-tasks-with-status="this.ticket.attachedTasksWithStatus" />
              </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,
    isFullTicketMenu: true
  }),
  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);
    },
    isCurrentAssigned() {
      return  this.userSettings.userName === this.ticket.assignee;
    },
    isRateAllowed() {
      return this.ticket.assignee && !this.isCurrentAssigned ?  true : false;
    },
    warningStyle() {
      return this.ticket.warning? `${this.ticket.warning} white` : 'grey lighten-5' ;
    }
  },
  created() {
    this.loadTicketData();
    this.getSupportMembers();
    this.initUserSettings();
    this.$root.$on('update-customer-rate', this.updateCustomerSatisfaction);
    this.$root.$on('update-ticket', this.updateTicketFromSticky);
    this.$root.$on('remove-task-from-ticket', this.removeTask);
    this.$root.$on('switch-edit-mode', this.switchEditMode);
    document.getElementById('UISiteBody').addEventListener('scroll', this.isFullTicketMenuHeader);
  },
  beforeDestroy() {
    this.$root.$off('update-customer-rate', this.updateCustomerSatisfaction);
    this.$root.$off('update-ticket', this.updateTicketFromSticky);
    this.$root.$off('remove-task-from-ticket', this.removeTask);
    this.$root.$off('switch-edit-mode', this.switchEditMode);
    document.getElementById('UISiteBody').removeEventListener('scroll', this.isFullTicketMenuHeader);
  },
  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.split('/forum/topic/')[1].split('/')[0];
        this.$ticketService.getTicket(ticketId).then((data) => {
          this.ticket = data;
          this.loadTicketFlowStates(this.ticket.flow);
          this.getCustomerSpaceEnvironment(this.ticket.environmentId);
          this.initCSpaceInfo();
          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() {
      let spaceGroupId = eXo.env.portal.spaceGroup;
      if (!spaceGroupId) {
        spaceGroupId = this.ticket.spaceGroupId.split('/spaces/')[1];
      }
      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.customerSatisfied !== status) {
        this.ticket.customerSatisfied = status;
        this.ticket.rateReason = reason;
        this.updateTicket(true);
      } else {
        this.ticket.rateReason = reason;
        this.updateTicket(false);
      }
    },
    switchEditMode(mode){
      this.editMode = mode;
    },
    removeTask(task){
      const index = this.attachedTasksList.indexOf(task);
      this.attachedTasksList.splice(index, 1);
      this.ticket.attachedJira = this.attachedTasksList.join(' ');
      this.updateTicket(false);
    },
    filterSuccessors(successors) {
      if (successors && successors !== '') {
        return this.userSettings & this.userSettings.canManage ? successors :
          successors.filter(successor => this.evaluateStateRole(successor.state));
      }
      return '';
    },
    isFullTicketMenuHeader() {
      const siteBody = document.getElementById('UISiteBody');
      const menuHeader = document.getElementById('CSTicketMenuApplication');
      const topicDetails = document.getElementsByClassName('containerTopicDetail')[0];
      this.isFullTicketMenu = siteBody.scrollTop < 400; //menuHeader.offsetHeight
      if (!this.isFullTicketMenu) {
        menuHeader.style.position = 'fixed';
        topicDetails.style.marginTop = '440px';
      } else {
        menuHeader.style.position = 'relative';
        topicDetails.style.marginTop = '10px';
      }
    },
    updateTicketFromSticky(status, reason, severity, tasks, rate) {
      this.ticket.status = status? status : this.ticket.status;
      this.ticket.reason = reason? reason :  this.ticket.reason;
      this.ticket.severity = severity? severity : this.ticket.severity;
      this.ticket.attachedJira = tasks? tasks : this.ticket.attachedJira;
      this.updateTicket(rate);
    }
  },
};
</script>
