<template>
  <div class="search">
    <div id="home">
      <img alt="数据检索中心" src="../../assets/images/search/610.png"/>
      <router-link to="/">
        <a >返回后台</a>
      </router-link>

    </div>

    <div v-if="engines" id="site-main">
      <div id="search-bar">
        <div id="container">
          <div id="headline-content">
            <el-row class="headline-center" >
              <div id="search-tab">
              <span
                v-for="engine_name in engine_names"
                v-bind:key="engine_name"
                :class="{ active: get_search_engine() === engine_name }"
                @click="set_search_engine(engine_name)"
              >{{ engines[engine_name][3] }}</span
              >
              </div>
            </el-row>

            <form
              id="search-form"
              ref="search_form"
              onsubmit="return false;"
              style="height: 50px;"
              class="headline-center"
            >
              <input
                id="search-keyword"
                ref="search_input"
                v-model="keyword"
                :name="engines[search_engine][1]"
                :placeholder="engines[search_engine][2]"
                autocomplete="off"
                autofocus
                class="float-left"
                type="search"
                @blur="blur()"
                @focus="focus()"
                @input="get_hot_keyword()"
                @keydown.down="down()"
                @keydown.prevent.up="up()"
              />
              <input
                id="search-form-submit"
                class="float-right"
                type="submit"
                value="搜索"
                @click="doSearch"
              />
            </form>

              <a-spin v-show="search_engine == '图谱'" :spinning="loadingChecked" class="flex1 panel flex-col" style="height: 730px;">
                <chart-comp ref="chart"
                          @="getInfoTooltip"
                          :isShowContextMenu="true"
                          @reloadChart="reloadChart"
                          :nodes="nodes"
                          :links="links"
                          :enable="true"
                          :isShowChart="true"></chart-comp>
              </a-spin>
              <span v-show="search_engine == '文档'" :spinning="loadingChecked" class="flex1 panel flex-col" style="height: 730px;background-color: transparent;">
                <PdfList/>
              </span>
              <span v-show="search_engine == '图片'" :spinning="loadingChecked" class="flex1 panel flex-col" style="height: 730px;background-color: transparent;">
                <ImageList/>
              </span>
              <span v-show="search_engine == '媒体'" :spinning="loadingChecked" class="flex1 panel flex-col" style="height: 730px;background-color: transparent;">
                <VideoList/>
              </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import fetchJsonp from "fetch-jsonp";

import chartComp from '@/views/knowledge/common/chart'
import PdfList from '@/views/search/pdf'
import ImageList from '@/views/search/image'
import VideoList from '@/views/search/video'
import { getGraphEntClsTree } from '@/api/graph/statisticalMap'
import { getAllEntityClass } from '@/api/graph/entityClass'
import { getAllRelationClass } from '@/api/graph/relationClass'
const dataList = []
  // 根据树生成一个列表
  const generateList = (data) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i]
      const key = node.key
      dataList.push({key, title: node.entClsName, entClsName: node.entClsName})
      if (node.children) {
        generateList(node.children, node.key)
      }
    }
  }
