<template>
  <div>
    <suspensionButton>
      <img src="~@/assets/images/ai/ai-botton.png" alt="" class="ai-botton" @dblclick="openAi()" />
    </suspensionButton>
    <n-modal
      v-model:show="showModal"
      class="custom-card"
      preset="card"
      :block-scroll="false"
      :style="bodyStyle"
      title="AI助手"
      size="huge"
      :bordered="false"
      :segmented="segmented"
    >
      <div class="ai-container">
        <div class="chat-container">
          <div class="chat-list" ref="scrollContainer">
            <AiHint v-model="keyWord" @sendMessage="handleSend"></AiHint>
            <div
              v-for="(item, index) in messageList"
              :key="index"
              :class="['chat-item', item.from == 'user' ? 'user-message' : 'ai-message']"
            >
              <!-- 头像 -->
              <img :src="item.from == 'user' ? userIcon : aiIcon" class="user-icon" alt="" />
              <!-- 内容 -->
              <div class="message-content">
                <div class="message-time">{{ item.time }}</div>
                <div class="message-text" :id="`box${index}`">
                  <!-- 纯文本 -->
                  <div class="text-ros">
                    <span v-show="item.type == 'text'">{{ item.text }}</span>
                    <AddIssue :issueText="item.text" :list="dictList" v-show="item.add"></AddIssue>
                  </div>
                  <!-- 图表 -->
                  <initEcharts :item="item" :currentIndex="index" @changeTheme="handlerTheme"></initEcharts>
                  <!-- 表格 -->
                  <AiTable :obj="item"></AiTable>
                  <!-- 思考 -->
                  <inThinking :item="item"></inThinking>
                  <!-- 免责 -->
                  <disclaimer :item="item" :currentIndex="index"></disclaimer>
                </div>
              </div>
            </div>
          </div>
          <!-- 搜索 -->
          <n-input
            class="chat-input"
            round
            v-model:value="keyWord"
            type="textarea"
            placeholder="请输入需要统计的数据"
            :autosize="{ minRows: 5 }"
          >
            <template #suffix>
              <div class="chat-suffix">
                <IssueQuey :list="dictList" v-model="keyWord" @sendMessage="handleSend">常用问题</IssueQuey>
                <n-button :loading="loading" size="small" :class="['chat-send']" :bordered="false" @click="handleSend">
                </n-button>
              </div>
            </template>
          </n-input>
        </div>
        <div class="chat-history">
          <AiHistory @finishInfo="finishInfo" @handlerAddmsg="saveMessage" ref="history"></AiHistory>
        </div>
      </div>
    </n-modal>
  </div>
</template>

<script setup>
import { onMounted, ref, nextTick, watch,reactive } from 'vue'
import {
  AiHint,
  AiTable,
  AddIssue,
  IssueQuey,
  disclaimer,
  inThinking,
  initEcharts,
  AiHistory
} from '@/views/AI/components'
import userIcon from '@/assets/images/ai/user-icon.png'
import aiIcon from '@/assets/images/ai/ai-icon.png'
import { LineChart, BarChart, PieChart } from '@/views/AI/chat/class/index'
import suspensionButton from '../../components/suspensionButton/index.vue'
import { getDict, historyMessageRoomUpdata, historyMessageRoom } from '@/api/path'
import moment from 'moment'
import { getAiMsg } from '@/api/ai.js'
import { httpErrorHandle } from '@/utils'
import { useSystemStore } from '@/store/modules/systemStore/systemStore'

const systemStore = useSystemStore()
//输入框加载
let loading = ref(false)
const ehcatrsType = ['pie', 'line', 'bar', 'number']
//聊天室容器
const scrollContainer = ref(null)
const history = ref(null)
let isloading = ref(false)
let infoId = ref(null)
let stopWatch = null
let isWatching = ref(false)
let showModal = ref(true)
let messageList = ref([])
//聊天记录最后一个索引
let lastIndex = ref(0)
let keyWord = ref('')
let dictList = ref([])
const bodyStyle = {
  width: '55%'
}
const segmented = {
  content: 'soft',
  footer: 'soft'
}

onMounted(() => {
  // getDictListist()
})
/**
 * 字典
 */
const getDictListist = async () => {
  const res = await getDict()
  dictList.value = res.data.records
}

/**
 * 获取详情后处理数据
 * @param e
 */
const finishInfo = res => {
  infoId.value = res.id
  messageList.value = []
  res.content.map((item, index) => {
    item.chartInstanceActiveIndex = 0
    messageList.value.push(item)
    nextTick(() => {
      initEchart(item.chartInstanceItem, item, index)
    })
  })
}

/**
 * 新建聊天---检查本地是否存在聊天对话，存在的化先保存
 */
