<template>
  <div>
    <CustomSubHeader>
      <CBreadcrumb class="border-0 mb-0">{{ title }}</CBreadcrumb>
      <CButton size="sm" color="primary" class="mr-auto" @click="$router.go(-1)">برگشت به صفحه قبل</CButton>
    </CustomSubHeader>

    <CCard>
      <CCardHeader>
        <slot name="header">
          <CIcon name="cil-grid" />
          {{ list_title }}
        </slot>
      </CCardHeader>
      <CCardBody>
        <CRow>
          <CCol lg="12">
            <CForm>
              <CInput
                label="نام مشتری"
                horizontal
                disabled
                :value="conversation.user_id.first_name + ' ' + conversation.user_id.last_name"
              />
              <CInput label="شناسه وریتی مشتری" horizontal disabled :value="conversation.user_id.verity_businessCode" />
              <CInput
                label="شناسه پاناتک مشتری"
                horizontal
                disabled
                :value="conversation.user_id.panatech_businessCode"
              />
              <CInput label="شماره پذیرش مربوطه" horizontal disabled :value="conversation.transaction_id || '-'" />
              <CTextarea label="عنوان تیکت" horizontal disabled rows="5" :value="conversation.title" />
            </CForm>

            <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>
                  <!-- user -->
                  <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">
                        <span>{{ $jDateTime(item.created_at) }}</span>
                        <span v-if="item.user_id.first_name">
                          ({{ item.user_id.first_name + ' ' + item.user_id.last_name }})
                        </span>
                      </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>
          </CCol>
        </CRow>
      </CCardBody>
    </CCard>
  </div>
</template>

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

export default {
  name: 'AddminTicketDetails',
  mixins: [axiosUploadProcess],
  layout: 'admin',
  async asyncData({ $axios, params, error }) {
    try {
      const conversation = await $axios.get(`/api/admin/ticket/${params.ticket}`)
      return {
        conversation: conversation.data
      }
    } catch (e) {
      error({ status: 404, message: 'Page not found' })
    }
  },
  data() {
    return {
      title: 'تیکت',
      list_title: 'لیست',
      conversation: null,
      message: '',
      attachment: '',
      validation: {}
    }
  },
  head() {
    return {
      title: this.title
    }
  },
  computed: {},
  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/admin/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>
