<script setup lang="ts">
import {ref, watch, computed, onMounted, nextTick, defineEmits} from 'vue'
import {getImageUrl} from '@/utils/common'
import {isKioskDevice} from '@/utils/useDeviceDetection'

import {Top} from '@element-plus/icons-vue'
import {useGlobalStore} from '@/stores/global'
import {ElMessage} from "element-plus";
import type {ElInput} from 'element-plus';
import {MessageApi} from '@/api/message'


import SsChatSendMessage from "@/components/ss_chat/components/SsChatSendMessage.vue";
import SsChatReply from "@/components/ss_chat/components/SsChatReply.vue";
import SsRecording from "@/components/SsRecording.vue";

const global = useGlobalStore()

const scrollbarRef = ref<any>(null)
const bottomRef = ref<HTMLElement | null>(null)
const textareaRef = ref<InstanceType<typeof ElInput>>();
const autoScroll = ref(true)
const message = ref('')
const conversationId = ref<string>(global.conversationId)
const replyList = ref<any[]>([])
const replyContent = ref()
let scrollDirection = 'down'
let scrollFlag = false;
let beforeScrollTop = 0;

const sendMessageFlag = computed(() => {
  let msg = message.value.trim();
  return msg == '' || global.inReply
});

const sendMessage = () => {
  const msg = message.value.trim();
  if (msg == '') {
    ElMessage.closeAll()
    ElMessage.info('请输入你想咨询的问题')
  } else {
    if (sendMessageFlag.value) {
      return
    }
    MessageApi.stop();
    // 设置状态参数
    global.setAudioChatId('');
    global.setSpread(true)
    global.setInReply(true)
    // 发送的消息
    replyList.value.push({
      type: 'send_message',
      content: msg,
    })
    message.value = ''
    scrollToBottom(true);
    // 增加回复消息容器
    replyContent.value = {
      chatId: '',
      source: [],
      avatar: '/images/robot-avatar.png',
      type: 'text',
      title: msg,
      content: ''
    }
    replyList.value.push(replyContent.value)
    MessageApi.sendMessage(msg, conversationId.value, (result: any) => {
      if (result.type == 'id') {
        replyContent.value.chatId = result.id
        conversationId.value = result.value
        global.setConversationId(result.value)
      }
      if (result.type == 'text') {
        replyContent.value.content += result.value
        scrollToBottom()
      }
      if (result.type == 'source') {
        replyContent.value.source = result.value
        scrollToBottom()
      }
      if (result.type == 'completed' || result.type == 'done') {
        replyContent.value = JSON.parse(JSON.stringify(replyContent.value))
        global.setInReply(false)
        MessageApi.stop()
      }
      if (result.type == 'error') {
        global.setInReply(false)
        MessageApi.stop()
      }
    })
  }
}

const stopInReply = () => {
  MessageApi.stop()
  global.setInReply(false)
}

const calculateLines = async (value: any) => {
  await nextTick(); // 确保 DOM 更新
  const textarea = textareaRef.value?.textarea as HTMLTextAreaElement | undefined;
  if (!textarea) return;

  // 获取行高（假设未自定义样式，默认值通常是 20px）
  const lineHeight = parseInt(getComputedStyle(textarea).lineHeight) || 20;

  // 计算实际行数
  const lines = Math.round(textarea.scrollHeight / lineHeight);
  if (value.length >= 200) {
    ElMessage.closeAll();
    ElMessage.warning('最多输入200个字')
  }
  global.setInputLine(lines);
};

const editMessage = (msg: string) => {
  message.value = msg
  inputFocusAndSelectAll()
}

const quickSend = (msg: string) => {
  message.value = msg
  scrollToBottom(true)
  sendMessage()
}

