<script setup>
import { ref, provide, nextTick, onMounted, onUnmounted } from 'vue';

import { message } from 'ant-design-vue';

import { useFileUpload } from '../composables/useFileUpload.ts';
import { useRecording } from '../composables/useRecording.ts';
import { useChatStore } from '../stores/chat.ts';
import { useThemeStore } from '../stores/theme.ts';
import { useUserStore } from '../stores/user.ts';
import { sendMessage } from '../utils/request.ts';
import CustomTextarea from './CustomTextarea.vue';
import EmojiPicker from './EmojiPicker.vue';
import FileUploadPreview from './FileUploadPreview.vue';

// 定义 props
const props = defineProps({
  currentFriend: {
    type: Object,
    default: () => ({})
  }
});

const userStore = useUserStore();
const chatStore = useChatStore();
const themeStore = useThemeStore();

const messageText = ref('');
const messageInputRef = ref(null);
const showEmojiPicker = ref(false);

// 使用文件上传组合式函数
const {
  uploadPreview,
  imageInput,
  videoInput,
  triggerFileInput,
  handleFileUpload,
  cancelUpload,
} = useFileUpload();

// 使用录音组合式函数
const { isRecording, startRecording, stopRecording } = useRecording();

// 发送上传的文件
const sendUploadedFile = () => {
  if (!uploadPreview.value) return;

  const messageObj = {
    type: uploadPreview.value.type,
    content: uploadPreview.value.url,
    time: new Date().toLocaleTimeString().slice(0, 5),
    senderId: `${userStore.currentUser.id}`,
    receiverId: chatStore.currentFriend.id,
    read: true,
    duration: 0,
  };

  chatStore.addMessage(messageObj, userStore.currentUser.id);

  // 发送到服务器
  sendMessage({
    senderId: userStore.currentUser.id,
    receiverId: chatStore.currentFriend.id,
    type: uploadPreview.value.type,
    content: uploadPreview.value.url,
  }).catch((error) => {
    console.error('发送文件失败:', error);
    message.error('文件发送失败');
  });

  uploadPreview.value = null;
};

// 提供给子组件
provide('uploadPreview', uploadPreview);
provide('cancelUpload', cancelUpload);
provide('sendFile', sendUploadedFile);

// 发送文本消息
const sendTextMessage = async () => {
  const content = messageText.value.trim();
  if (!content && !uploadPreview.value) return;

  let messageContent = content;
  let messageType = 'text';

  // 如果有文件预览，发送文件
  if (uploadPreview.value) {
    messageContent = uploadPreview.value.url;
    messageType = uploadPreview.value.type;
    uploadPreview.value = null;
  }

  // 创建消息对象
  const messageObj = {
    type: messageType,
    content: messageContent,
    time: new Date().toLocaleTimeString().slice(0, 5),
    senderId: `${userStore.currentUser.id}`,
    receiverId: chatStore.currentFriend.id,
    isSent: true,
    read: true,
    duration: 0,
  };

  // return console.log('发送消息:' + userStore.currentUser.id, messageObj);
  // 添加到本地消息列表
  chatStore.addMessage(messageObj, userStore.currentUser.id);

  // 发送到服务器
  try {
    await sendMessage({
      senderId: userStore.currentUser.id,
      receiverId: chatStore.currentFriend.id,
      roomId: chatStore.currentFriend.room_id,
      type: messageType,
      content: messageContent,
    });
  } catch (error) {
    console.error('发送消息失败:', error);
    message.error('消息发送失败');
  }

  // 清空输入框
  messageText.value = '';

  // 重置焦点
  nextTick(() => {
    if (messageInputRef.value) {
      messageInputRef.value.focus();
    }
  });
};

// 处理键盘事件
const handleKeydown = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault();
    sendTextMessage();
  }
};

// 处理粘贴文件
const handlePasteFile = (file) => {
  console.log('检测到粘贴文件:', file);

  // 根据文件类型自动选择处理方式
  if (file.type.startsWith('image/')) {
    handleFileFromPaste(file, 'image');
  } else if (file.type.startsWith('video/')) {
    handleFileFromPaste(file, 'video');
  } else {
    message.warning('不支持的文件类型');
  }
};

