<template>
  <user-dashboard-container page-class="tickets" panel-title="لیست تیکت ها">
    <div class="tableBox">
      <table class="tickets">
        <thead>
          <tr>
            <th class="index">ردیف</th>
            <th class="title">عنوان</th>
            <th class="transactionId">شماره پذیرش</th>
            <th class="date">تاریخ ایجاد مکالمه</th>
            <th class="details">جزئیات</th>
          </tr>
        </thead>
        <tbody>
          <template v-if="conversations.length">
            <tr v-for="(item, index) in conversations" :key="item._id" :title="item.title">
              <td class="index">
                <span>{{ index + 1 }}</span>
              </td>
              <td class="title">
                <span class="singleLineTxt">{{ item.title }}</span>
              </td>
              <td class="transactionId">
                <span>{{ item.transaction_id ? item.transaction_id : '-' }}</span>
              </td>
              <td class="date">
                <span>{{ $jDate(item.created_at) }}</span>
              </td>
              <td class="rowButtons details">
                <nuxt-link
                  :to="{ name: 'account-tickets-ticket', params: { ticket: item._id } }"
                  class="btn btn-primary"
                >
                  <span>مشاهده</span>
                  <i v-if="hasUnread(item._id)">{{ hasUnread(item._id) }}</i>
                </nuxt-link>
              </td>
            </tr>
          </template>
          <tr v-else>
            <td class="noItem">
              <span>هیچ اطلاعاتی وجود ندارد</span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <table-notice />
  </user-dashboard-container>
</template>

<script>
export default {
  name: 'AccountTicketList',
  layout: 'user',
  async asyncData({ $axios, error }) {
    try {
      const conversations = await $axios.get('/api/user/ticketConversations')
      return {
        conversations: conversations.data
      }
    } catch (e) {
      error({ status: 500, message: 'There is a problem here' })
    }
  },
  data() {
    return {
      conversations: null
    }
  },
  methods: {
    hasUnread(id) {
      const conversation = this.conversations.filter(item => item._id === id)[0]
      return conversation.messages.filter(item => !item.read && !item.isUser).length
    }
  }
}
</script>
