<script setup>
import { useClipboard } from '@vueuse/core'
import { useAI } from '@/composables/useAI'
import { useMapStore } from '@/stores/map'
// import { useUserStore } from '@/stores/user'
import { useConnection } from '../composables/useConnection'
import { useIndustry } from '../composables/useIndustry'
import {
  getNameByValue,
  materialMethodList,
  materialUsageList,
  materialUsersList,
  materialPictureStyleList,
  textPurposeList,
} from '@/utils/dictionary'
import IconComputer from './IconComputer.vue'
import IconUser from './IconUser.vue'
import IconAI from './IconAI.vue'
import xss from 'xss'
import { uploadFileByUrl } from '@/utils/upload'

const emit = defineEmits(['submit'])

const form = defineModel()

const materialType = useMapStore().getMapValuesByKey('experiment_marketing_material_type')
const { industryList } = useIndustry()
const { connectionList } = useConnection()

const welcomeMessage = computed(() => {
  const data = form.value
  const way = getNameByValue(data.way, materialMethodList)
  const type = getNameByValue(data.type, materialType)
  const industry = industryList.value.find((item) => item.id == data.industry_id)?.name
  const personnel = getNameByValue(data.personnel_type, materialUsersList)
  const scenario = getNameByValue(data.scenario_type, materialUsageList)
  const connection = connectionList.value.find((item) => item.id == data.channel)?.type_name
  const extendInfo = data.extend_info || {}
  const pictureStyle = getNameByValue(extendInfo.picture_style, materialPictureStyleList)
  const textPurpose = getNameByValue(extendInfo.text_use, textPurposeList)
  console.log(textPurpose, 'textPurpose')

  if (data.type == 1) {
    return `请帮我创作一个在<b class="bold">“${industry}行业”</b>，使用的“<b class="bold">${textPurpose}”</b>，这个内容的使用人员是“<b class="bold">${personnel}”</b>,通过<b class="bold">“${connection}”</b>渠道进行投放，使用场景是<b class="bold">“${scenario}”</b>，字数控制在“<b class="bold">${extendInfo.text_count}字以内</b>“，关键点需要包含：<b class="bold">${data.key_points}</b>。`
  } else if (data.type == 2) {
    return `<b class="bold">${extendInfo.person_des}${extendInfo.scene_des}</b>，重点突出<b class="bold">${extendInfo.important_info_desc}，${pictureStyle}</b>`
  }
  return `你将以<b class="bold">${way}</b>的方式创作一个<b class="bold">${type}内容</b>，该营销内容的所属行业是<b class="bold">${industry}</b>，主要使用人员是<b class="bold">${personnel}</b>，主要使用的场景是用于<b class="bold">${scenario}</b>，主要投放渠道是在<b class="bold">${connection}</b>，内容的关键突出点包含了<b class="bold">${data.key_points}</b>。`
})

const content = ref('')
const route = useRoute()

const { ai, options, usages, messages, post, isLoading, fetchUsages, generateText, generateImage } = useAI({
  experiment_id: route.query.experiment_id,
  marketing_material_id: form.value.id,
})

onMounted(() => {
  fetchUsages()
  messages.value.push({ role: 'system', content: welcomeMessage.value })
  // if (form.value.content) {
  //   messages.value.push({ role: 'bot', content: form.value.content })
  // }
})

watch(welcomeMessage, () => {
  messages.value.splice(0, 1, { role: 'system', content: welcomeMessage.value })
})

// 设置为最后一条ai回复的内容
// watchEffect(() => {
//   const botLastMessage = messages.value.findLast(item => item.role === 'bot')
//   if (botLastMessage) {
//     form.value.content = botLastMessage.content
//   }
// })

async function postMessage() {
  if (!content.value) return
  messages.value.push({ role: 'user', content: content.value })
  if (form.value.type == 2) {
    generateImage({ content: content.value })
  } else {
    post({ content: content.value, type: '1' })
  }
  content.value = ''
}

async function handleSend(event) {
  if (event.shiftKey) return
  event.preventDefault()
  await postMessage()
}