// 处理粘贴的文件
const handleFileFromPaste = (file, type) => {
  // 文件大小检查
  const maxSize = type === 'image' ? 10 * 1024 * 1024 : 50 * 1024 * 1024;
  if (file.size > maxSize) {
    const maxSizeMB = maxSize / 1024 / 1024;
    message.error(
      `文件大小超过限制！${type === 'image' ? '图片' : '视频'}最大${maxSizeMB}MB`,
    );
    return;
  }

  const reader = new FileReader();
  reader.addEventListener('load', (e) => {
    uploadPreview.value = {
      type,
      url: e.target.result,
      name: file.nick_name,
      size: file.size,
      file,
    };
  });

  reader.onerror = (error) => {
    console.error('文件读取失败:', error);
    message.error('文件读取失败，请重试');
  };

  reader.readAsDataURL(file);
};

// 切换表情选择器
const toggleEmojiPicker = () => {
  showEmojiPicker.value = !showEmojiPicker.value;
};

// 插入表情
const insertEmoji = (emoji) => {
  messageText.value += emoji;
  showEmojiPicker.value = false;

  nextTick(() => {
    if (messageInputRef.value) {
      messageInputRef.value.focus();
    }
  });
};

// 监听录音完成事件
const handleAudioRecorded = (event) => {
  const { url, duration } = event.detail;

  const messageObj = {
    type: 'audio',
    content: url,
    time: new Date().toLocaleTimeString().slice(0, 5),
    senderId: `${userStore.currentUser.id}`,
    receiverId: chatStore.currentFriend.id,
    isSent: true,
    read: true,
    duration,
  };

  chatStore.addMessage(messageObj, userStore.currentUser.id);

  // 发送到服务器
  sendMessage({
    senderId: userStore.currentUser.id,
    receiverId: chatStore.currentFriend.id,
    roomId: chatStore.currentFriend.room_id,
    isSent: true,
    type: 'audio',
    content: url,
    duration,
  }).catch((error) => {
    console.error('发送音频失败:', error);
    message.error('音频发送失败');
  });
};

onMounted(() => {
  window.addEventListener('audioRecorded', handleAudioRecorded);

  // 点击外部关闭表情选择器
  document.addEventListener('click', (event) => {
    if (
      !event.target.closest('.emoji-picker') &&
      !event.target.closest('.function-btn')
    ) {
      showEmojiPicker.value = false;
    }
  });
});

onUnmounted(() => {
  window.removeEventListener('audioRecorded', handleAudioRecorded);
});

// 定义 emits
const emit = defineEmits([
  'sendMessage',
  'openPrescription' // 添加开方事件
]);

// 开方功能触发函数
const handleOpenPrescription = () => {
  // 获取当前会话的register_id，这里假设可以通过某种方式获取
  // 例如从聊天存储或props中获取
  const registerId = props.currentFriend?.register_id || 0;
  
  if (registerId) {
    emit('openPrescription', registerId);
  } else {
    console.warn('无法获取当前会话的register_id');
    // 可以添加一个提示或使用默认值
    emit('openPrescription', 0);
  }
};

</script>

<template>
  <div class="message-input-container" :class="{ dark: themeStore.isDarkMode }">
    <!-- 工具栏 -->
    <div class="toolbar">
      <button 
        class="toolbar-button prescription-button" 
        @click="handleOpenPrescription"
        title="开方"
      >
        <i class="iconfont icon-prescription"></i>
        开方
      </button>
      <button 
        class="toolbar-button" 
        @click="triggerFileInput('image')"
        title="发送图片"
      >
        <i class="fas fa-image"></i>
        图片
      </button>
      <button 
        class="toolbar-button" 
        @click="triggerFileInput('video')"
        title="发送视频"
      >
        <i class="fas fa-video"></i>
        视频
      </button>
      <button 
        :class="{ active: showEmojiPicker }"
        class="toolbar-button"
        title="选择表情"
        @click="toggleEmojiPicker"
      >
        <i class="fas fa-smile"></i>
        表情
      </button>
      <button 
        :class="{ recording: isRecording }"
        class="toolbar-button record-btn"
        title="按住录音"
        @mousedown="startRecording"
        @mouseleave="stopRecording"
        @mouseup="stopRecording"
        @touchend="stopRecording"
        @touchstart="startRecording"
      >
        <i class="fas fa-microphone"></i>
        录音
      </button>
    </div>
    
    <!-- 文件上传预览 -->
    <FileUploadPreview v-if="uploadPreview" />
    <!-- 表情选择器 -->
    <EmojiPicker v-if="showEmojiPicker" class="mb-10" @select="insertEmoji" />

    <div class="input-container">
      <!-- 输入框区域 -->
      <div class="input-section">
        <CustomTextarea
          ref="messageInputRef"
          v-model="messageText"
          :auto-resize="true"
          :detect-paste="true"
          :max-rows="4"
          class="message-textarea"
          placeholder="输入消息... (支持拖拽文件)"
          @keydown="handleKeydown"
          @paste-file="handlePasteFile"
        />

        <button
          :disabled="!messageText.trim() && !uploadPreview"
          class="send-btn"
          title="发送消息"
          @click="sendTextMessage"
        >
          <i class="fas fa-paper-plane"></i>
          <div class="send-ripple"></div>
        </button>
      </div>
    </div>

    <!-- 隐藏的文件输入框 -->
    <input
      ref="imageInput"
      accept="image/*"
      class="hidden"
      type="file"
      @change="handleFileUpload"
    />
    <input
      ref="videoInput"
      accept="video/*"
      class="hidden"
      type="file"
      @change="handleFileUpload"
    />
  </div>