const loadService = (categoryId: number, title: string, avatar: string) => {
  if (global.inReply) {
    return
  }
  scrollToBottom(true);
  global.setAudioChatId('');
  global.setInReply(true)
  global.setSpread(true)
  replyContent.value = {
    type: 'category',
    avatar: getImageUrl(avatar),
    title: title,
    content: categoryId
  }
  let [last] = replyList.value.slice(-1);
  if (last) {
    if (typeof last.content === 'number') {
      if (last.content != categoryId) {
        replyList.value.push(replyContent.value)
      } else {
        global.setInReply(false)
      }
    } else {
      replyList.value.push(replyContent.value)
      global.setInReply(false)
    }
  } else {
    replyList.value.push(replyContent.value)
  }
}

const loadCommonProblem = () => {
  if (global.inReply) {
    return
  }
  scrollToBottom(true);
  global.setAudioChatId('');
  global.setInReply(true)
  global.setSpread(true)
  replyContent.value = {
    type: 'problem',
    avatar: '/images/robot-avatar.png',
    title: '常见问题',
    content: ''
  }
  let [last] = replyList.value.slice(-1);
  if (last) {
    if (last.type != 'problem') {
      replyList.value.push(replyContent.value)
    }
  } else {
    replyList.value.push(replyContent.value)
  }
  global.setInReply(false)
}

const inputFocusAndSelectAll = () => {
  nextTick(() => {
    if (textareaRef.value) {
      textareaRef.value.focus()
      textareaRef.value.select()
    }
  })
}

const setMessage = (msg: string) => {
  message.value = msg
  inputFocusAndSelectAll()
}

// 滚动到底部
const scrollToBottom = (force = false) => {
  nextTick(() => {
    if (global.spread && autoScroll.value && scrollDirection == 'down' || force) {
      bottomRef.value?.scrollIntoView({behavior: 'smooth'})
    }
  })
}
// 处理滚动事件
const handleScroll = ({scrollTop}: any) => {
  if (scrollbarRef.value) {
    if (scrollFlag && beforeScrollTop > scrollTop) {
      scrollDirection='up'
    } else {
      scrollDirection='down'
    }
    let clientHeight = scrollbarRef.value?.$el?.clientHeight ?? 0;
    let scrollHeight = scrollbarRef.value?.wrapRef?.scrollHeight ?? 0;
    // 如果用户手动向上滚动，暂停自动滚动
    autoScroll.value = scrollTop + clientHeight >= scrollHeight - 50;
    beforeScrollTop = scrollTop;
  }
}

const loaded = () => {
  global.setInReply(false)
  scrollToBottom()
}

const emit = defineEmits(['loaded'])

onMounted(() => {
  scrollToBottom()
  emit('loaded', 'input_box')
  MessageApi.stop()
})

watch(replyList, () => {
  scrollToBottom()
}, {deep: true})

watch(() => global.spread, (newVal, oldVal) => {
  if (newVal) {
    setTimeout(() => {
      scrollFlag = true
    }, 500)
  }
})

defineExpose({
  editMessage,
  quickSend,
  loadService,
  loadCommonProblem
})
</script>

