<template>
  <div class="floating-container">
    <!-- 功能选择 Popconfirm -->
    <Popconfirm
      v-model:open="isPanelVisible"
      :overlayClassName="'function-popconfirm'"
      :trigger="'hover'"
      :destroyTooltipOnHide="true"
      :icon="null"
      :showCancel="false"
      :title="''"
    >
      <template #okButton>
        <div class="function-buttons">
          <!-- AI 助手按钮 -->
          <div class="function-btn ai-chat-btn" @click="openAiChat">
            <div class="btn-icon">
              <SmileOutlined />
            </div>
            <span>AI 助手</span>
          </div>
          
          <!-- 反馈中心按钮 -->
          <div class="function-btn feedback-btn" @click="openFeedback">
            <div class="btn-icon">
              <MessageOutlined />
            </div>
            <span>反馈中心</span>
          </div>
        </div>
      </template>
      
      <!-- 触发按钮 -->
      <div 
        ref="buttonRef"
        class="floating-button" 
        @click="handleClick" 
        :style="[bgColorStyle, positionStyle]"
        :class="{ 'dragging': isDragging }"
      >
        <div class="button-icon">
          <!-- <QuestionCircleOutlined /> -->
        </div>
        <span class="button-text">有疑问？</span>
      </div>
    </Popconfirm>

    <!-- AI 聊天面板 -->
    <div v-if="isAiChatVisible" class="ai-chat-panel" :class="{ 'panel-visible': isAiChatVisible }" :style="aiChatPanelPositionStyle">
      <div class="panel-header" :style="bgColorStyle">
        <h3>AI 智能助手</h3>
        <button class="close-btn" @click="closeAiChat">
          <CloseOutlined />
        </button>
      </div>
      <div class="panel-content">
        <AiChat 
          :bgColorStyle="bgColorStyle" 
          :themeColorStyle="themeColorStyle" 
          :pollingInterval="parsedPollingInterval"
          :userId="userId"
          :userName="userName"
          v-bind="aiChatConfig"
        />
      </div>
    </div>

    <!-- 反馈中心面板 -->
    <div v-if="isFeedbackVisible" class="feedback-panel" :class="{ 'panel-visible': isFeedbackVisible }" :style="feedbackPanelPositionStyle">
      <div class="panel-header" :style="bgColorStyle">
        <h3>反馈中心</h3>
        <button class="close-btn" @click="closeFeedback">
          <CloseOutlined />
        </button>
      </div>
      <div class="panel-content">
        <div class="feedback-content">
        <FeedbackForm  
          v-bind="feedbackConfig"
          :bgColorStyle="bgColorStyle" 
          :theme="themeColorStyle"
          :systemId="feedbackConfig.systemId"
          :link="feedbackConfig.link"
          :userId="userId"
          :userName="userName"
        />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import Popconfirm from 'ant-design-vue/es/popconfirm'
import { SmileOutlined, MessageOutlined, CloseOutlined } from '@ant-design/icons-vue'
import AiChat from '../ai-chat/content.vue'
import FeedbackForm from '../feedback/components/feedback-form.vue'
import { useDrag } from '../ai-chat/hooks/useDragFixed'
import { usePanelPosition } from '../ai-chat/hooks/usePanelPosition'

const props = defineProps({
  themeColor: {
    type: [String, Array],
    default: () => ['#667eea', '#764ba2']
  },
  position: {
    type: [String, Object],
    default: () => ({
      top: 'auto',
      right: '20px',
      bottom: '20px',
      left: 'auto'
    })
  },
  draggable: {
    type: [Boolean, String],
    default: true
  },
  aiChatConfig: {
    type: Object,
    default: () => ({
      pollingInterval: 500,
      botCode: ''
    })
  },
  userName: {
    type: String,
    default: ''
  },
  userId: {
    type: String,
    default: ''
  },
  feedbackConfig: {
    type: Object,
    default: () => ({
        systemId: '',
    })
  }
})

const emit = defineEmits(['position-change', 'ai-chat-open', 'feedback-open'])

// 解析Web Components属性
const parsedThemeColor = computed(() => {
  if (typeof props.themeColor === 'string') {
    try {
      return JSON.parse(props.themeColor)
    } catch {
      return [props.themeColor]
    }
  }
  return props.themeColor
})

const parsedPosition = computed(() => {
  if (typeof props.position === 'string') {
    try {
      return JSON.parse(props.position)
    } catch {
      return {
        top: 'auto',
        right: '20px',
        bottom: '20px',
        left: 'auto'
      }
    }
  }
  return props.position
})

const parsedDraggable = computed(() => {
  if (typeof props.draggable === 'string') {
    return props.draggable === 'true'
  }
  return props.draggable
})

const parsedPollingInterval = computed(() => {
  return props.aiChatConfig?.pollingInterval || 500
})

// 模板引用
const buttonRef = ref<HTMLElement>()

const themeColorStyle = computed(() => {
  if (Array.isArray(parsedThemeColor.value)) {
    return parsedThemeColor.value?.length === 1 ? [...parsedThemeColor.value, ...parsedThemeColor.value] : parsedThemeColor.value
  }
  return [parsedThemeColor.value, parsedThemeColor.value]
})

const bgColorStyle: any = computed(() => {
  return {
    background: `linear-gradient(135deg, ${themeColorStyle.value[0]} 0%, ${themeColorStyle.value[1]} 100%)`,
    'box-shadow': `0 4px 12px ${themeColorStyle.value[0]}66`,
    color: 'white'
  }
})

