<template>
  <div class="chat-input-comp" ref="chatInputCompRef">
    <div class="input-box">
      <div v-if="false" class="mr-12">语音todo</div>
      <div
          @click="openTool('operate')"
          class="iconfont icon-close-one rotate-45 mr-12 text-black-6"
          style="font-size: 32px"
      ></div>
      <div
          @click="openTool('emoji')"
          class="iconfont icon-slightly-smiling-face text-black-6 mr-12"
          style="font-size: 32px"
      ></div>
      <div class="input-box__textarea mr-12" id="input-kary">
        <van-field
            v-model="inputValue"
            autosize
            ref="inputRef"
            rows="1"
            type="textarea"
            placeholder="请输入"
            @focus="handleFocus"
            @blur="handleBlur"
        />
      </div>
      <van-button size="small" type="warning" @click="sendTextMessage"> 发 送</van-button>
    </div>
    <div v-show="showTool" class="px-20 py-8">
      <div class="operate-box" v-show="currTool === 'operate'">
        <div v-for="(operate, i) in showOperateList"
             :key="i"
             @click="handleOperate(operate)"
        >
          <div
              class="w-54 h-54 active:bg-[#FF9300]/[0.1] bg-[#F3F3F3] shrink-0 rounded-full mb-5 flex justify-center items-center">
            <span
                :class="`iconfont ${operate.icon} text-black-6 active:text-[#FF9300] `"
                style="font-size: 32px"
            ></span>
          </div>
          <p class="text-sm w-full text-center">{{ operate.title }}</p>
        </div>
      </div>
      <div class="emoji-box h-144 overflow-y-auto" v-show="currTool === 'emoji'">
        <div
            v-for="(item, index) in emojiJson"
            :key="index"
            @click="selectEmoji(item, index)"
            class="active:bg-[#ddd] text-4xl w-26 aspect-[1/1] grid place-items-center"
        >
          <div @click="selectEmoji(index)" v-html="item.emoji"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import emojiJson from "~/components/Profile/News/emoji";

const props = defineProps({
  operates: {
    type: Array,
    default: () => ['image']// ['image', 'share-group']
  },
})
const emit = defineEmits(['send', 'focus', 'blur'])

const inputValue = ref('')
const inputRef = ref(null);

const chatInputCompRef = ref(null);
const operateList = [
  {
    title: '相册',
    icon: 'icon-pic',
    isShow: props.operates.includes('image'),
    fn: 'uploadImage'
  },
  {
    title: '分享群聊',
    icon: 'icon-peoples-two',
    isShow: props.operates.includes('share-group'),
    fn: 'shareGroupChat'
  }
];

const showOperateList = computed(() => {
  return operateList.filter(o => o.isShow)
})

const {open, onChange: uploadImage} = useFileDialog({
  accept: 'image/*'
})

const handleOperate = (operate) => {
  try {
    switch (operate.fn) {
      case 'uploadImage':
        open()
        break;
      case 'shareGroupChat':
        console.log('分享群聊')
        showToast('研发中，敬请期待~')
        break;
    }
  } catch (e) {

  }
}

uploadImage(async (files) => {
  if (!files.length) return

  console.log(files[0], 'files[0]files[0]')
  const {type, size} = files[0];
  if (!['image/jpeg', 'image/png', 'image/gif'].includes(type)) {
    showToast('请上传图片')
  }
  const maxSize = 20 * 1024 * 1024 // 20 MB
  if (size > maxSize) {
    showToast('图片大小不能超过20MB')
    return
  }
  /*  const formData = new FormData()
    formData.append('uploadFile', files[0])
    formData.append('asImage', true)
    formData.append('fieldName', 'messageContent')
    const {data} = await request('/website/tourMessage/upload', {
      method: 'post',
      body: formData
    })*/
  // closeToast()
  emit('send', {
    type: 'image',
    messageContent: files[0]
  })
})

const sendTextMessage = () => {
  try {
    if (!inputValue.value.trim()) {
      showToast('发送内容不能为空！')
      return
    }
    emit('send', {
      type: 'text',
      messageContent: inputValue.value
    })
    inputValue.value = ''
  } catch (e) {

  }
}
const selectEmoji = async (item, index) => {
  try {
    const position = getInputPosition()
    const str = inputValue.value;
    inputValue.value = `${str.slice(0, position)}${emojiJson[index].emoji}${str.slice(position)}`
  } catch (e) {

  }
}

const showTool = ref(false)
const currTool = ref('')
const openTool = (toolName) => {
  showTool.value = true
  currTool.value = toolName
}
const handleFocus = () => {
  showTool.value = false
  emit('focus')
}
const handleBlur = () => {
  emit('blur')
}
const getInputPosition = () => {
  try {
    if (!inputValue.value) return 0
    const el = inputRef.value?.$el.querySelector('input, textarea');
    if (!el) return inputValue.value.length - 1;
    return el.selectionStart
  } catch (e) {
    console.log(e, '??')
  }
}

// 判断是否点击的非输入框
const handleClickOutside = (event) => {
  const chatInputCompEl = chatInputCompRef.value;
  const isChatInputCompEl = chatInputCompEl.contains(event.target);

  if (!isChatInputCompEl) {
    showTool.value = false
    inputRef.value.$el.blur()
  }
};
onMounted(() => {
  useEventListener('click', handleClickOutside, {target: document})
  useEventListener('mousedown', handleClickOutside, {target: document})
  useEventListener('touchstart', handleClickOutside, {target: document})

  if (process.env.NODE_ENV === 'development') {
    useEventListener('keyup', (event) => {
      if (event.key === 'Enter') {
        sendTextMessage()
      }
    })
  }
})
</script>

<style scoped lang="scss">
.chat-input-comp {
  width: 100%;
  border-top: 1px solid #E7E7E7;

  .input-box {
    width: 100%;
    //height: 64px;
    padding: 12px;
    box-sizing: border-box;
    background: #fff;
    display: flex;
    align-items: center;

    .input-box__textarea {
      flex: 1;
      background: #F3F3F3;
      border-radius: 20px;
      border: 1px solid #DCDCDC;
      padding: 5px 10px;
    }
  }

  .operate-box {
    display: grid;
    grid-template-columns: 54px 54px 54px 54px;
    grid-template-rows: 54px 54px;
    gap: 20px;
  }

  .emoji-box {
    display: grid;
    gap: 5px;
    grid-template-columns: repeat(6, 1fr);
    grid-auto-rows: auto;
    box-sizing: border-box;
    justify-content: center;
    align-content: center;
    justify-items: center;
    align-items: center;
  }
}

:deep(.van-cell) {
  padding: 0;
  background: transparent;
  min-height: 24px;
  max-height: 100px;
  overflow-y: auto;
}
</style>