<template>
  <div class="chat-container" :class="{spread: global.spread, 'kiosk-chat': isKioskDevice() && global.spread}">
    <!-- 立式一体机模式：输入框在顶部 -->
    <div v-if="isKioskDevice() && global.spread" class="input-box input-box-top" :class="{spread: global.spread}">
      <div class="input-container hover-scale scale101">
        <el-input ref="textareaRef" v-model="message" class="input-container-input" placeholder="请输入你想咨询的问题..."
                  :type="global.spread ? 'textarea' : 'text'"
                  :autosize="{ minRows: 1, maxRows: 3 }"
                  @keyup.enter="sendMessage"
                  maxlength="200"
                  @input="calculateLines"
                  @change="calculateLines"
        />
        <div class="input-buttons">
          <div class="input-buttons-limit">{{ message.length }}/200</div>
          <div class="input-buttons-right">
            <ss-recording @set-message="setMessage"/>
            <div class="buttons-separate"></div>
            <el-button class="send-button" v-if="global.inReply" circle @click="stopInReply">
              <div class="stop-block"></div>
            </el-button>
            <el-button class="send-button" v-else :icon="Top" circle @click="sendMessage"/>
          </div>
        </div>
      </div>
    </div>
    
    <el-scrollbar ref="scrollbarRef" class="ss-chat" @scroll="handleScroll">
      <div class="ss-chat-container">
        <template v-for="(item, idx) in replyList">
          <ss-chat-send-message v-if="item.type == 'send_message'" :message="item.content" @edit-message="editMessage"/>
          <ss-chat-reply v-else :reply="item" @loaded="loaded" @quick-send="quickSend" :last="replyList.length <= idx + 1"/>
        </template>

      </div>
      <div ref="bottomRef"></div>
      <div style="height: 1rem"></div>
    </el-scrollbar>
    
    <!-- 非立式一体机模式：输入框在底部 -->
    <div v-if="!(isKioskDevice() && global.spread)" class="input-box" :class="{spread: global.spread}">
      <div class="input-container hover-scale scale101">
        <el-input ref="textareaRef" v-model="message" class="input-container-input" placeholder="请输入你想咨询的问题..."
                  :type="global.spread ? 'textarea' : 'text'"
                  :autosize="{ minRows: 1, maxRows: 3 }"
                  @keyup.enter="sendMessage"
                  maxlength="200"
                  @input="calculateLines"
                  @change="calculateLines"
        />
        <div class="input-buttons">
          <div class="input-buttons-limit">{{ message.length }}/200</div>
          <div class="input-buttons-right">
            <ss-recording @set-message="setMessage"/>
            <div class="buttons-separate"></div>
            <el-button class="send-button" v-if="global.inReply" circle @click="stopInReply">
              <div class="stop-block"></div>
            </el-button>
            <el-button class="send-button" v-else :icon="Top" circle @click="sendMessage"/>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
@keyframes rotation {
  0% {
    transform: translate(-50%, -50%) rotate(0deg);
  }
  100% {
    transform: translate(-50%, -50%) rotate(360deg);
  }
}

.chat-container {
  position: relative;
  transition: all 0.3s linear;

  &.spread {
    height: 100%;

    .ss-chat {
      height: 100%;
    }
  }

  .ss-chat {
    position: relative;
    height: 0;
    overflow: hidden;
    transition: all 0.3s linear;

    &::after, &:after {
      content: "";
      position: absolute;
      bottom: 0;
      height: 2rem;
      width: 100%;
      z-index: 100;
      background: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1));
    }

    .ss-chat-container {
      max-width: 768px;
      margin: 0 auto;
      height: 100%;
      padding: 0 1rem;
      position: relative;


    }
  }

  .input-box {
    margin-bottom: 3rem;
    margin-right: 1rem;
    margin-left: 1rem;
    transition: all .3s linear;

    .input-container {
      max-width: 768px;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      padding: 1.25rem 1rem;
      border-radius: var(--border-radius);
      position: relative;
      overflow: hidden;
      box-shadow: 0 0.25rem 0.44rem 0 rgba(0, 0, 0, 0.08);
      min-height: var(--min-touch-target);

      &::before, &:before {
        content: "";
        position: absolute;
        width: 110%;
        padding-top: 110%;
        top: 50%;
        left: 50%;
        z-index: -2;
        transform: translate(-50%, -50%);
        background: linear-gradient(45deg, #FFA37C 30%, #FF7BB0 40%, #AD8AFE 60%, #73B9FF 70%);
        animation: rotation 10s infinite linear;
      }

      &::after, &:after {
        content: "";
        position: absolute;
        top: 2px;
        left: 2px;
        bottom: 2px;
        right: 2px;
        z-index: -1;
        border-radius: calc(var(--border-radius) - 0.05rem);
        background-color: #ffffff;
      }

      .input-container-input {
        width: calc(100% - 6rem);
        border: 0;
        background-color: transparent;
        font-size: var(--body-font-size);

        &::-webkit-input-placeholder {
          color: #AEAEB0;
        }

        &::-moz-placeholder {
          color: #AEAEB0;
        }

        &:-ms-input-placeholder {
          color: #AEAEB0;
        }

        &:-moz-placeholder {
          color: #AEAEB0;
        }
      }

      .input-buttons {
        display: flex;
        align-items: flex-end;
        font-size: 1.2rem;

        .input-buttons-limit {
          font-size: 0.88rem;
          color: #7E8AA2;
          display: none;
        }

        .input-buttons-right {
          display: flex;
          align-items: center;

          .microphone {
            cursor: pointer;
            color: #101333;
          }

          .buttons-separate {
            background-color: #D5D6D8;
            height: 1rem;
            width: 1px;
            margin: 0 1rem;
          }

          .send-button {
            position: relative;
            background-color: #2942D4;
            padding: 0.5rem;
            color: #ffffff;
            border: 0;
            font-size: 1.2rem;
            min-width: var(--min-touch-target);
            min-height: var(--min-touch-target);

            .stop-block {
              width: 1rem;
              height: 1rem;
              border-radius: 0.2rem;
              background-color: #ffffff;
            }
          }
        }
      }
    }

    &.position-1 {
      position: absolute;
      z-index: 200;
      width: calc(100% - 2rem);
    }

    &.bottom {
      bottom: 0 !important;
    }

    &.spread {
      .input-container {
        display: block;
        padding: 0.75rem 1rem;

        .input-container-input {
          width: 100%;
        }

        .input-buttons {
          .input-buttons-limit {
            display: block;
          }

          justify-content: space-between;
        }
      }
    }
  }
}

