<template>
  <div class="child-page-display">
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <span class="loading-text">{{ lang.ssAiWait }}</span>
    </div>
    
    <div class="child-page-header">
      <div class="header-left">
        <span class="badge">{{ lang.ssWaitSelection }}</span>
        <span class="hint">{{ formatHint(lang.ssWaitSelectionHint, toolsArray.length) }}</span>
      </div>
      <div class="header-right">
        <button v-for="(tool, index) in toolsArray" :key="tool.tool_id" class="candidate-tag"
          :class="{ active: selectedToolIndex === index }" @click="selectTool(index)">
          {{ lang.ssCandidate }} {{ fillDigit(index + 1, 2) }} {{ tool.tool_name }}
        </button>
      </div>
    </div>

    <div class="child-page-body" v-if="toolsJson?.url === toolsArray[selectedToolIndex]?.url">
      <div class="question-area">
        <template v-for="(tool, index) in toolsArray" :key="tool.tool_id">
          <iframe
          v-if="index === selectedToolIndex && tool.url"
          :src="tool.url + '&isSet=2' + '&timestamp=' + new Date().getTime()"
          frameborder="0"></iframe>
        </template>
      </div>

      <div class="side-panel" v-if="!toolsJson.isSet">
         <button class="side-btn primary" @click="saveTool(toolsJson.url || '', currentToolType, selectedToolIndex)">{{ lang.ssKeep }}</button>
        <button class="side-btn secondary" @click="discardTool(selectedToolIndex)">{{ lang.ssDiscard }}</button>
        <div class="divider"></div>
        <button class="side-btn link" @click="keepAllTools">{{ lang.ssKeepAll }}</button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch, computed } from 'vue'
import { storeToRefs } from 'pinia'
import { useMainStore } from '@/store'
import { fillDigit } from '@/utils/common'
import { lang } from '@/main'
import { useSlidesStore } from '@/store/slides'
import { chat_no_stream, chat_no_stream2 } from '@/tools/aiChat'

const slidesStore = useSlidesStore()
const mainStore = useMainStore()
const { childPageToolsArray, userid, courseTitle, childPageIndex } = storeToRefs(mainStore)
const { setChildPageState } = mainStore
const { currentSlide, slideIndex } = storeToRefs(slidesStore)

const toolsArray = childPageToolsArray.value
const selectedToolIndex = ref(0)
const agentid2 = ref('f86aa63c-b7b7-4d03-9b37-b59f116d36f3')// 生成内容
const loading = ref(true)


const toolsJson = computed(() => {
  return toolsArray[selectedToolIndex.value] || {}
})

const formatHint = (str: string, count: number) => {
  return str.replace('{0}', String(count))
}

const selectTool = (index: number) => {
  selectedToolIndex.value = index
  console.log('👶 选中工具:', toolsArray[index])
}

onMounted(() => {
  console.log('👶 带选页打开，toolsArray:', toolsArray)
  const toolsToCreate = toolsArray.filter(t => !t.url)
  if (toolsToCreate.length === 0) {
    loading.value = false
    // return
  }
  
  // const createPromises = toolsToCreate.map((tool) => {
  //   const originalIndex = toolsArray.findIndex(t => t.tool_id === tool.tool_id)
  //   return createTool(toolsArray, tool, originalIndex)
  // })
  
  // await Promise.all(createPromises)
  // loading.value = false
})

watch(childPageToolsArray, (newVal) => {
  // async 
  console.log('👶 带选页 toolsArray 更新:', newVal)
  const toolsToCreate = newVal.filter(t => !t.url)
  if (toolsToCreate.length === 0) {
    loading.value = false
    // return
  }
  
  // loading.value = true
  // const createPromises = toolsToCreate.map((tool) => {
  //   const originalIndex = newVal.findIndex(t => t.tool_id === tool.tool_id)
  //   return createTool(newVal, tool, originalIndex)
  // })
  
  // await Promise.all(createPromises)
  // loading.value = false
}, { immediate: true, deep: true })