async function handleSendType(type, content) {
  // const userName = useUserStore().user.name
  content = xss(content, {
    whiteList: {}, // 白名单为空，表示过滤所有标签
    stripIgnoreTag: true, // 过滤所有非白名单标签的HTML
    stripIgnoreTagBody: ['script'], // script标签较特殊，需要过滤标签中间的内容
  })
  switch (type) {
    case 2:
      // content = `${content}`
      content = `请帮我创作以下内容：${content.replace('请帮我创作一个', '')}`
      break
    case 3:
      content = `请帮我改写以下内容：${content.replace('请帮我创作一个', '')}`
      break
    case 4:
      content = `请帮我扩写以下内容：${content.replace('请帮我创作一个', '')}`
      break
    case 7:
      content = `请帮我缩写以下内容：${content.replace('请帮我创作一个', '')}`
      break
    case 8:
      content = `请帮我总结以下内容：${content.replace('请帮我创作一个', '')}`
      break
  }
  if (type == 99) {
    generateImage({ type, content })
  } else {
    generateText({ type, content })
  }
}

const chatRef = ref()
function scrollToBottom() {
  if (!chatRef.value) return
  const parentEl = chatRef.value.parentElement
  parentEl.scrollTo(0, parentEl.scrollHeight)
}
watch(messages.value, () => nextTick(() => scrollToBottom()))

const { copy } = useClipboard()

function handleCopy(content) {
  const html = xss(content, {
    whiteList: {}, // 白名单为空，表示过滤所有标签
    stripIgnoreTag: true, // 过滤所有非白名单标签的HTML
    stripIgnoreTagBody: ['script'], // script标签较特殊，需要过滤标签中间的内容
  })
  copy(html)
}

function parseHtml(content) {
  return content.replaceAll('\n', '<br/>')
}
// 保存图片
async function handleSave(message) {
  const url = await uploadFileByUrl(message.image_url)
  form.value.content = url
  emit('submit', form.value)
}
</script>

<template>
  <div class="chat" ref="chatRef">
    <div class="chat-message" :class="item.role" v-for="(item, index) in messages" :key="index">
      <div class="chat-message-avatar">
        <IconComputer v-if="item.role === 'system'" />
        <IconUser v-else-if="item.role === 'user'" />
        <IconAI v-else />
      </div>
      <div class="chat-message-main">
        <div class="chat-message-content">
          <div v-if="item.type === 'image'">
            <img :src="item.image_url" />
          </div>
          <div v-else v-html="parseHtml(item.content)"></div>
        </div>
        <div class="chat-message-extra">
          <!-- 文本 -->
          <template v-if="form.type == 1 && item.role !== 'user'">
            <el-button size="small" type="primary" @click="handleCopy(item.content)">复制</el-button>
            <el-button
              size="small"
              type="primary"
              @click="handleSendType(5, item.input || item.content)"
              v-if="item.role == 'assistant'"
              >刷新
              <!-- ({{ usages.ai_refresh_count }}/{{ usages.ai_refresh_max_count }}) -->
            </el-button>
            <el-button size="small" type="primary" @click="handleSendType(2, item.content)"
              >AI创作
              <!-- ({{ usages.ai_creation_count }}/{{ usages.ai_creation_max_count }}) -->
            </el-button>
            <el-button size="small" type="primary" @click="handleSendType(3, item.content)"
              >AI改写
              <!-- ({{ usages.ai_polish_count }}/{{ usages.ai_polish_max_count }}) -->
            </el-button>
            <el-button size="small" type="primary" @click="handleSendType(4, item.content)"
              >AI扩写
              <!-- ({{ usages.ai_expand_count }}/{{ usages.ai_expand_max_count }}) -->
            </el-button>
            <el-button size="small" type="primary" @click="handleSendType(7, item.content)"
              >AI缩写
              <!-- ({{ usages.ai_abbr_count }}/{{ usages.ai_abbr_max_count }}) -->
            </el-button>
            <el-button size="small" type="primary" @click="handleSendType(8, item.content)"
              >AI总结
              <!-- ({{ usages.ai_summary_count }}/{{ usages.ai_summary_max_count }}) -->
            </el-button>
          </template>
          <!-- 图片 -->
          <template v-if="form.type == 2">
            <template v-if="item.role == 'system'">
              <el-button size="small" type="primary" @click="handleCopy(item.content)">复制</el-button>
              <el-button size="small" type="primary" @click="handleSendType(99, item.content)"
                >生成({{ usages.ai_generate_image_count }}/{{ usages.ai_generate_image_max_count }})</el-button
              >
            </template>
            <template v-if="item.role == 'assistant'">
              <el-button size="small" type="primary" @click="handleSendType(99, item.content)"
                >重画({{ usages.ai_generate_image_count }}/{{ usages.ai_generate_image_max_count }})</el-button
              >
              <el-button size="small" type="primary" @click="handleSave(item)">保存</el-button>
            </template>
          </template>
        </div>
      </div>
    </div>
    <div class="chat-message" v-if="isLoading">
      <div class="chat-message-avatar"><IconAI /></div>
      <div class="chat-message-main">
        <div class="dot-flashing"></div>
      </div>
    </div>
  </div>
  <div class="chat-footer">
    <el-select-v2
      :options="options"
      v-model="ai"
      style="width: 100%; margin-bottom: 10px"
      v-if="form.type == 1"></el-select-v2>
    <el-input
      type="textarea"
      :autosize="{ minRows: 1, maxRows: 12 }"
      placeholder="发消息"
      v-model="content"
      @keydown.enter="handleSend"></el-input>
    <el-button text type="primary" @click="handleSend">发送</el-button>
  </div>
