<template>
  <a-card
    class="question-history"
    id="question-history"
    size="small"
    :bordered="false"
    :bodyStyle="{ height:'100%', overflowY: 'auto'}">
    <a-tabs v-model="activeKey" :tabBarStyle="{ textAlign: 'center',height:'100%' }" tabPosition="top">
      <a-tab-pane key="1" tab="对话历史">
        <a-list item-layout="horizontal" :data-source="questions">
          <a-list-item
            slot="renderItem"
            :class="renderItem.sql ? (renderItem.uuid === currentuuid ? 'question-history-active' : 'question-history-inactive') : (renderItem.uuid === currentuuid ? 'question-history-active-bug' : 'question-history-inactive-bug')"
            slot-scope="renderItem,index"
            @click="handleOpenFavorite(renderItem)">
            <a-list-item-meta
              :title="renderItem.question"
              :description="renderItem.date"
            />
            <a-space>
              <a-tooltip title="查看元数据">
                <a-icon
                  v-if="renderItem.data"
                  type="eye"
                  @click.stop="openMetaDataModal(renderItem)"/>
              </a-tooltip>
              <span>&emsp;</span>
              <a-tooltip title="删除对话">
                <a-icon
                  type="delete"
                  theme="filled"
                  class="delClass"
                  @click.stop="delQuestion(renderItem,index)"/>
              </a-tooltip>
              <span>&emsp;</span>
              <a-tooltip :title="renderItem.isFavorite ? '取消收藏' : '收藏'" v-if="renderItem.sql">
                <a-icon
                  type="star"
                  :class="renderItem.isFavorite ? 'startActive' : 'startInactive'"
                  @click.stop="toFavorites(renderItem,index,'lib')"
                  :theme=" renderItem.isFavorite ? 'filled': 'twoTone'"
                  two-tone-color="#FFD700"/>
              </a-tooltip>
              <a-tooltip title="重新查询" v-else>
                <a-icon
                  @click.stop="reTrySearch(renderItem, index)"
                  type="sync"
                  class="reSearch"
                  title="重新查询"/>
              </a-tooltip>
            </a-space>
          </a-list-item>
        </a-list>
      </a-tab-pane>
      <a-tab-pane key="2" tab="收藏的对话" force-render>
        <a-list item-layout="horizontal" :data-source="favorites">
          <a-list-item
            slot="renderItem"
            slot-scope="renderItem, index"
            :class="renderItem.uuid === currentuuid ? 'question-history-active' : 'question-history-inactive'"
            @click="handleOpenFavorite(renderItem, true)">
            <a-list-item-meta
              :title="renderItem.question"
              :description="renderItem.date"
            />
            <a-space>
              <a-tooltip title="查看元数据">
                <a-icon
                  v-if="renderItem.data"
                  type="eye"
                  @click.stop="openMetaDataModal(renderItem)"/>
              </a-tooltip>
              <span>&emsp;</span>
              <a-icon
                type="star"
                :class="renderItem.isFavorite ? 'startActive' : 'startInactive'"
                @click.stop="delFavorites(renderItem,index)"
                :theme=" renderItem.isFavorite ? 'filled': 'twoTone'"
                two-tone-color="#FFD700"/>
            </a-space>
          </a-list-item>
        </a-list>
      </a-tab-pane>
      <a-tab-pane key="3" tab="对话库">
        <a-button type="dashed" class="pullQuestion" :loading="pullQuestionLoading" @click="pullQuestion">
          拉取对话
        </a-button>
        <a-list item-layout="horizontal" :data-source="questionsLib">
          <a-list-item
            slot="renderItem"
            class="questionItem"
            :class="[renderItem.sql ? (renderItem.uuid === currentuuid ? 'question-history-active' : 'question-history-inactive') : (renderItem.uuid === currentuuid ? 'question-history-active-bug' : 'question-history-inactive-bug'),
                     index===0 || questionsLib[index].date !== questionsLib[index-1].date ? 'mgtop-20' : '']"
            slot-scope="renderItem,index"
            @click="handleOnlyOpen(renderItem)">
            <a-divider v-if="index===0 || questionsLib[index].date !== questionsLib[index-1].date" class="questionItemDivider">
              {{ timeAgo(renderItem.date) }}
            </a-divider>
            <a-list-item-meta
              :description="renderItem.date"
            >
              <span slot="title">
                {{ renderItem.question }}
                <br/>
                <span class="evaluation" v-if="icons[renderItem.evaluation]">
                  <a-icon
                    :type="icons[renderItem.evaluation].icon"
                    theme="twoTone"
                    style="font-size: 1rem"
                    :two-tone-color="icons[renderItem.evaluation].color"/>
                  【{{ icons[renderItem.evaluation].text }}】
                </span>
                <span class="evaluation" v-else>
                  <a-icon type="message" style="font-size: 1rem" theme="twoTone" two-tone-color="#999"/>
                  未评价
                </span>
              </span>
            </a-list-item-meta>
            <a-space>
              <a-tooltip title="查看元数据">
                <a-icon
                  v-if="renderItem.data"
                  type="eye"
                  @click.stop="openMetaDataModal(renderItem)"/>
              </a-tooltip>
              <span>&emsp;</span>
              <a-tooltip :title="renderItem.isFavorite ? '取消收藏' : '收藏'" v-if="renderItem.sql">
                <a-icon
                  type="star"
                  :class="renderItem.isFavorite ? 'startActive' : 'startInactive'"
                  @click.stop="libToFavorites(renderItem,index)"
                  :theme=" renderItem.isFavorite ? 'filled': 'twoTone'"
                  two-tone-color="#FFD700"/>
              </a-tooltip>
              <a-tooltip title="重新查询" v-else>
                <a-icon
                  @click.stop="reTrySearch(renderItem, index)"
                  type="sync"
                  class="reSearch"
                  title="重新查询"/>
              </a-tooltip>
            </a-space>
          </a-list-item>
        </a-list>
      </a-tab-pane>
    </a-tabs>
    <a-modal
      width="1200px"
      title="元数据"
      @cancel="handleCancel"
      :visible="metaDataModalVisible"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="uuid">
          {{ item.uuid }}
        </a-descriptions-item>
        <a-descriptions-item label="问题">
          {{ item.question }}
        </a-descriptions-item>
        <a-descriptions-item label="类型">
          {{ item.queryType }}
        </a-descriptions-item>
        <a-descriptions-item label="filterTable">
          {{ item.filterTable }}
        </a-descriptions-item>
        <a-descriptions-item label="relationTable">
          {{ item.relationTable }}
        </a-descriptions-item>
        <a-descriptions-item label="similarTable">
          {{ item.similarTable }}
        </a-descriptions-item>
        <a-descriptions-item label="prompt">
          {{ item.prompt }}
        </a-descriptions-item>
        <a-descriptions-item label="sql">
          {{ item.sql }}
        </a-descriptions-item>
        <a-descriptions-item label="oldSql">
          {{ item.oldSql }}
        </a-descriptions-item>
        <a-descriptions-item label="查询日期">
          {{ item.date }}
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </a-card>
</template>

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