const positionStyle: any = computed(() => {
  return {
    position: 'fixed',
    top: parsedPosition.value.top || 'auto',
    right: parsedPosition.value.right || 'auto',
    bottom: parsedPosition.value.bottom || 'auto',
    left: parsedPosition.value.left || 'auto'
  }
})

// 响应式数据
const isPanelVisible = ref(false)
const isAiChatVisible = ref(false)
const isFeedbackVisible = ref(false)

// 使用拖拽 hook
const { isDragging, position: dragPosition } = useDrag(buttonRef, {
  draggable: parsedDraggable.value,
  inertia: true,
  autoScroll: true,
  restrictToViewport: true
})

// 监听拖拽状态，拖拽时关闭所有 panel
watch(isDragging, (dragging) => {
  if (dragging) {
    isPanelVisible.value = false
    isAiChatVisible.value = false
    isFeedbackVisible.value = false
  }
})

// Popconfirm 会自动处理位置，不需要手动计算

// AI聊天面板位置
const { panelPositionStyle: aiChatPanelPositionStyle } = usePanelPosition(
  buttonRef,
  dragPosition,
  positionStyle,
  {
    panelWidth: 400,
    panelHeight: 600,
    margin: 10,
    safeMargin: 10
  }
)

// 反馈面板位置
const { panelPositionStyle: feedbackPanelPositionStyle } = usePanelPosition(
  buttonRef,
  dragPosition,
  positionStyle,
  {
    panelWidth: 400,
    panelHeight: 500,
    margin: 10,
    safeMargin: 10
  }
)

// Popconfirm 会自动处理显示/隐藏，不需要手动切换

// 打开AI聊天
const openAiChat = () => {
  isPanelVisible.value = false
  isAiChatVisible.value = true
  emit('ai-chat-open')
}

// 关闭AI聊天
const closeAiChat = () => {
  isAiChatVisible.value = false
}

// 打开反馈中心
const openFeedback = () => {
  isPanelVisible.value = false
  isFeedbackVisible.value = true
  emit('feedback-open')
}

// 关闭反馈中心
const closeFeedback = () => {
  isFeedbackVisible.value = false
}

// 提交反馈函数已移除，由FeedbackForm组件内部处理

// 关闭所有面板（Popconfirm 会自动处理，此函数已不需要）

// 处理点击事件（避免拖拽时触发点击）
const handleClick = () => {
  if (!isDragging.value) {
    // 如果有panel已经打开，则关闭当前panel
    if (isAiChatVisible.value) {
      closeAiChat()
    } else if (isFeedbackVisible.value) {
      closeFeedback()
    }
    // 由于现在使用 hover 触发，点击主要用于关闭已打开的 panel
  }
}
</script>

<style scoped>
.floating-container {
  position: relative;
}

/* 浮动按钮样式 */
.floating-button {
  position: fixed;
  z-index: 1001;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  color: white;
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
  user-select: none;
  touch-action: none;
}

.floating-button:hover {
  transform: translateY(-2px);
}

.floating-button.dragging {
  opacity: 0.8;
  transform: scale(1.05);
  cursor: grabbing;
  z-index: 1003;
  transition: none;
}

.button-icon {
  display: flex;
  align-items: center;
  justify-content: center;
}

.button-text {
  font-size: 14px;
  font-weight: 500;
}

.ai-chat-panel,
.feedback-panel {
  position: fixed;
  z-index: 1002;
  width: 500px;
  height: 600px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transform: translateY(20px) scale(0.95);
  opacity: 0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.feedback-panel {
  height: 678px;
}

.ai-chat-panel.panel-visible,
.feedback-panel.panel-visible {
  transform: translateY(0) scale(1);
  opacity: 1;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  color: white;
  border-radius: 12px 12px 0 0;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.panel-content {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 功能按钮样式 */
.function-buttons {
  width: 140px;
  height: 100%;
}

.ai-chat-btn {
  margin-bottom: 10px;
}

.function-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  background: linear-gradient(135deg, #ffffff 0%, #fafafa 100%);
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-size: 12px;
  font-weight: 600;
  color: #333;
  flex: 1;
  min-height: 30px;
  position: relative;
  overflow: hidden;
}

.function-btn:hover::before {
  opacity: 1;
}

.function-btn:hover {
  border-color: #667eea;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9ff 100%);
  transform: translateY(-4px) scale(1.02);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.2);
}

.ai-chat-btn:hover {
  border-color: #667eea;
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.25);
}

.feedback-btn:hover {
  border-color: #52c41a;
  box-shadow: 0 8px 25px rgba(82, 196, 26, 0.25);
}

.feedback-btn:hover::before {
  background: linear-gradient(135deg, rgba(82, 196, 26, 0.05) 0%, rgba(24, 144, 255, 0.05) 100%);
}

.btn-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  color: #666;
  border-radius: 50%;
  transition: all 0.3s ease;
  font-size: 16px;
  margin-right: 4px;
}

.ai-chat-btn .btn-icon {
  color: #667eea;
  /* background: rgba(102, 126, 234, 0.1); */
}

.feedback-btn .btn-icon {
  color: #52c41a;
  /* background: rgba(82, 196, 26, 0.1); */
}

.function-btn:hover .btn-icon {
  transform: scale(1.1);
  background: rgba(102, 126, 234, 0.15);
}

.ai-chat-btn:hover .btn-icon {
  background: rgba(102, 126, 234, 0.2);
}

.feedback-btn:hover .btn-icon {
  background: rgba(82, 196, 26, 0.2);
}


/* 反馈中心内容 */

.panel-content :deep(.ai-chat-container) {
  position: relative;
  bottom: auto;
  right: auto;
  width: 100%;
  height: 100%;
  margin: 0;
  border-radius: 0;
}
</style>
