<template>
  <form @submit.prevent="onSendMsg" class="border-t-2">
    <div class="h-8 flex flex-row items-center justify-end mt-1">
      <span>选择语言</span>
      <el-select v-model="language" class="mx-2" @change="onlanguagechange">
        <el-option v-for="item in languageOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </div>
    <label for="chat" class="sr-only">Your message</label>
    <div class="flex items-center px-3 py-2 rounded-lg bg-gray-50 dark:bg-gray-700">
      <el-upload
        v-model:file-list="fileList"
        ref="uploadRef"
        :headers="uploadHeaders"
        :action="uploadUrl"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :show-file-list="false"
        :limit="1"
        :auto-upload="true"
        :before-upload="handleBeforeUpload"
        :on-progress="handleProgress"
        accept="image/*"
        :on-success="handleSuccess"
        :on-error="handleError"
        :on-exceed="handleExceed"
        :on-change="handleChange"
        >
        <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>
      <textarea
        id="chat"
        rows="5"
        @keyup.enter="onSendMsg"
        v-model="content"
        @paste="handlePaste"
        :disabled="disable"
        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="Enter键发送消息，Shift + Enter 换行" />
      <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>
</template>

<script setup lang="ts" name="ChatFooter">
import SvgIcon from '@/components/SvgIcon.vue'
import EmojiPicker from './EmojiPicker.vue'
import { genFileId, type UploadFile, type UploadFiles, type UploadInstance, type UploadProgressEvent, type UploadProps, type UploadRawFile, type UploadUserFile } from 'element-plus'
import { ref } from 'vue'
import * as AuthUtils from '@/utils/auth'
import type { Message } from '@/types/global'
import { useUserInfoStore } from '@/stores/counter'
import {uploadFile} from '@/api/file'
import  {isBlank} from '@/utils/stringUtils'
import {nanoid} from 'nanoid'
import {ElMessage} from 'element-plus'
const language = ref(localStorage.getItem('language') || 'EN')



const languageOptions = ref([
  { label: '英语', value: 'EN' },
  { label: '丹麦语', value: 'DA' },
  { label: '葡萄牙语', value: 'PT' },
  { label: '意大利语', value: 'IT' },
  { label: '德语', value: 'DE' },
  { label: '法语', value: 'FR' },
  { label: '西班牙语', value: 'ES' },
  { label: '芬兰语', value: 'FI' },
])
const uploadUrl = ref(
  (import.meta.env.VITE_BASE_URL as string) + import.meta.env.VITE_API_URL + '/infra/file/upload/13'
)
const disable = ref(false)
const showEmojiPicker = ref(false)
const uploadRef = ref<UploadInstance>()
const content = ref('')
const tipMessage = ref('')
const emits = defineEmits(['sendMessage'])
const userInfoStore = useUserInfoStore()
const onSendMsg = () => {
  const value = content.value
  if (isBlank(value)) {
    content.value = ''
    return
  }

  const receiver = userInfoStore.getUserInfo()
  if (Object.keys(receiver).length <= 0) {
    ElMessage.error('请选择指定的用户再发送消息')
    return
  }
  // 接收者
  const message: Message = {
    content: value,
    type: 1,
    customerId: receiver.id,
    receiverId: receiver.id,
    username: receiver.username,
    senderId:  AuthUtils.getUserId(),
    translationLanguage: language.value,
    cid: nanoid(),
    status: 0
  }
  emits('sendMessage', message)
}

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

const setContent = (message: string) => {
  content.value = message
}

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) => {
  console.log('handleExceed')
  uploadRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadRef.value!.handleStart(file)
}

const handleChange = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  console.log('handleChange', uploadFile, uploadFiles)
}


const handleBeforeUpload = (rawFile: UploadRawFile) => {
  console.log('handleBeforeUpload',rawFile)
  uploadHeaders.value = {
    Authorization: 'Bearer ' + AuthUtils.getAccessToken(),
  }
  if (!rawFile.uid) {
    rawFile.uid = genFileId()
  }
  return true
}

const handleProgress = (evt: UploadProgressEvent, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  console.log('Upload progress:', evt, uploadFile, uploadFiles);
};

const handleSuccess = (response: any) => {
  // 添加消息到文件
  console.log('handleSuccess')
  fileList.value = []
  const message = {
    content: response.data,
    type: 2,
    customerId: userInfoStore.getUserInfo().id,
    receiverId: userInfoStore.getUserInfo().id,
    username: userInfoStore.getUserInfo().username,
    senderId: AuthUtils.getUserId(),
    isRead: false,
  }
  emits('sendMessage', message)
}

const handleError = () => {
  console.log('handleError')
  fileList.value = []
  tipMessage.value = '上传失败'
}

const addEmoji = (emojiItem: any) => {
  console.log('addd', emojiItem)
  content.value += emojiItem.emoji
  showEmojiPicker.value = false
}

// 复制图片
const handlePaste = async (e: ClipboardEvent) => {
  const items = e.clipboardData?.items as DataTransferItemList
  if (!items) return
  for (const item of Array.from(items)) {
    if (item.type.startsWith('image/')) {
      console.log('居然是图片，直接上传')
      const file = item.getAsFile()
      if (!file) continue;
      // axios 上传图片
      const formData = new FormData()
      formData.append('file', file)
      const res = await uploadFile(formData)
      handleSuccess(res)
    }
  }
}

const onlanguagechange = (value: string) => {
  localStorage.setItem('language', value)
}

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