<template>
  <div class="px-4px h-full overflow-hidden">
    <div class="back-wap cursor-pointer mb-17px mt--3px !w-fit" @click="goChatIndex">
      <icon-left size="16" class="color-#737478 mr-4px" />
      <span class="cs">返回空间</span>
    </div>
    <div class="workflow-container">
      <div class="left-wap mr-24px" v-if="isCollapsed == false">
        <div class="w-full w-100% mb-15px h-160px rounded-8px bg-#E6E6E8" v-image-main-color="cozeInfo.image_url">
          <img v-if="cozeInfo?.image_url" :src="cozeInfo?.image_url" class="w-full h-full object-contain" />
        </div>
        <div class="content mb-15px">
          <div class="title-body">
            <div class="text mr-4px">{{ cozeInfo?.name }}</div>
            <div class="tag-body">
              <div class="">
                <SvgIcon size="12" name="svg-chatbot" class="color-#6D4CFE" />
              </div>
              <div class="text">对话式</div>
            </div>
          </div>
          <div class="use-body flex items-center">
            <div class="num mr-2px">{{ formatNumberShow({ value: cozeInfo?.views, showExactValue: true }) }}</div>
            <div class="text">次使用</div>
          </div>
        </div>
        <div class="description">
          <div class="text">
            {{ cozeInfo?.description }}
          </div>
        </div>
      </div>
      <div class="right-wap">
        <div class="header">
          <div class="body">
            <div class="">
              <div class="toggle-btn cursor-pointer" @click="toggleCollapse">
                <a-tooltip :content="isCollapsed ? '展开' : '折叠'">
                  <img class="status-icon" :src="isCollapsed ? menuUnfold : menuFold" />
                </a-tooltip>
              </div>
            </div>
          </div>
        </div>
        <div class="coze-content" id="coze-chat-container"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getChatAgent } from '@/api/all/agent';
import { useRouter } from 'vue-router';
import menuFold from '@/assets/svg/menu-fold.svg';
import menuUnfold from '@/assets/svg/menu-unfold.svg';
import { formatNumberShow } from '@/utils/tools';

const router = useRouter();

// 存储认证令牌
const authToken = ref('');
const isCollapsed = ref(false);

// 切换折叠状态
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
};

// 模拟从API获取token
const fetchToken = async () => {
  // 实际开发中应替换为真实的 API 请求
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('pat_' + Math.random().toString(36).substring(2, 15));
    }, 500);
  });
};

// 刷新token
const refreshToken = async () => {
  authToken.value = await fetchToken();
};

const goChatIndex = async () => {
  router.push({
    path: '/agent/index',
  });
};

// 动态加载脚本函数
const loadScript = (src) =>
  new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = src;
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });

const route = useRoute();
const id = route.query.id;
const query = reactive({
  id: id,
});

const cozeInfo = reactive({
  title: '',
  description: '',
  icon_url: '',
  bot_id: '',
  auth: {},
});

let cozeWebSDK = null;
const initChat = async () => {
  const { code, data } = await getChatAgent(query.id);
  if (code !== 200) {
    return false;
  }

  Object.assign(cozeInfo, data.info);
  await loadScript('https://lf-cdn.coze.cn/obj/unpkg/flow-platform/chat-app-sdk/1.2.0-beta.17/libs/cn/index.js');
  let cozeConfig = await cozeWebSdkConfig(data.info.bot_id, data.info.name, data.info.auth, data.info.user_info);
  cozeWebSDK = cozeWebSDK = new CozeWebSDK.WebChatClient(cozeConfig);
  showChatPage();
};

const cozeWebSdkConfig = (botId, name, auth, userInfo) => {
  auth.onRefreshToken = function () {
    return '';
  };
  let config = {
    config: {
      botId: botId,
    },
    ui: {
      chatBot: {
        el: document.getElementById('coze-chat-container'),
        width: '100%',
        height: '100%',
        title: name,
        isNeedFunctionCallMessage: true,
        isNeedAudio: false,
        feedback: {
          isNeedFeedback: true,
          feedbackPanel: {
            title: '您对这个回答有什么看法？请告诉我们',
            placeholder: '请详细描述您的问题...',
            tags: [
              {
                label: '信息不正确',
              },
              {
                label: '涉及敏感信息',
                isNeedDetail: true,
              },
            ],
          },
        },
      },
      base: {
        icon: '',
        zIndex: 1000,
        lang: 'zh-CN',
      },
      footer: {
        expressionText: '内容由AI生成，无法确保真实准确，仅供参考。',
      },
      header: {
        isShow: false,
        isNeedClose: false,
      },
      conversations: {
        isNeed: true,
        isNeedAddNewConversation: true,
        isNeedQuote: true,
      },
    },
    auth: auth,
    userInfo: userInfo,
    header: {
      isShow: false,
      isNeedClose: false,
    },
  };
  return config;
};

const showChatPage = () => {
  cozeWebSDK.showChatBot();
};

onMounted(() => {
  initChat();
});
onUnmounted(() => {
  cozeWebSDK.destroy();
});
</script>

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