const saveMessage = async () => {
  if (messageList.value.length > 0 && !isloading.value) {
    //销毁渲染的图表
    messageList.value.forEach(instance => {
      if (ehcatrsType.includes(instance.type) && instance.chartInstanceItem) {
        console.log(instance)
        instance.chartInstanceItem.dispose()
      }
    })
    console.log(messageList.value)
    const jsonData = JSON.stringify(messageList.value)
    let res
    isloading.value = true
    if(infoId.value){
      res = await historyMessageRoomUpdata({ content: jsonData, id: infoId.value})
    }else{
      res = await historyMessageRoom({ content: jsonData, createUserId: systemStore.userInfo.userId || 1 })
    }
    if (res.code === 200) {
      history.value.messageList()
    } else {
      httpErrorHandle()
    }
  }
  isloading.value = false
  messageList.value = []
  lastIndex.value = 0
  infoId.value = null
  keyWord.value = ''
}

/**
 * 问答
 */
const handleSend = async () => {
  if (!keyWord.value.trim() && loading.value) {
    return
  }

  loading.value = true
  //存储用户回答
  setMessageItem({
    from: 'user',
    text: keyWord.value,
    type: 'text',
    time: moment().format('YYYY/MM/DD HH:mm:ss'),
    add: true
  })

  //先存储AI回答，作为交互提示，接口响应后再做更新
  setMessageItem(
    {
      from: 'ai',
      text: '',
      time: moment().format('YYYY/MM/DD HH:mm:ss'),
      loading: true, //ai思考中
      chartInstanceItem: null,
      chartInstanceActiveIndex: 0,
      type: 'text',
      xData: [],
      yData: []
    },
    false
  )
  try {
    const res = await getAiMsg({ prompt: keyWord.value })

    // 更新
    updataMessageItem({
      from: 'ai',
      text: res.data,
      time: moment().format('YYYY/MM/DD HH:mm:ss'),
      loading: false, //ai思考中
      chartInstanceItem: null,
      chartInstanceActiveIndex: 0,
      type: res.type,
      xData: res.xData,
      data: res.data,
      title: res.title,
      unit: res.unit
    })
    nextTick(() => {
      const itemData = messageList.value[lastIndex.value]
      initEchart(itemData.chartInstanceItem, res, lastIndex.value)
    })
  } catch {
    updataMessageItem({
      from: 'ai',
      type: 'text',
      text: '服务器繁忙，请稍后再试。',
      time: moment().format('YYYY/MM/DD HH:mm:ss'),
      loading: false
    })
  }
}

/**
 *
 * @param currentItem
 * @param res
 */
const initEchart = (chartInstanceItem, res, index) => {
  //饼图
  if (res.type === 'pie') {
    chartInstanceItem = new PieChart(`${res.type}${index}`, {
      title: res.title,
      unit: res.unit,
      data: res.data
    })
  } else if (res.type === 'bar') {
    chartInstanceItem = new BarChart(`${res.type}${index}`, {
      title: res.title,
      unit: res.unit,
      xData: res.xData,
      data: res.data
    })
  } else if (res.type === 'line') {
    chartInstanceItem = new LineChart(`${res.type}${index}`, {
      title: res.title,
      unit: res.unit,
      xData: res.xData,
      data: res.data
    })
  }
}

/**
 * 存储聊天室数据
 * @param obj
 */

const setMessageItem = (obj, set = true) => {
  messageList.value.push(obj)
  lastIndex.value = messageList.value.length - 1
}
/**
 * ai回答后更新对应数据
 * @param data
 */
const updataMessageItem = data => {
  messageList.value[lastIndex.value] = data
  keyWord.value = ''
  loading.value = false
}

/**
 * 图表切换主题
 * @param index
 */
const handlerTheme = (item, index) => {
  if (isWatching.value) {
    pauseWatching()
    isWatching.value = false
    console.log('暂停')
  }
  item.chartInstanceActiveIndex = index
  item.chartInstanceItem.changeColorStyle(index)

  setTimeout(() => {
    startWatching()
    console.log('监听')
  }, 5000)
}
const pauseWatching = () => {
  if (stopWatch) {
    stopWatch() // 调用停止函数
    stopWatch = null
  }
}
// 聊天室自动滚动条下拉
const startWatching = () => {
  stopWatch = watch(
    messageList.value,
    newVal => {
      nextTick(() => {
        if (scrollContainer.value) {
          scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight
        }
      })
    },
    { deep: true }
  )
  isWatching.value = true
}

const openAi = () => {
  messageList.value = []
  getDictListist()
  startWatching()
  showModal.value = true
}
</script>

<style lang="scss" scoped>
.ai-botton {
  cursor: grab;
  width: 160px;
  height: 80px;
}
.ai-botton:active {
  cursor: grabbing;
}
.ai-container {
  height: 70vh;
  width: 100%;
  display: flex;
  align-items: center;
  & > div {
    height: 100%;
  }
  .chat-container {
    box-sizing: border-box;
    padding: 0 100px 0 80px;
    width: 80%;
    border-right: 1px solid #000000;
    .chat-list,
    .chat-input {
      width: 100%;
    }
    .chat-input {
      border: 1px solid #3c434d !important;
      background: rgba(57, 58, 68, 0.5) !important;
    }
  }
  .chat-history {
    width: 20%;
    box-sizing: border-box;
    padding: 10px;
  }
}

.message-text {
  background: #2f323b;
  border-radius: 10px;
  border: 1px solid #3c434d;
}

/* 设置滚动条整体样式 */
::-webkit-scrollbar {
  width: 0px;
}
</style>