/* 1080x1920 中等尺寸设备 - 输入框优化 */
@media screen and (min-width: 751px) and (max-width: 1200px) and (min-height: 1700px) {
  .chat-container {
    /* 定义统一的内容区域宽度：与顶部导航栏对齐 */
    --kiosk-content-padding: 2rem;
    --kiosk-content-width: calc(100vw - var(--kiosk-content-padding) * 2);

    .ss-chat {
      /* 聊天容器：与顶部导航栏内容区域对齐 */
      .ss-chat-container {
        max-width: var(--kiosk-content-width);
        width: 100%;
        margin: 0 auto;
        padding: 0;
      }
    }

    .input-box {
      margin-bottom: 4rem;
      margin-right: 0;
      margin-left: 0;

      .input-container {
        max-width: var(--kiosk-content-width); /* 与顶部导航栏内容区域对齐 */
        width: 100%;
        margin: 0 auto;
        padding: 1.75rem 1.5rem;
        box-shadow: 0 0.5rem 1rem 0 rgba(0, 0, 0, 0.12);

        /* 增大输入框文字大小 */
        .input-container-input {
          font-size: 1.125rem;
        }

        .input-buttons {
          font-size: 1.5rem;

          .input-buttons-limit {
            font-size: 1.125rem; /* 1rem → 1.125rem */
          }

          .input-buttons-right {
            .buttons-separate {
              height: 1.5rem;
              margin: 0 1.25rem;
            }

            .send-button {
              padding: 0.75rem;
              font-size: 1.5rem;

              .stop-block {
                width: 1.25rem;
                height: 1.25rem;
              }
            }
          }
        }
      }

      &.spread {
        .input-container {
          padding: 1rem 1.5rem;
        }
      }
    }

    /* 立式一体机对话模式：输入框固定在对话区顶部 */
    &.kiosk-chat {
      display: flex;
      flex-direction: column;
      
      .input-box-top {
        order: 1;
        flex-shrink: 0;
        margin-top: 2rem;
        margin-bottom: 1.5rem;
      }
      
      .ss-chat {
        order: 2;
        flex: 1;
        height: auto !important;
      }
    }
  }
}

@media screen and (max-width: 750px) {
  .chat-container {
    .input-box {
      padding: 0 1.25rem;
      margin-bottom: 2rem;

      &.position-1 {
        width: 100%;
      }

      .input-container {
        padding: 0.56rem 0.75rem;
        border-radius: 0.75rem;

        &::after, &:after {
          border-radius: 0.6rem;
        }

        .input-container-input {
          width: calc(100% - 5rem);
        }

        .input-buttons {
          font-size: 1rem;

          .buttons-separate {
            margin: 0 0.9rem;
          }

          .send-button {
            font-size: 1rem;
          }
        }
      }
    }
  }
}
</style>
