<!-- @format -->

<script setup>
import { ref } from 'vue'
import { useMessage } from './useMessage'
import { ossUploadApi } from '@/api/model/common'

const { sendMessage } = useMessage()

const messageValue = ref('')
const input = ref(null)
const sending = ref(false)

async function onSendMessage() {
  if (messageValue.value.trim()) {
    sending.value = true
    await sendMessage(messageValue.value, '1')
    sending.value = false
    messageValue.value = ''
  }
}
function uploadImg() {
  input.value?.click()
}
function inputChange(e) {
  const file = e.target.files[0]
  if (sending.value)
    return ElMessage.error('Sending message, please wait')

  if (file.size > 1024 * 1024 * 10)
    return ElMessage.error('Image size cannot exceed 10M')

  sendImgMessage(file)
}
async function sendImgMessage(file) {
  try {
    sending.value = true
    const imgUrl = await ossUploadApi(file)
    await sendMessage(imgUrl, '2')
    sending.value = false
  }
  catch (error) {
    ElMessage.error('send failed')
    console.log(error)
  }
  finally {
    sending.value = false
  }
}
</script>

<template>
  <div class=" bg-#fff b-rd-6px">
    <div class="px-15px py-12px">
      <img
        src="@/assets/images/addImage.png"
        class="w-24px h-24px cursor-pointer"
        @click="uploadImg"
      >
      <input
        ref="input"
        type="file"
        class="hidden"
        accept="image/*"
        @change="inputChange"
      >
    </div>
    <div class="p-10px pos-relative">
      <el-input
        v-model="messageValue"
        type="textarea"
        placeholder="Please enter your message here"
        class="!b-0 custom-textarea"
        :rows="6"
        @press-enter.prevent="onSendMessage"
      />
      <el-button
        :disabled="!messageValue"
        class="pos-absolute w-160px bottom-20px right-20px px-30px py-10px !h-40px !bg-#C58C64 !text-#fff" @click="onSendMessage"
      >
        Send
      </el-button>
    </div>
  </div>
</template>

<style lang="less" scoped>
::v-deep(.custom-textarea) {
  .el-textarea__inner{
    border: none !important;
    box-shadow: unset !important;
  }
}
</style>
