<template>
  <div class="bg-[#f8f9fa] border-t-2 w-full"  v-loading.fullscreen.lock="uploadLoading">
    <form @submit.prevent="onSendMsg">
      <label for="chat" class="sr-only">Your message</label>
      <div class="flex items-center px-3 py-2 rounded-lg">
        <el-upload
          v-model:file-list="fileList"
          ref="upload"
          :headers="uploadHeaders"
          :action="uploadUrl"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :show-file-list="false"
          :limit="1"
          :auto-upload="true"
          :before-upload="handleBeforeUpload"
          accept="image/*"
          :on-success="handleSuccess"
          :on-error="handleError"
          :on-exceed="handleExceed">
          <button
            type="button"
            class="inline-flex justify-center p-2 text-gray-500 rounded-lg cursor-pointer hover:text-indigo-900 hover:bg-gray-100 dark:text-gray-400 dark:hover:text-white dark:hover:bg-gray-600">
            <SvgIcon name="images" class="w-7 h-7" />
            <span class="sr-only">Upload image</span>
          </button>
        </el-upload>
        <button
          type="button"
          @click="showEmojiPicker = true"
          class="p-2 text-gray-500 rounded-lg cursor-pointer hover:text-indigo-600 hover:bg-gray-100 dark:text-gray-400 dark:hover:text-white dark:hover:bg-gray-600">
          <SvgIcon name="face-smile" class="w-7 h-7" />
          <span class="sr-only">Add emoji</span>
        </button>
        <input
          id="chat"
          v-model="content"
          class="block mx-4 p-2.5 w-full text-sm
          text-gray-900 bg-white rounded-lg border
           border-gray-300 focus:ring-blue-500 focus:border-indigo-600
           dark:bg-gray-800 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500
           dark:focus:border-blue-500"
          placeholder="Your message..." />
        <button
          type="submit"
          class="inline-flex justify-center p-2 text-blue-600 rounded-full cursor-pointer hover:bg-blue-100 dark:text-blue-500 dark:hover:bg-gray-600">
          <svg
            class="w-5 h-5 rotate-90"
            aria-hidden="true"
            xmlns="http://www.w3.org/2000/svg"
            fill="currentColor"
            viewBox="0 0 18 20">
            <path
              d="m17.914 18.594-8-18a1 1 0 0 0-1.828 0l-8 18a1 1 0 0 0 1.157 1.376L8 18.281V9a1 1 0 0 1 2 0v9.281l6.758 1.689a1 1 0 0 0 1.156-1.376Z" />
          </svg>
          <span class="sr-only">Send message</span>
        </button>
      </div>
      <div v-if="showEmojiPicker" class="relative">
          <div class="absolute bg-white bottom-[72px] left-5 rounded-lg w-[300px] h-[70vh]
          overflow-x-hidden overflow-y-scroll">
            <EmojiPicker @add-emoji="addEmoji"/>
          </div>
      </div>
    </form>
  </div>
  <el-dialog v-model="dialogVisible" center align-center width="70%">
    <template #default>
      <div class="flex flex-col items-center justify-center">
        <SvgIcon name="exclamation-triangle" class="mb-4 text-orange-500 w-8 h-8" color="#F96825"/>
        <span class="text-sm font-black">{{tipMessage}}</span>
      </div>
    </template>
    <template #footer>
      <div>
        <button
            class="flex w-full justify-center rounded-md bg-[#F96825] px-3 py-1.5
            text-sm font-semibold leading-6 text-white shadow-sm
            hover:bg-[#F96825] focus-visible:outline focus-visible:outline-2
            focus-visible:outline-offset-2 focus-visible:outline-indigo-600" @click="dialogVisible = false">Confirm</button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="ChatFooter">
import SvgIcon from '@/components/SvgIcon.vue'
import { ref } from 'vue'
import { genFileId } from 'element-plus'
import * as AuthUtils from '@/utils/auth'
import type { Message } from '@/types/global'
import EmojiPicker from './EmojiPicker.vue'
import { nanoid } from 'nanoid'
import {useUserInfoStore} from "@/stores/message";

const content = ref('')
import type { UploadInstance, UploadProps, UploadRawFile, UploadRequestOptions, UploadUserFile } from 'element-plus'
const upload = ref<UploadInstance>()
const emits = defineEmits(['sendMessage'])
const uploadLoading = ref(false)
const userInfoStore = useUserInfoStore()



const uploadUrl = ref(
  import.meta.env.VITE_BASE_URL as string + import.meta.env.VITE_API_URL + '/infra/file/message/upload'
)

const dialogVisible = ref(false)
const showEmojiPicker = ref(false)
const tipMessage = ref('')
const onSendMsg = () => {
  const value = content.value
  if (value) {
    const message: Message = {
      content: value,
      type: 1,
      isRead: false,
      isReceived: false,
      cid: nanoid(),
      status: 1,
    }
    emits('sendMessage', message)
  }
}

const onSendSuccess = () => {
  content.value = ''
}

const fileList = ref<UploadUserFile[]>([])

const uploadHeaders = ref({})

const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
}

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

const handleBeforeUpload = () => {
  uploadHeaders.value = {
    Authorization: 'Bearer ' + AuthUtils.getAccessToken(),
  }
  uploadLoading.value = true
}

const handleSuccess = (response: any) => {
  const data = response.data
  if (!data) {
    handleError()
    return
  }
  // 添加消息到文件
  fileList.value = []
  const message:Message = {
    content: data,
    type: 2,
    cid: nanoid(),
    isReceived: false,
    senderId: userInfoStore.getUserInfo().id,
    status: 1
  }
  emits('sendMessage', message)
  uploadLoading.value = false
}

const handleError = () => {
  fileList.value = []
  dialogVisible.value = true
  tipMessage.value = 'upload failed. Please try again.'
  uploadLoading.value = false
}

const addEmoji = (emojiItem:any) => {
  content.value += emojiItem.emoji
  showEmojiPicker.value = false
}


defineExpose({
  onSendSuccess,
  addEmoji
})
</script>

<style scoped>


</style>
