<template>
  <div>
    <div class="message-quote-uni-container">
      <MessageQuote
        :style="{ minWidth: 0 }"
        :displayType="displayType"
        @getQuoteMessageCloudCustomData="getQuoteMessageCloudCustomData"
      />
    </div>
    <div :class="['message-input',  'message-input-h5']">
      <div class="audio-main-content-line">
        <!-- for app&小程序，用 recorderManager -->
        <MessageInputAudio
          v-if="!isH5 && props.enableSendingAudio && isInHumanService"
          :class="{
            'message-input-wx-audio-open': displayType === 'audio',
          }"
          :isInAudioMode="displayType === 'audio'"
          @changeDisplayType="changeDisplayType"
        />
        <!-- for h5，用 js-audio-recorder -->
        <MessageInputAudioH5
          v-if="isH5 && props.enableSendingAudio && isInHumanService"
          :class="{
            'message-input-wx-audio-open': displayType === 'audio',
          }"
          :isInAudioMode="displayType === 'audio'"
          @changeDisplayType="changeDisplayType"
        />
        <!-- uniapp 打包到微信小程序，v-show 可能会导致状态异常，改用 v-if，其它平台用 v-show  -->
        <!-- #ifdef MP-WEIXIN -->
        <MessageInputEditor
          v-if="displayType === 'editor'"
          ref="editor"
          class="message-input-editor"
          :placeholder="props.placeholder"
          :isMuted="props.isMuted"
          :muteText="props.muteText"
          :enableInput="props.enableInput"
          :enableTyping="props.enableTyping"
          @onTyping="onTyping"
          @onFocus="onFocus"
          @isInputNotEmpty="isInputNotEmpty"
          @sendMessage="sendMessage"
          />
        <!-- #endif -->
        <!-- #ifndef MP-WEIXIN -->
        <MessageInputEditor
          v-show="displayType === 'editor'"
          ref="editor"
          class="message-input-editor"
          :placeholder="props.placeholder"
          :isMuted="props.isMuted"
          :muteText="props.muteText"
          :enableInput="props.enableInput"
          :enableTyping="props.enableTyping"
          @onTyping="onTyping"
          @onFocus="onFocus"
          @isInputNotEmpty="isInputNotEmpty"
          @sendMessage="sendMessage"
        />
        <!-- #endif -->
        <div :class="isTikTok ? 'icon-face-uniapp-in-tt' : 'icon-face-uniapp'" >
          <image v-if="isTikTok" :src="faceIcon" class="img-in-tt" @click="changeToolbarDisplayType('emojiPicker')"></image>
          <Icon
            v-else
            class="icon icon-face"
            :file="faceIcon"
            :size="'23px'"
            :hotAreaSize="'3px'"
            @onClick="changeToolbarDisplayType('emojiPicker')"
          />
        </div>
        <div v-if="!showSendButton" :class="isTikTok ? 'icon-tool-uniapp-in-tt' : 'icon-tool-uniapp'" >
          <image v-if="isTikTok" :src="moreIcon" class="img-in-tt" @click="changeToolbarDisplayType('tools')"></image>
          <Icon
            v-else
            class="icon icon-more"
            :file="moreIcon"
            :size="'23px'"
            :hotAreaSize="'3px'"
            @onClick="changeToolbarDisplayType('tools')"
        />
        </div>
        <div v-if="showSendButton" class="send-button" @click="sendMessage">
          <image v-if="isTikTok" :src="sendButtonIcon" class="send-button-in-tt"></image>
          <Icon v-else :file="sendButtonIcon" width="35px" height="35px"/>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import {
  TUIStore,
  StoreName,
  IMessageModel,
  IConversationModel,
} from '../../../@aidesk/uikit-engine';
import vue from '../../../adapter-vue';
import MessageInputEditor from './message-input-editor-uniapp.vue';
import MessageInputAudio from './message-input-audio-uniapp.vue';
import MessageInputAudioH5 from './message-input-audio-h5.vue';
import MessageQuote from './message-input-quote/index.vue';
import Icon from '../../common/Icon.vue';
import faceIcon from '../../../assets/emoji.png';
import moreIcon from '../../../assets/more_tools.png';
import { isApp, isH5, isTikTok, isWeChat } from '../../../utils/env';
import { sendMessages,sendTyping } from '../utils/sendMessage';
import { transformTextWithEmojiNamesToKeys } from '../emoji-config';
import { ToolbarDisplayType, InputDisplayType } from '../../../interface';
import sendButtonIcon from '../../../assets/send-button.svg';

const { ref, watch, onMounted, onUnmounted } = vue;

interface IProps {
  placeholder: string;
  isMuted?: boolean;
  muteText?: string;
  enableInput?: boolean;
  enableTyping?: boolean;
  enableSendingAudio?: number;
  replyOrReference?: Record<string, any>;
  inputToolbarDisplayType: ToolbarDisplayType;
}
interface IEmits {
  (e: 'changeToolbarDisplayType', displayType: ToolbarDisplayType): void;
  (e: 'messageSent'): void;
}

const emits = defineEmits<IEmits>();
const props = withDefaults(defineProps<IProps>(), {
  placeholder: '',
  replyOrReference: () => ({}),
  isMuted: true,
  muteText: '',
  enableInput: true,
  enableTyping: true,
  enableSendingAudio: 0,
  inputToolbarDisplayType: 'none',
});

