<template>
  <div class="go-chart-configurations-data-ajax chat-container">
    <!-- <chart-data-matching-and-show :show="showMatching && !loading" :ajax="true"></chart-data-matching-and-show> -->
    <div class="chat-list" ref="scrollContainer">
      <div
        v-for="(item, index) in messageList.value"
        :key="index"
        :class="['chat-item', item.from == 'user' ? 'user-message' : 'ai-message']"
      >
        <!-- 头像 -->
        <img :src="userIcon" class="user-icon" alt="" />
        <!-- 内容 -->
        <div class="message-content">
          <div class="message-time">{{ item.time }}</div>
          <div class="message-text">
            <!-- 纯文本 -->
            <div class="text-ros" v-if="!item.loading">
              <span v-show="item.type == 'text'">{{ item.text }}</span>
            </div>
            <!-- 思考 -->
            <div class="ai-loading" v-else><span>思考中</span> <n-spin size="small" content-class="spin-class" /></div>
          </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">
          <span></span>
          <n-button :loading="loading" size="small" :class="['chat-send']" :bordered="false" @click="sendHandle">
          </n-button>
        </div>
      </template>
    </n-input>
  </div>
</template>

<script setup lang="ts">
import userIcon from '@/assets/images/ai/user-icon.png'
import { lineAndBar } from '../ChartDataAjax/handlerFormat.js'
import { ref, toRefs, computed, onBeforeUnmount, nextTick, watch, toRaw, reactive, onMounted } from 'vue'
import { icon } from '@/plugins'
import { useDesignStore } from '@/store/modules/designStore/designStore'
import { SettingItemBox, SettingItem } from '@/components/Pages/ChartItemSetting'
import { ChartDataRequest } from '../ChartDataRequest/index'
import {
  RequestHttpEnum,
  ResultEnum,
  SelectHttpTimeNameObj,
  RequestContentTypeEnum,
  RequestHttpIntervalEnum,
  RequestDataTypeEnum,
  RequestBodyEnum
} from '@/enums/httpEnum'
import { chartDataUrl, rankListUrl, scrollBoardUrl, numberFloatUrl, numberIntUrl, textUrl, imageUrl } from '@/api/mock'
import { http, customizeHttp } from '@/api/http'
import { SelectHttpType } from '../..'
import { ChartDataMatchingAndShow } from '../ChartDataMatchingAndShow'
import { useTargetData } from '../../../hooks/useTargetData.hook'
import { newFunctionHandle } from '@/utils'
import { RequestConfigType } from '@/store/modules/chartEditStore/chartEditStore.d'
const { HelpOutlineIcon, FlashIcon, PulseIcon } = icon.ionicons5
const { targetData, chartEditStore } = useTargetData()
import moment from 'moment'
const {
  requestOriginUrl,
  requestInterval: GlobalRequestInterval,
  requestIntervalUnit: GlobalRequestIntervalUnit
} = toRefs(chartEditStore.getRequestGlobalConfig)
const designStore = useDesignStore()

// 是否展示数据分析
const loading = ref(false)
const requestShow = ref(false)
const showMatching = ref(false)

let firstFocus = 0
let lastFilter: any = undefined
let keyWord = ref('')
let lastIndex = ref(0)
//聊天记录list
let messageList: any = reactive([])

const scrollContainer = ref<HTMLElement | null>(null)
// 发送请求
const sendHandle = async () => {
  if (!targetData.value?.request) return
  loading.value = true
  targetData.value.request = {
    requestDataType: RequestDataTypeEnum.AJAX,
    requestHttpType: RequestHttpEnum.POST,
    requestUrl: 'http://baijiahu.mynatapp.cc',
    requestInterval: 300, //十分钟600
    requestIntervalUnit: RequestHttpIntervalEnum.SECOND,
    requestContentType: RequestContentTypeEnum.DEFAULT,
    requestParamsBodyType: RequestBodyEnum.FORM_DATA,
    requestSQLContent: {
      sql: 'select * from  where'
    },
    requestParams: {
      Body: {
        'form-data': {
          prompt: keyWord.value
        },
        'x-www-form-urlencoded': {},
        json: '',
        xml: ''
      },
      Header: {},
      Params: {}
    }
  }
  //存储用户回答
  messageList.value.push({
    from: 'user',
    text: keyWord.value,
    type: 'text',
    time: moment().format('YYYY/MM/DD HH:mm:ss'),
    loading: true
  })
  lastIndex.value = messageList.value.length - 1

  try {
    const res = await customizeHttp(toRaw(targetData.value.request), toRaw(chartEditStore.getRequestGlobalConfig))
    loading.value = false
    messageList.value[lastIndex.value].loading = false
    keyWord.value = ''
    if (res) {
      targetData.value.lastMessagesItem = messageList.value[lastIndex.value] //保存最后一次问答
      targetData.value.filter = lineAndBar
      targetData.value.option.dataset = newFunctionHandle(res.data, res, targetData.value.filter)
      return
    }
    window['$message'].warning('没有拿到返回值，请检查接口！')
  } catch (error) {
    loading.value = false
    console.error(error)
    window['$message'].warning('数据异常，请检查参数！')
  }
}

//监听图表选中变化
watch(
  () => targetData.value.id,
  newData => {
    if (targetData.value.lastMessagesItem) {
      messageList.value = [targetData.value.lastMessagesItem]
    } else {
      messageList.value = []
    }
  },
  {
    immediate: true
  }
)



// 聊天室滚动条
watch(
  messageList.value,
  () => {
    nextTick(() => {
      if (scrollContainer.value) {
        scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight
      }
    })
  },
  { deep: true }
)

onBeforeUnmount(() => {
  lastFilter = null
})
</script>

<style lang="scss" scoped>
.go-chart-configurations-data-ajax {
  height: 87vh;
}
.chat-container {
  & > div {
    width: 100%;
  }
  .user-icon {
    height: 35px;
    width: 35px;
  }
}
/* 设置滚动条整体样式 */
::-webkit-scrollbar {
  width: 0px;
}
</style>