</template>

<style scoped>
.message-input-container {
  padding: 20px;
  border-top: 1px solid #e2e8f0;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  position: relative;
}

.message-input-container.dark {
  border-top-color: #374151;
  background: linear-gradient(135deg, #2d2d2d 0%, #1f2937 100%);
}

.input-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.toolbar {
  display: flex;
  align-items: center;
  padding: 8px;
  border-top: 1px solid #eee;
}

.toolbar-button {
  background: none;
  border: none;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  margin-right: 5px;
  display: flex;
  align-items: center;
  color: #666;
}

.toolbar-button:hover {
  background-color: #f0f0f0;
}

.prescription-button {
  color: #455cda;
  font-weight: 500;
}

.prescription-button:hover {
  background-color: #e6e9ff;
}

.function-buttons {
  display: flex;
  gap: 12px;
  align-items: center;
}

.function-btn {
  position: relative;
  width: 44px;
  height: 44px;
  border-radius: 50%;
  border: none;
  background: linear-gradient(135deg, #f1f5f9, #e2e8f0);
  color: #64748b;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.function-btn:hover {
  background: linear-gradient(135deg, #4361ee, #3f37c9);
  color: white;
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 8px 20px rgba(67, 97, 238, 0.3);
}

.function-btn.active {
  background: linear-gradient(135deg, #4361ee, #3f37c9);
  color: white;
  transform: scale(1.1);
}

.function-btn.recording {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  color: white;
  animation: pulse-recording 1s infinite;
}

@keyframes pulse-recording {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

.recording-wave {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60px;
  height: 60px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  animation: wave-expand 1.5s infinite;
}

@keyframes wave-expand {
  0% {
    transform: translate(-50%, -50%) scale(0.8);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) scale(1.5);
    opacity: 0;
  }
}

.btn-ripple {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  transform: translate(-50%, -50%);
  transition: all 0.6s ease;
}

.function-btn:active .btn-ripple {
  width: 100px;
  height: 100px;
}

.message-input-container.dark .function-btn {
  background: linear-gradient(135deg, #374151, #4b5563);
  color: #9ca3af;
}

.message-input-container.dark .function-btn:hover {
  background: linear-gradient(135deg, #4361ee, #3f37c9);
  color: white;
}

.input-section {
  display: flex;
  align-items: end;
  gap: 12px;
  position: relative;
}

.message-textarea {
  flex: 1;
}

.send-btn {
  position: relative;
  width: 52px;
  height: 52px;
  border-radius: 50%;
  border: none;
  background: linear-gradient(135deg, #4361ee, #3f37c9);
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(67, 97, 238, 0.3);
}

.send-btn:hover:not(:disabled) {
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 8px 20px rgba(67, 97, 238, 0.4);
}

.send-btn:disabled {
  background: #94a3b8;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.send-ripple {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.4);
  transform: translate(-50%, -50%);
  transition: all 0.6s ease;
}

.send-btn:active:not(:disabled) .send-ripple {
  width: 80px;
  height: 80px;
}

.hidden {
  display: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .function-buttons {
    gap: 8px;
  }

  .function-btn {
    width: 40px;
    height: 40px;
    font-size: 16px;
  }

  .send-btn {
    width: 48px;
    height: 48px;
    font-size: 16px;
  }
}
</style>