const createTool = async (array: any[], tool: any, index: number) => {
  let action = ''
  let type = 0
  if (tool.tool_id === 'choice') {
    action = lang.ssAiChatQuickAction1
    type = 45
  }
  else if (tool.tool_id === 'qa') {
    action = lang.ssAiChatQuickAction2
    type = 15
  }
  else if (tool.tool_id === 'poll') {
    action = lang.ssAiChatQuickAction6
    type = 78
  }
  else if (tool.tool_id === 'photo') {
    action = lang.ssAiChatQuickAction7
    type = 79
  }
  
  const textContents = currentSlide.value?.elements
    .filter((element: any) => element.type === 'text' || (element.type === 'shape' && element.text && element.text.content))
    .map((textElement: any) => {
      if (textElement.type === 'shape') {
        const tempElement = document.createElement('div')
        tempElement.innerHTML = textElement.text.content
        return tempElement.textContent || tempElement.innerText || ''
      }
      const tempElement = document.createElement('div')
      tempElement.innerHTML = textElement.content
      return tempElement.textContent || tempElement.innerText || ''
    })
    .filter(content => content.trim() !== '') || []
  
  console.log('textContents', textContents)
  const prompt = `
      #课程标题(course_title): ${courseTitle.value || ''}
      #当前页面内容(current_page_content): ${textContents.length > 0 ? textContents.join('\n') : '无文本内容'}
      #query: ${action}
      `
  const result = chat_no_stream(prompt, agentid2.value, userid.value || '', lang.lang)
  console.log(result)
  const content = await result.promise
  console.log('👶 创建工具:', content)

  let jsonFormat = ''
  if (tool.tool_id === 'choice') {
    jsonFormat = `{"testCount":1,"testTitle":"","testJson":[{"id":"7de1fdb4-bec3-4324-8986-4623f838e3d7","type":"2","teststitle":"1+1？","checkList":["1","2","3"],"timuList":[],"answer":[1],"userAnswer":[],"explanation":"解析"}]}`
  }
  else if (tool.tool_id === 'qa') {
    jsonFormat = `{"answerQ":"问题","answer":"","fileList":[],"imageList":[],"evaluationCriteria":"评价标准"}`
  }
  else if (tool.tool_id === 'poll') {
    jsonFormat = `{"testCount":1,"testTitle":"","testJson":[{"id":"7de1fdb4-bec3-4324-8986-4623f838e3d7","type":"2","teststitle":"1+1？","checkList":["1","2","3"],"timuList":[],"answer":[],"userAnswer":[]}]}`
  }
  else if (tool.tool_id === 'photo') {
    jsonFormat = `{"answerQ":"问题","answer":"","fileList":[]}`
  }
  
  const res = await chat_no_stream2([{
    role: 'user',
    content: `这是用户输入的内容："${content}",根据用户输入的内容，生成json。输出一个json格式的回复，格式如下：${jsonFormat}。`,
  }], { type: 'json_object' })
  
  console.log(`${tool.tool_name}`, JSON.parse(res))
  
  const pageId = await setPageId(type, res)
  const baseUrl = setUrl()
  const url = `${baseUrl}/pbl-teacher-table/dist/workPage.html#/setWorkPage?id=${pageId}&type=${type}&userid=${userid.value || ''}`
  array[index].url = url
  setTool()
}

const setTool = () => {
  const slide = currentSlide.value
  slidesStore.updateSlide({ toolsArray: toolsArray }, slide.id)
  console.log(slide)

  // 判断所有工具是否都已保留
  const allToolsSet = toolsArray.every(t => t.isSet)
  if (allToolsSet) {
    const slide = currentSlide.value
    slidesStore.updateSlide({ toolsArray: [] }, slide.id) 
    setChildPageState(false, [], slideIndex.value || 0)
  }
}

const setUrl = () => {
  let url = 'https://beta.pbl.cocorobo.cn'
  if (window.location.href.includes('beta')) {
    url = 'https://beta.pbl.cocorobo.cn/'
  }
  else if (lang.lang === 'cn') {
    url = 'https://pbl.cocorobo.cn/'
  }
  else if (lang.lang === 'hk') {
    url = 'https://pbl.cocorobo.hk/'
  }
  else if (lang.lang === 'en') {
    url = 'https://pbl.cocorobo.com/'
  }
  return url
}

import { getWorkPageId } from '@/services/course'
const setPageId = async (tool: any, json: any) => {
  const res = await getWorkPageId({
    userid: userid.value || '',
    type: tool,
    json: json
  })
  return res[0][0].id
}