export default {
  name: "Home",
  components: { chartComp, PdfList, ImageList, VideoList },
  data() {
    return {
      loadingChecked: false,
      nodes: null,
      links: null,
      relClsList: [], // 关系类列表
      allRelClsNameList: [],// 所有的关系类名列表
      checkedRelClsNameList: [], // 去重的关系类名列表
      search_engine: "图谱",
      engines: "",
      engine_names: "",
      keyword: "",
      keywords: [],
      key_selected: -1,
      search_hot_display: "display: none",
    };
  },
  created() {
    let engines = {
      list: ["文档", "图片", "媒体", "图谱"],
      文档: ["https://www.so.com/s", "q", "word pdf txt", "文档"],
      图片: ["https://www.baidu.com/s", "wd", "jpg png bmp", "图片"],
      媒体: ["https://www.google.com/search", "q", "mp3 mp4", "媒体"],
      图谱: ["https://www.sogou.com/web", "query", "知识图谱", "图谱"],
    };
    this.engines = engines;
    this.engine_names = engines["list"];
    this.refreshEntityClassList()
    /**
     * 请求数据，获取所有实体类的信息，然后根据pid组装出实体类之间的关系
     * */
    this.loadingChecked = true
    Promise.all([getAllEntityClass(true), getAllRelationClass()]).then((resp) => {
      let links = []
      resp[0].data.forEach((v) => {
        v.id = v.entClsID
        v.label = v.entClsName
        if (v.pid !== null) {
          let fromId = v.pid, toId = v.entClsID
          const item = {
            id: fromId + '_' + toId
          }
          item.from = v.pid
          item.to = v.entClsID
          item.classType = 'dashed'
          links.push(item)
        }
      })
      var relClassNameTempMap = {}
      resp[1].data.forEach((v) => {
        const item = {
          label: v.relClsName,
          value: v.relClsID,
          checked: true
        }
        v.from = v.startID
        v.to = v.endID
        v.id = v.relClsID
        v.label = v.relClsName
        this.relClsList.push(item)
        relClassNameTempMap[v.relClsName] = true
      })
      //去掉重复关系类名
      for (let name in relClassNameTempMap) {
        this.allRelClsNameList.push({
          label: name,
          value: name
        })
        this.checkedRelClsNameList.push(name)
      }
      links = links.concat(resp[1].data)
      this.allEntClassCache = resp[0]
      this.filLinks = this.allLinksCache = links

      // if (clsId) { // 路径中存在实体类id
      //   this.onCheckEntCls(this.checkedKeys)
      // } else {
        this.drawChart(resp[0].data, links)
      // }
      this.loadingChecked = false
    })
  },
  methods: {
    goHome(){
      this.$router.replace("index");
    },
    set_search_engine(engine) {
      this.search_engine = engine;
      this.keyword = ''
    },
    get_search_engine() {
      return this.search_engine;
    },
    get_hot_keyword() {
      if (this.keyword === "") {
        this.keywords = [];
        return;
      }
      // https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=golang&cb=xxxxx
      if (this.keyword !== "" && this.keyword !== "0") {
        clearTimeout(this.timer); // 清除定时器
        this.timer = setTimeout(() => {
          let api =
            "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=" + this.keyword;
          fetchJsonp(api, {
            jsonpCallback: "cb",
          })
            .then((response) => {
              return response.json();
            })
            .then((data) => {
              this.keywords = data.s; // 用到this一定要注意this指向
            })
            .catch((error) => {
              console.log(error);
            });
        }, 50);
      } else {
        this.keywords = [];
      }
    },
    go_submit(val) {
      this.keyword = val;
      this.$refs.search_input.value = val;
      this.$refs.search_form.submit();
    },
    getData(url) {
      fetchJsonp(url, {
        jsonpCallback: "callback",
      })
        .then((response) => {
          console.log(response);
          console.log(response.json());
          return response.json();
        })
        .then((json) => {
          this.users = json; // 在此处进行接收数据之后的操作
        })
        .catch((error) => {
          console.log(error); // 此处是数据请求失败后的处理
        });
    },
    down() {
      this.key_selected = (this.key_selected + 1) % this.keywords.length;
      this.keyword = this.keywords[this.key_selected];
      // this.$refs.search_input.value = this.keywords[this.key_selected];
    },
    up() {
      this.key_selected =
        (this.key_selected - 1 + this.keywords.length) % this.keywords.length;
      this.keyword = this.keywords[this.key_selected];
      // this.$refs.search_input.value = this.keywords[this.key_selected];
    },
    blur() {
      clearTimeout(this.timer); //清除延迟执行
      this.timer = setTimeout(() => {
        //设置延迟执行
        this.search_hot_display = "display: none";
        this.key_selected = -1;
      }, 100);
    },
    focus() {
      this.search_hot_display = "display: block";
      this.key_selected = -1;
      this.get_hot_keyword();
    },
    doSearch() {
    },
    getInfoTooltip(event, args) {
      const vm = this
      this.$set(this.tooltip, 'x', event.pageX + 'px')
      this.$set(this.tooltip, 'y', event.pageY + 'px')
      if (args.clickNode) {
        vm.tooltip.entClsID = args.clickNode.data.entClsID
        vm.tooltip.relClsID = false
      } else if (args.clickLink) {
        vm.tooltip.entClsID = false
        vm.tooltip.relClsID = args.clickLink.data.relClsID
        vm.relClsName = args.clickLink.data.relClsName
      } else {
        vm.tooltip.entClsID = false
        vm.tooltip.relClsID = false
      }
    },
    reloadChart(nodes, links) {
      this.drawChart(nodes, links)
    },
    drawChart(nodes, links) {
      this.nodes = nodes
      this.links = links
      this.$refs.chart.destroyChart() // 先清空chart实例，再绘图
      this.$refs.chart.reDraw(undefined, nodes, links)
    },
    refreshEntityClassList(clsId) {
      this.loadingTree = true
      getGraphEntClsTree().then((data) => {
        for (let i = 0; i < data.length; i++) {
          data[i]['key'] = data[i]['entClsID']
          data[i]['title'] = data[i]['entClsName']
          data[i]['scopedSlots'] = {title: 'custom'}
          if (!data[i]['pid']) {
            this.checkedKeys.push(data[i]['entClsID'])
          }
        }
        // 此处传固定的option
        const option = {
          idName: 'entClsID',
          pidName: 'pid',
          childName: 'children',
          returnList: []
        }
        let treeData = this.$utils.tree.listToTree(data, option) // 数组转成树
        if (clsId) {  // 如果路径中存在实体类id
          for (let z = 0; z < treeData.length; z++) {
            if (treeData[z]['entClsID'] === clsId) {
              this.checkedKeys = getIdsList(treeData[z])
            }
          }
        }
        this.gData = treeData
        generateList(treeData)  // 生成个列表
        const vm = this
        // 遍历树找到父节点下面的所有子节点
        this.$utils.tree.walk(treeData, function (node, index, way) {
          var id = clsId  // 路由中的id
          var myWay = []  // 需要找到的展开节点key
          if (node.key === id) {
            for (let i = 0; i < way.length; i++) {
              myWay.push(way[i]['key'])
            }
            vm.expandedKeys = myWay
            return false
          }
        })
        this.loadingTree = false
      })
    },
  }
};
</script>
<style lang="less" scoped>
@import "../../assets/styles/common";
@import "../../assets/styles/search";
.search {
  height: 100%;
  background-image: url("../../assets/search/backgrand.png");
  background-size:100% 100%;
  background-attachment:fixed;
}
</style>
