<template>
  <div class="dynamic-statistics">
    <div class="data-nav-card-back">
      <div class="data-nav-card">
        <div class="search-card">
          <a-row class="search-title-card">
            <img class="search-title-logo" src="@vue2-client/assets/img/logo.png"/>
            <a-col class="search-title-text">数据检索平台</a-col>
          </a-row>
          <!--          <div class="blue-overlay"></div>-->
          <div class="search-card-main" v-show="currentDialogName !== ''">
            <!-- 搜索栏组件 -->
            <search-bar ref="searchBar" @search="handleSearch"></search-bar>
          </div>
        </div>
      </div>
    </div>
    <div class="data-main-card">
      <a-row style="height:100%">
        <a-col :span="6" style="height:100%;">
          <question-history-and-favorites
            ref="qhaf"
            @handleOpenFavorite="handleOpenFavorite"
            @handleOnlyOpen="handleOnlyOpen"
            :currentKey="currentDialogName"
            @handleSearch="handleSearch"
            @afterCreateDialog="afterCreateDialog"
            @afterDelDialog="afterDelDialog">
          </question-history-and-favorites>
        </a-col>
        <a-col :span="18" style="height:100%">
          <a-spin :spinning="loading" tip="正在努力加载..." wrapperClassName="spingclass">
            <!-- 数据展示Tabs -->
            <data-tabs
              ref="tabs"
              @afterDelDialogOfOne="afterDelDialogOfOne"
            ></data-tabs>
          </a-spin>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script>
import SearchBar from './SearchBar.vue'
import DataTabs from './DataTabs.vue'
import { formatDate } from '@vue2-client/utils/util'
import QuestionHistoryAndFavorites from './QuestionHistoryAndFavorites.vue'
import { post } from '@vue2-client/services/api'
import { indexedDB } from '@vue2-client/utils/indexedDB'

export default {
  name: 'NewDynamicStatistics',
  components: {
    SearchBar,
    DataTabs,
    QuestionHistoryAndFavorites
  },
  data () {
    return {
      cacheSearchArray: {},
      loading: false,
      // 当前选中的uuid
      currentuuid: '',
      //  当前会话名称
      currentDialogName: ''
    }
  },
  methods: {
    //  创建会话完成回调
    afterCreateDialog () {
      this.$refs.qhaf.loadData()
    },
    //  删除会话回调
    afterDelDialog (item) {
      this.currentDialogName = ''
    },
    // 处理搜索逻辑，这里简化为直接赋值，实际应调用API
    async handleSearch (value, queryType, callback, uuid) {
      if (!value) {
        this.$message.warn('请先输入查询的数据')
        callback()
        return
      }
      // 何总说我们自己用 不需要判断有没有评论了
      this.handleSearchMain(value, queryType, callback, uuid)
    },
    handleSearchMain (value, queryType, callback, uuid) {
      this.loading = true
      if (!uuid) {
        uuid = this.uuid()
      }
      const url = '/ai/question/'
      // if (queryType !== 'all') {
      //   url = '/' + url + queryType + '/'
      // }
      post(url, {
        messages: [{
          content: value,
          role: 'user'
        }]
      }).then(res => {
        this.loading = false
        const sql = res.sql ? res.sql.replace(/'/g, "''") : null
        const oldSql = res.old_sql ? res.old_sql.replace(/'/g, "''") : null
        const questionInfo = {
          uuid: uuid,
          question: value,
          queryType: queryType,
          evaluation: -1,
          filterTable: res.filter_table,
          prompt: res.prompt,
          relationTable: res.relation_table,
          similarTable: res.similar_table,
          sql: sql,
          oldSql: oldSql,
          date: formatDate('now'),
          data: res.result,
          isFavorite: false
        }
        // 保存到数据库中
        post('/api/af-system/logic/openapi/addCommonData', {
          type: 'ai-question',
          content: questionInfo
        })
        indexedDB.get(this.currentDialogName, (item) => {
          item.questionList.push(questionInfo)
          indexedDB.update(this.currentDialogName, item)
          this.$refs.qhaf.loadData()
          this.handleOpenFavorite(item)
        })
        this.addTab(questionInfo, false)
      }).catch(e => {
        this.$message.warning(e)
      }).finally(() => {
        callback()
        this.loading = false
      })
    },
    addTab (questionInfo) {
      this.$refs.tabs.show(questionInfo)
    },
    // 处理Tab变更，可以在这里进行额外的逻辑处理
    handleTabChange (uuid) {
      if (uuid) {
        this.$refs.searchBar.setObj(this.cacheSearchArray[uuid])
      } else {
        this.cacheSearchArray = []
        this.$refs.searchBar.init()
      }
    },
    uuid () {
      const tempUrl = URL.createObjectURL(new Blob())
      const uuid = tempUrl.toString() // blob:https://xxx.com/b250d159-e1b6-4a87-9002-885d90033be3
      URL.revokeObjectURL(tempUrl)
      return uuid.substr(uuid.lastIndexOf('/') + 1)
    },
    // 处理从对话历史/收藏夹打开收藏项
    handleOpenFavorite (item) {
      this.currentDialogName = item.key
      this.addTab(item)
    },
    // 处理从对话历史/收藏夹打开收藏项
    handleOnlyOpen (item) {
      this.$refs.tabs.show(item)
    },
    //  删除单个聊天内容回调
    afterDelDialogOfOne () {
      this.$refs.qhaf.loadData()
    }
  }
}
</script>

<style lang="less" scoped>
.dynamic-statistics {
  position: relative;
  overflow: auto;
  height: 100vh;
  background-color: #f5f7fb;
  margin: 0 auto;

  .data-nav-card-back {
    width: 100%;
    height: auto;
  }

  .data-nav-card {
    z-index: 999;
    //position: fixed;
    width: 100%;
    height: 150px;
    top: 0;
    background: #fff;

    .search-title-card {
      height: 65px;
      width: 94%;
      margin: 0 auto;
      position: absolute;
      top: 30%;
      left: 5%;
      display: flex;

      .search-title-logo {
        width: 60px;
        margin-right: 8px;
      }

      .search-title-text {
        line-height: 60px;
        font-size: 20px;
        font-weight: bold;
      }
    }

    .search-card {

      width: 100%;
      height: 100%;
      background-image: url('@vue2-client/assets/img/dynamicStatistics/1080.jpg');
      background-size: cover;
      position: relative;
    }
  }

  .data-main-card {
    //width: 75%;
    height: calc(100vh - 150px);
    padding: 15px 15px 15px 15px;
    background-color: #f5f7fb;
  }

  .blue-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    //background-color: rgba(#4F93FE, 0.8) // 这里设置蓝色蒙版的颜色和透明度
  }

  .search-card-main {
    height: 100%;
  }
}

.spingclass {
  height: 100%;
  background-color: #fff;
  transition: none;
}

:deep(.ant-spin-container) {
  height: 100%;
}
</style>
