<template>
  <div class="intelligentQA">
    <div class="history">
      <div class="historyTitle">历史记录</div>
      <div class="historyContent">
        <div v-for="item in historyData" :key="item.id" class="historyItem">
          <span style="float: left"> {{ item.question }}</span>
          <i class="el-icon-more historyMore" @click="historyDetail(item.id)"></i>
        </div>
      </div>
    </div>
    <div class="chat">
      <!-- <div class="header">Header</div> -->
      <div ref="main" class="main">
        <div class="chatLine">
          <div v-for="(item, index) in chatInfo" :key="index">
            <div class="chatRow chatQ" v-if="item.question">
              <div class="questionContent">{{ item.question }}</div>
            </div>
            <div class="chatRow" v-if="item.answer">
              <div class="answerData">
                <div class="answer">{{ item.answer }}</div>
                <!-- <div class="graph"></div> -->
                <graphECharts v-if="item.graph" :graphData="item.graph" class="charts"></graphECharts>
                <i v-if="item.answer" class="el-icon-more more" @click="handleMore(item)"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="footer">
        <div class="footerContent">
          <textarea v-model="questionInput" :style="{ height: `${currentHeight}px`, overflowY: isScrollable ? 'auto' : 'hidden' }" placeholder="请输入您的问题..." @keydown="handleKeydown"> </textarea>
          <i class="el-icon-s-promotion icon" @click="sendQuestion"></i>
        </div>
      </div>
    </div>
    <div class="statistics">
      <div class="statisticsTitle">统计列表</div>
    </div>
    <el-dialog title="更多" :visible.sync="dialogVisible" width="1500px" :before-close="handleClose">
      <div class="dialogContent">
        <div class="contentLeft">
          <div>
            <div class="moreAnswer">{{ moreData.answer }}</div>
            <graphECharts :graphData="moreData.graph"></graphECharts>
          </div>
        </div>
        <div class="contentRight">
          <div>
            <div class="source">
              <el-link :href="`${fileInfo.url}`" style="color: #209cc1" :underline="false" target="_blank">
                <el-tooltip class="item" effect="dark" content="点击可下载" placement="top">
                  <span> 来源：《{{ moreData.file_name }}{{ moreData.fileName }}》</span>
                </el-tooltip>
              </el-link>
            </div>
            <div class="fileContent">
              <div v-if="fileInfo.fileSuffix == '.docx' || fileInfo.fileSuffix == '.doc'">
                <VueOfficeDocx style="width: 100%; height: calc(100vh - 400px)" :src="fileInfo.url" />
              </div>
              <div v-if="fileInfo.fileSuffix == '.pdf'">
                <VueOfficePdf style="width: 100%; height: calc(100vh - 400px)" :src="fileInfo.url" />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span> -->
    </el-dialog>
  </div>
</template>

<script>
import store from '@/store'
import { handlerAsk, getQAHistoryList, getQAHistoryDetail } from '@/api/als/intelligentQA'
import graphECharts from '@/views/als/components/Charts/graph.vue'
import axios from 'axios'
import { getListByIdsApi } from '@/api/als/oss'
//引入VueOfficeDocx组件
import VueOfficeDocx from '@vue-office/docx'
import VueOfficePdf from '@vue-office/pdf'
import '@vue-office/docx/lib/index.css'