export default {
  props: {
    currentuuid: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      activeKey: '1',
      actions: [
        { type: 'star-o', text: '156' },
        { type: 'like-o', text: '156' },
        { type: 'message', text: '2' },
      ],
      questions: [], // 你的问题历史
      favorites: [], // 你的收藏问题
      questionsLib: [], // 对话库
      icons: {
        0: {
          icon: 'like',
          text: '满意'
        },
        1: {
          icon: 'dislike',
          text: '不满意',
          color: '#FF4F53'
        },
        2: {
          icon: 'dislike',
          text: '不满意',
          color: '#FF4F53'
        }
      }, // 对话库
      // 元数据窗口
      metaDataModalVisible: false,
      item: {},
      pullQuestionLoading: false
    }
  },
  mounted () {
    this.loadData()
  },
  methods: {
    // 根据时间yyyy-mm-dd hh24:mi:ss判断是刚刚？今天？昨天？还是更早？
    timeAgo (time) {
      const now = new Date()
      const date = new Date(time)
      const diff = now - date
      const day = 24 * 60 * 60 * 1000
      if (diff < 60 * 60 * 1000) {
        return '刚刚'
      } else if (diff < day) {
        return '今天'
      } else if (diff < day * 2) {
        return '昨天'
      } else {
        return time.substring(0, 10)
      }
    },
    pullQuestion () {
      this.pullQuestionLoading = true
      post('/api/af-system/logic/openapi/getCommonData', {
        type: 'ai-question',
        content: ''
      }).then(res => {
        const _questionsLib = []
        res.forEach(item => {
          const _item = JSON.parse(item.f_json)
          if (_item.data && _item.data.length) {
            if (!this.questionsLib.some(_ => _.uuid === _item.uuid)) {
              _item.date = formatDate('now')
              _questionsLib.push(_item)
              indexedDB.add('question-lib-' + _item.uuid, _item)
            }
          }
        })
        // _questionsLib 根据问题question文字排序
        _questionsLib.sort((a, b) => a.question.localeCompare(b.question))
        // 把_questionsLib 放到 questionsLib 上面
        this.questionsLib = _questionsLib.concat(this.questionsLib)
        this.pullQuestionLoading = false
      }).catch(e => {
        this.pullQuestionLoading = false
      })
    },
    loadData () {
      this.questions = []
      this.favorites = []
      indexedDB.getAll((data) => {
          // 遍历data，将question和favorites分别赋值给questions和favorites
          for (const datum of data) {
            if (datum.key.includes('question-lib')) {
              this.questionsLib.push(datum.data)
            } else if (datum.key.includes('favorites')) {
              this.favorites.push(datum.data)
            } else if (datum.key.includes('question')) {
              this.questions.push(datum.data)
            }
          }
          this.questions.sort((a, b) => new Date(b.date) - new Date(a.date))
          this.favorites.sort((a, b) => new Date(b.date) - new Date(a.date))
          this.questionsLib.sort((a, b) => new Date(b.date) - new Date(a.date))
        }
      )
    },
    handleOpenFavorite (item, reSearch) {
      this.$emit('handleOpenFavorite', item, reSearch)
    },
    handleOnlyOpen (item) {
      this.$emit('handleOnlyOpen', item)
    },
    submitEvaluationLib (value, uuid) {
      // 根据uuid 在 questionslib里卖弄找到这个对象
      const item = this.questionsLib.find(item => item.uuid === uuid)
      const key = 'question-lib-' + uuid
      // 收藏状态不存储到库里
      delete item.isFavorite
      const content = Object.assign(item, {
        evaluation: value
      })
      // 使用 content 替换 item
      this.questionsLib = this.questionsLib.map(_item => {
        if (_item.uuid === uuid) {
          _item = content
        }
        return _item
      })
      if (content.sql) {
        // 处理sql的单引号
        content.sql = content.sql.replaceAll(/'/g, "''")
      }
      if (content.oldSql) {
        // 处理sql的单引号
        content.oldSql = content.oldSql.replaceAll(/'/g, "''")
      }
      console.log(content)
      // 保存到数据库中
      post('/api/af-system/logic/openapi/updateCommonData', {
        type: 'ai-question',
        content: uuid,
        newContent: content
      }).then(res => {
        this.$message.success('评论成功')
        indexedDB.delete(key)
        indexedDB.add(key, content)
      })
    },
    reTrySearch (item, index) {
      this.delQuestion(item, index)
      this.$emit('handleSearch', item.question, null, item.uuid)
    },
    add (question) {
      // 检查 questions 数组中是否已经存在这个问题 替换掉
      const index = this.questions.findIndex(item => item.uuid === question.uuid)
      const index2 = this.favorites.findIndex(item => item.uuid === question.uuid)
      if (index2 !== -1) {
        return
      }
      if (index !== -1) {
        if (question.data) {
          this.questions.splice(index, 1, Object.assign(question, { date: this.questions[index].date }))
        } else {
          this.questions.splice(index, 1, question)
        }
        this.updateQuestion(question)
      } else {
        this.questions.push(question)
        this.handleOpenFavorite(question)
        indexedDB.add('question-' + question.uuid, question)
        this.loadData()
      }
    },
    updateQuestion (question) {
      console.log(question)
      const questionKey = 'question-' + question.uuid
      indexedDB.delete(questionKey)
      indexedDB.add(questionKey, question)
    },
    openMetaDataModal (item) {
      this.item = item
      this.metaDataModalVisible = true
    },
    handleCancel () {
      this.metaDataModalVisible = false
    },
    toFavorites (question, index) {
      this.questions[index].isFavorite = !this.questions[index].isFavorite
      if (this.questions[index].isFavorite) {
        const key = 'favorites-' + question.uuid
        question.date = formatDate('now')
        question.isFavorite = true
        indexedDB.add(key, question)
        this.favorites.push(question)
        this.$message.success('收藏成功')
      } else {
        // 根据 uuid 删除 favorites 中的对应项
        this.favorites = this.favorites.filter(item => item.uuid !== question.uuid).sort((a, b) => new Date(b.date) - new Date(a.date))
        // 删除收藏的储存
        const key = 'favorites-' + question.uuid
        indexedDB.delete(key)
      }
      this.updateQuestion(question)
    },
    libToFavorites (question, index) {
      this.questionsLib[index].isFavorite = !this.questionsLib[index].isFavorite
      this.questionsLib = JSON.parse(JSON.stringify(this.questionsLib))
      if (this.questionsLib[index].isFavorite) {
        const key = 'favorites-' + question.uuid
        question.isFavorite = true
        // 避免从其他地方收藏了这个 uuid
        indexedDB.delete(key)
        indexedDB.add(key, question)
        this.favorites.push(Object.assign({}, question, { date: formatDate('now') }))
        this.$message.success('收藏成功')
      } else {
        // 根据 uuid 删除 favorites 中的对应项
        this.favorites = this.favorites.filter(item => item.uuid !== question.uuid).sort((a, b) => new Date(b.date) - new Date(a.date))
        // 删除收藏的储存
        const key = 'favorites-' + question.uuid
        indexedDB.delete(key)
      }

      const questionKey = 'question-lib-' + question.uuid
      indexedDB.delete(questionKey)
      indexedDB.add(questionKey, this.questionsLib[index])
    },
    delQuestion (item, index) {
      // 删除对话历史
      this.questions.splice(index, 1)
      const key = 'question-' + item.uuid
      indexedDB.delete(key)
      // 删除收藏
      const favoritesKey = 'favorites-' + item.uuid
      indexedDB.delete(favoritesKey)
    },
    delFavorites (item, index) {
      this.favorites.splice(index, 1)
      // 根据uuid寻找 questions 中的对应项
      // 重新赋值给 questions
      this.questions = this.questions.map(_item => {
        if (_item.uuid === item.uuid) {
          _item.isFavorite = false
        }
        return _item
      })
      const key = 'favorites-' + item.uuid
      indexedDB.delete(key)
      this.$message.success('取消收藏成功')
      // 如果favorites为空，切换到对话历史
      if (this.favorites.length === 0) {
        this.activeKey = '1'
      }
      this.updateQuestion(item)
    }
    ,
  }
}
</script>

<style scoped lang="less">

#question-history {

  margin-right: 10px;
  height: 100%;
  border-radius: 8px;

  .question-history-active-bug {
    border-left: 4px solid #FF0036;
    border-radius: 4px;
    padding: 18px 18px 18px 14px;
    background-color: rgba(#ff0000, 0.04);
  }

  .question-history-active {
    border-left: 4px solid #1890FF;
    border-radius: 4px;
    padding: 18px 18px 18px 14px;
  }

  .question-history-inactive-bug {
    border-radius: 4px;
    padding: 18px;
    background-color: rgba(#ff0000, 0.04);
  }

  .question-history-inactive {
    border-radius: 4px;
    padding: 18px;
  }

  .ant-list-item-meta /deep/ {
    width: 60%;
  }

  .ant-list-item-meta-content /deep/ {
    width: 98%;
  }

  .ant-list-item-meta-title /deep/ {
    width: 90%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .ant-card {
    height: 100%;
    overflow-y: auto;
  }

  .startActive {
    color: #FFD700;
    font-size: 1rem;
  }

  .startInactive {
    font-size: 1rem;
  }

  .delClass {
    font-size: 1rem;
    color: #777;
  }

  .reSearch {
    font-size: 1rem;
    color: #1890FF;
  }

  .reSearch:hover {
    animation: rotate 0.5s ease-in-out both;
  }

  @keyframes rotate {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(180deg);
    }
  }

  .startActive, .startInactive, .reSearch {
    transition: transform 0.1s;
  }

  .startActive:hover, .startInactive:hover {
    animation: shake 0.5s ease-in-out both;
  }

  @keyframes shake {
    0% {
      transform: rotate(0deg);
    }
    25% {
      transform: rotate(-20deg);
    }
    50% {
      transform: rotate(0deg);
    }
    75% {
      transform: rotate(20deg);
    }
    100% {
      transform: rotate(0deg);
    }
  }

  .pullQuestion {
    width: 100%;
    margin-bottom: 10px;
  }

  .evaluation {

  }

  .mgtop-20 {
    margin-top: 20px;
  }

  .questionItemDivider {
    position: absolute;
    top: -25px
  }

  .questionItem {
    position: relative;
  }
}

.scroller {
  height: 100%;
  overflow-y: auto;
}
</style>