const editor = ref();
const currentConversation = ref<IConversationModel>();
const displayType = ref<InputDisplayType>('editor');
const showSendButton = ref(false);
const isInHumanService = ref(false);
const isInAudioMode = ref(false);
let quoteMessageCloudCustomData: string = '';

onMounted(() => {
  TUIStore.watch(StoreName.CONV, {
    currentConversation: onCurrentConversationUpdated,
  });

  TUIStore.watch(StoreName.CHAT, {
    quoteMessage: onQuoteMessageUpdated,
  });

  TUIStore.watch(StoreName.CUSTOM, {
    isInHumanService: onInHumanServiceUpdate,
  });
});

onUnmounted(() => {
  TUIStore.unwatch(StoreName.CONV, {
    currentConversation: onCurrentConversationUpdated,
  });

  TUIStore.unwatch(StoreName.CHAT, {
    quoteMessage: onQuoteMessageUpdated,
  });

  TUIStore.unwatch(StoreName.CUSTOM, {
    isInHumanService: onInHumanServiceUpdate,
  });
});

watch(
  () => props.inputToolbarDisplayType,
  (newVal: ToolbarDisplayType) => {
    if (newVal !== 'none') {
      changeDisplayType('editor');
    }
  },
);

function changeDisplayType(display: InputDisplayType) {
  displayType.value = display;
  if (display === 'audio') {
    emits('changeToolbarDisplayType', 'none');
  }
}

function changeToolbarDisplayType(displayType: ToolbarDisplayType) {
  emits('changeToolbarDisplayType', displayType);
}

const onTyping = (inputContentEmpty: boolean, inputBlur: boolean) => {
  sendTyping(inputContentEmpty, inputBlur);
};

const onFocus = () => {
  if (isH5) {
    emits('changeToolbarDisplayType', 'none');
  }
};

const getQuoteMessageCloudCustomData = (cloudCustomData: string) => {
  quoteMessageCloudCustomData = cloudCustomData;
};

const insertEmoji = (emoji: any) => {
  editor?.value?.addEmoji && editor?.value?.addEmoji(emoji);
  showSendButton.value = true;
};

const reEdit = (content: any) => {
  editor?.value?.resetEditor();
  showSendButton.value = false;
  editor?.value?.setEditorContent(content);
};

function onCurrentConversationUpdated(conversation: IConversationModel) {
  currentConversation.value = conversation;
}

function onQuoteMessageUpdated(options?: {
  message: IMessageModel;
  type: string;
}) {
  // switch text input mode when there is a quote message
  if (options?.message && options?.type === 'quote') {
    changeDisplayType('editor');
  }
}

const onInHumanServiceUpdate = (data: {conversationID: string, value: boolean}) => {
  if (data && data.conversationID === currentConversation.value.conversationID) {
    isInHumanService.value = data.value;
    // 结束人工会话时，displayType 重置为 editor
    if (!isInHumanService.value) {
      changeDisplayType('editor');
    }
  }
};

const sendMessage = async () => {
  const _editorContentList = editor.value?.getEditorContent();
  if (!_editorContentList || !currentConversation.value) return;
  const editorContentList = _editorContentList.map((editor: any) => {
    if (editor.type === 'text') {
      editor.payload.text = transformTextWithEmojiNamesToKeys(
        editor.payload.text,
      );
    }
    return editor;
  });
  await sendMessages(editorContentList, currentConversation.value, quoteMessageCloudCustomData);
  editor.value?.resetEditor();
  showSendButton.value = false;
  // 注意这里不要 emit 'sendMessage'，避免写出死循环
  emits('messageSent');
};

const isInputNotEmpty = (show: boolean) => {
  showSendButton.value = show;
}

defineExpose({
  insertEmoji,
  reEdit,
});
</script>

<style scoped lang="scss">
@import "../style/common";

.icon-face-uniapp {
  background-color: #fff;
  padding: 5px;
  border-radius: 0 10px 10px 0;
}
.icon-face-uniapp-in-tt {
  background-color: #fff;
  padding: 8px;
  border-radius: 0 10px 10px 0;
}
.icon-tool-uniapp {
  background-color: #fff;
  padding: 3px;
  margin-left: 10px;
  border-radius: 10px;
}
.icon-tool-uniapp-in-tt {
  background-color: #fff;
  padding: 5px;
  margin-left: 10px;
  border-radius: 10px;
}

:not(not) {
  display: flex;
  flex-direction: column;
  min-width: 0;
  box-sizing: border-box;
}

.message-quote-uni-container{
}

.message-input {
  position: relative;
  display: flex;
  flex-direction: column;
  border: none;
  overflow: hidden;
  background: #ebf0f6;

  &-h5 {
    background-color: transparent;
    padding: 10px;
  }

  &-editor {
    flex: 1;
    display: flex;
  }

  .icon {
  }

  &-wx-audio-open {
    flex: 1;
  }
}

.audio-main-content-line {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.send-button {
  margin-left: 10px;
  animation: scaleOnShow 0.4s;
}

@keyframes scaleOnShow {
  0% {
    transform: scale(0.5);
  }
  100% {
    transform: scale(1);
  }
}

.img-in-tt {
  width: 23px;
  height: 23px;
  cursor: pointer;
}

.send-button-in-tt {
  width: 33px;
  height: 33px;
  cursor: pointer;
}
</style>