export default {
  name: 'IntelligentQA',
  components: { graphECharts, VueOfficeDocx, VueOfficePdf },
  data() {
    return {
      dialogVisible: false,
      chatInfo: [],
      questionInput: '', //202310150010
      currentHeight: 'auto',
      lastScrollHeight: 0,
      isScrollable: false,
      moreData: {
        user_id: '',
        answer: '',
        file_name: '',
        ossID: '',
        graph: {}
      },
      historyData: [],
      fileInfo: {}
    }
  },
  mounted() {
    this.getHistory()
    this.adjustHeight()
  },
  watch: {},
  created() {},
  methods: {
    adjustHeight() {
      const textarea = this.$el.querySelector('textarea')
      this.currentHeight = 'auto'
      if (textarea.scrollHeight < this.lastScrollHeight) {
        this.lastScrollHeight = this.lastScrollHeight - 16
      }
      this.$nextTick(() => {
        this.currentHeight = Math.min(this.lastScrollHeight, 200)
        this.lastScrollHeight = textarea.scrollHeight
        if (textarea.scrollHeight >= 200) {
          this.isScrollable = true
        } else {
          this.isScrollable = false
        }
      })
    },

    async getHistory() {
      try {
        const {
          data: { list, total }
        } = await getQAHistoryList()
        this.historyData = list
        // console.log('this.historyData', this.historyData)
      } catch (error) {}
    },

    handleKeydown(event) {
      if (event.key === 'Enter') {
        if (event.ctrlKey) {
          // 按下了 Ctrl+Enter，则插入换行符
          this.questionInput += '\n'
          this.adjustHeight()
        } else {
          // 只是按下了 Enter，阻止默认行为并发送消息
          event.preventDefault()
          this.sendQuestion()
        }
      }
      if (event.key === 'Backspace') {
        if (this.questionInput) {
          this.adjustHeight()
        } else {
          this.currentHeight = '50'
        }
      }
    },

    async sendQuestion() {
      const sendInput = {
        question: this.questionInput,
        userId: String(store.state.user.userInfo.user.userId)
      }

      try {
        if (this.questionInput.trim() === '') {
          return
        }
        this.chatInfo.push(sendInput, {
          answer: '正在解析您的问题，请稍后......'
        })
        this.questionInput = ''
        // const { code, data } = await handlerAsk(sendInput)
        const { code, data } = {
          code: 200,
          msg: '',
          data: {
            user_id: 'user',
            answer: '解决办法为：更换电池或遥控器',
            file_name: '排故手册',
            // ossID: '225825878820585472',//pdf
            ossID: '225840762526433280', //word
            graph: {
              data: [
                { name: '202310150010', category: 'HMC' },
                { name: '电视', category: '成品' },
                { name: '电视遥控器失灵', category: '故障描述' },
                { name: '家用电器', category: '系统' },
                { name: '更换电池或遥控器', category: '维修策略' }
              ],
              links: [
                { source: '202310150010', target: '电视', value: '成品' },
                { source: '202310150010', target: '电视遥控器失灵', value: '故障描述' },
                { source: '202310150010', target: '家用电器', value: '系统' },
                { source: '202310150010', target: '更换电池或遥控器', value: '维修策略' }
              ]
            }
          }
        }

        if (code == 200) {
          // const newData = this.handleData(JSON.parse(data))
          const newData = this.handleData(data)
          this.chatInfo.pop()
          this.chatInfo.push(newData)
        }
        // 等处理过返回数据后，调用使视图保持在最底部
        let main = this.$refs.main
        setTimeout(() => {
          main.scrollTop = main.scrollHeight
        }, 0)
      } catch (error) {}
    },

    handleData(data) {
      // const graphData = eval('(' + data.graph + ')')
      // data.graph = graphData
      const categories = []
      data.graph.data.forEach((node) => {
        const flag = categories.find((item) => {
          return item.name === node.category
        })
        if (!flag) {
          categories.push({ name: node.category })
        }
      })
      data.graph.categories = categories
      return data
    },

    handleMore(data) {
      this.getListById(data.ossID)
      this.moreData = data
      this.dialogVisible = true
    },

    async getListById(id) {
      const { data } = await getListByIdsApi(id)
      this.fileInfo = data[0]
    },

    handleClose() {
      this.dialogVisible = false
    },

    async historyDetail(id) {
      try {
        const { data } = await getQAHistoryDetail(id)
        const newData = this.handleData(data)
        this.chatInfo = []
        this.chatInfo.push(newData)
      } catch (error) {}
    }

    // const { code, data } = {
    //   code: 200,
    //   msg: '',
    //   data: {
    //     user_id: 'user',
    //     answer: '解决办法为：更换电池或遥控器',
    //     file_name: '排故手册',
    //     ossID: 2,
    //     graph: {
    //       data: [
    //         { name: '202310150010', category: 'HMC' },
    //         { name: '电视', category: '成品' },
    //         { name: '电视遥控器失灵', category: '故障描述' },
    //         { name: '家用电器', category: '系统' },
    //         { name: '更换电池或遥控器', category: '维修策略' }
    //       ],
    //       links: [
    //         { source: '202310150010', target: '电视', value: '成品' },
    //         { source: '202310150010', target: '电视遥控器失灵', value: '故障描述' },
    //         { source: '202310150010', target: '家用电器', value: '系统' },
    //         { source: '202310150010', target: '更换电池或遥控器', value: '维修策略' }
    //       ]
    //     }
    //   }
    // }
  }
}
</script>

<style lang="scss">
@import './index.scss';
</style>
