<template>
  <user-dashboard-container page-class="guarantee-details ticket-messenger" :panel-title="conversation.title">
    <div class="messenger">
      <h3 class="messenger-title">پیام ها:</h3>
      <div class="messenger-body">
        <div class="messages" :class="!conversation.messages.length ? 'no-msg' : null">
          <!-- no-msg -->
          <p v-if="!conversation.messages.length">هیچ پیامی وجود ندارد.</p>

          <div
            v-for="item in conversation.messages"
            :key="item._id"
            class="message user"
            :class="[item.isUser ? 'user' : 'asan-admin', !item.read && !item.isUser ? 'unread' : null]"
          >
            <div class="txt">
              <img v-if="item.image" :src="item.image" alt="" />
              <p>{{ item.message }}</p>
              <p class="date">{{ $jDateTime(item.created_at) }}</p>
            </div>
            <user-icon />
          </div>
        </div>
        <div class="newMsg">
          <div class="relativePos">
            <input v-model="message" type="text" placeholder="پیام خود را بنویسید" />
            <label for="file"></label>
            <input id="file" ref="attachment" type="file" @change="preview" />
            <img v-if="attachment" :src="attachment" alt="" />
            <i v-if="attachment" id="clearFile" class="fas fa-times-circle" @click="clearFile"></i>
            <button class="btn btn-primary" :disabled="!message && !attachment" @click="sendMessage">ارسال</button>
            <div class="validationMsg">
              <p v-if="validation.message">{{ validation.message.msg }}</p>
              <p v-if="validation.image">{{ validation.image.msg }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </user-dashboard-container>
</template>

<script>
import axiosUploadProcess from '@/mixins/axiosUploadProcess'

export default {
  name: 'AccountTicketDetails',
  mixins: [axiosUploadProcess],
  layout: 'user',
  async asyncData({ $axios, params, error }) {
    try {
      const conversation = await $axios.get(`/api/user/getTicket/${params.ticket}`)
      return {
        conversation: conversation.data
      }
    } catch (e) {
      error({ status: 404, message: 'Page not found' })
    }
  },
  data() {
    return {
      conversation: null,
      message: '',
      attachment: '',
      validation: {}
    }
  },
  methods: {
    preview(event) {
      this.attachment = URL.createObjectURL(event.target.files[0])
    },
    clearFile() {
      this.attachment = null
      this.$refs.attachment.value = null
    },
    sendMessage() {
      this.validation = {}
      const data = new FormData()
      data.append('message', this.message)
      if (this.$refs.attachment.files[0]) data.append('image', this.$refs.attachment.files[0])

      this.$axios
        .post(`/api/user/addMessageToTicket/${this.conversation._id}`, data, this.axiosConfig)
        .then(res => {
          this.$message({
            type: 'success',
            message: 'پیام با موفقیت ارسال شد.'
          })
          this.attachment = ''
          this.message = ''
          this.$refs.attachment.value = null
          this.conversation = res.data
          setTimeout(() => {
            window.scrollTo(0, document.body.scrollHeight)
          }, 100)
        })
        .catch(err => {
          if (err.response.data.status === 401) {
            return this.$message({
              type: 'warning',
              message: 'لطفا دوباره وارد حساب خود شوید'
            })
          }
          if (err.response.status === 422) this.validation = err.response.data.validation
          else console.log(err)
        })
    }
  }
}
</script>