</template>

<style lang="scss">
.chat {
  height: calc(100vh - 90px - 280px);
  overflow-y: auto;
}
.chat-footer {
  position: relative;
  margin-top: 40px;
  .el-textarea__inner {
    padding: 16px;
    resize: none;
  }
  .el-button {
    position: absolute;
    right: 10px;
    bottom: 10px;
  }
}
.chat-message {
  margin: 30px 0;
  display: flex;
  flex-direction: row;
  gap: 10px;
}
.chat-message-avatar {
  flex: 0 0 40px;
  height: 40px;
  background-color: #fff;
  border-radius: 50%;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}
.chat-message-main {
  color: #000;
  max-width: 100%;
  padding: 20px;
  border-radius: 16px;
  background-color: #fff;
}
.chat-message-content {
  max-width: 100%;
  word-break: break-word;
  * {
    max-width: 100%;
  }
}
.user .chat-message-main {
  color: #fff;
  background-color: var(--main-color);
}

.chat-message-extra:not(:empty) {
  margin-top: 20px;
  padding-top: 12px;
  border-top: 1px solid #edeff1;
}

.chat-message-extra button {
  margin-bottom: 10px;
}

.dot-flashing {
  animation: dot-flashing 0.8s infinite alternate;
  animation-delay: -0.2s;
  animation-timing-function: ease;
  margin: 7px 18px;
  overflow: visible !important;
  position: relative;
}

.dot-flashing,
.dot-flashing:after,
.dot-flashing:before {
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  color: rgba(0, 0, 0, 0.1);
  height: 8px;
  width: 8px;
}

.dot-flashing:after,
.dot-flashing:before {
  animation: dot-flashing 0.8s infinite alternate;
  animation-timing-function: ease;
  content: '';
  display: inline-block;
  position: absolute;
  top: 0;
}

.dot-flashing:before {
  left: -15px;
  animation-delay: -0.4s;
}

.dot-flashing:after {
  left: 15px;
  animation-delay: 0s;
}

@keyframes dot-flashing {
  0% {
    background-color: #000;
  }

  50% {
    background-color: rgba(0, 0, 0, 0.1);
  }

  to {
    background-color: #000;
  }
}
.bold {
  padding: 0 3px;
  font-size: 16px;
  font-weight: bold;
  color: var(--main-color);
}
</style>