import useCreateElement from '@/hooks/useCreateElement'
import useSlideHandler from '@/hooks/useSlideHandler'
const { createSlide } = useSlideHandler()
const { createFrameElement } = useCreateElement()

// 切换页面
const changeSlideIndex = (index: number) => {
  mainStore.setActiveElementIdList([])

  if (slideIndex.value === index) return
  slidesStore.updateSlideIndex(index)
}
// 保留工具
const saveTool = (url: string, type: any, index: number) => {
  console.log('保留工具')
  
  createSlide()
  createFrameElement(url, type)
  changeSlideIndex(childPageIndex.value)
  toolsArray[index].isSet = true
  setTool()
  setTimeout(() => {
    changeSlideIndex(childPageIndex.value + 1)
    setChildPageState(false, [], slideIndex.value || 0)
  }, 100)
  console.log('保留工具', toolsArray)
}

// 放弃工具
const discardTool = (index: number) => {
  toolsArray[index].isSet = true
  setTool()
  console.log('放弃工具', toolsArray)
}

// 保留所有工具
const keepAllTools = () => {
  toolsArray.forEach(tool => {
    if (!tool.isSet) {
      createSlide()
      createFrameElement(tool.url, getToolType(tool.tool_id))
      tool.isSet = true
    }
  })
  changeSlideIndex(childPageIndex.value)
  setTool()
  setTimeout(() => {
    changeSlideIndex(childPageIndex.value + 1)
    setChildPageState(false, [], slideIndex.value || 0)
  }, 100)
}

// 判断工具type
const toolTypeMap: Record<string, number> = {
  'choice': 45,
  'qa': 15,
  'poll': 78,
  'photo': 79
}

const currentToolType = computed(() => {
  const toolId = toolsArray[selectedToolIndex.value]?.tool_id
  return toolId ? toolTypeMap[toolId] || 0 : 0
})

const getToolType = (toolId: string) => {
  return toolTypeMap[toolId] || 0
}
</script>

<style lang="scss" scoped>
.child-page-display {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fffbeb;
  position: absolute;
  top: 0;
  left: 0;
  border-radius: 3px;
  overflow: hidden;
}

.child-page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 7px 20px;
  background: linear-gradient(180deg, #fcd34d 0%, #f59e0b 100%);

  .header-left {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .badge {
    background-color: #d97706;
    color: white;
    padding: 4px 12px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 600;
  }

  .hint {
    color: #78350f;
    font-size: 14px;
  }

  .header-right {
    display: flex;
    gap: 8px;
    background: #d97706;
    padding: 5px 10px;
    border-radius: 30px;
  }

  .candidate-tag {
    background-color: #d97706;
    color: white;
    padding: 4px 12px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
    border: none;
    cursor: pointer;
    transition: all 0.2s;
    border-radius: 30px;

    &:hover {
      background-color: #b45309;
    }

    &.active {
      background-color: white;
      color: #d97706;
    }
  }
}

.child-page-body {
  flex: 1;
  display: flex;
  padding: 20px;
  gap: 20px;
  overflow: auto;
}

.question-area {
  flex: 1;
  background-color: white;
  border: 2px solid #f59e0b;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);

  iframe {
    width: 100%;
    height: 100%;
    border: none;
  }
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 251, 235, 0.95);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 16px;
  z-index: 100;
}

.loading-spinner {
  width: 48px;
  height: 48px;
  border: 4px solid #f59e0b;
  border-top-color: transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text {
  color: #d97706;
  font-size: 16px;
  font-weight: 500;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.side-panel {
  width: 90px;
  display: flex;
  flex-direction: column;
  gap: 12px;

  .side-btn {
    padding: 12px 20px;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;

    &.primary {
      background-color: #f59e0b;
      color: white;

      &:hover {
        background-color: #d97706;
      }
    }

    &.secondary {
      background-color: white;
      color: #6b7280;
      border: 1px solid #e5e7eb;

      &:hover {
        border-color: #f59e0b;
        color: #f59e0b;
      }
    }

    &.link {
      background-color: transparent;
      color: #f59e0b;
      text-align: left;
      padding-left: 0;

      &:hover {
        text-decoration: underline;
      }
    }
  }

  .divider {
    height: 1px;
    background-color: #e5e7eb;
    margin: 4px 0;
  }
}
</style>