// 检索 邓岚
<template>
  <div class="retrievalListBox">
    <up-down-layout :headerVisible="headerVisible" :header="$t('retrievalIndex.head')" :handleFlag.sync="handleFlag">
    <template slot="table">
      <div class="retrievalContent">
        <div class="leftBox">
          <div class="searchBox">
             <span>{{$t('reviewMaterialIndex.keyWord')}}</span>
             <div class="searchInput">
               <yf-es-search class="yfesSearch-sub"
                             style="align-items: center"
                             @callbackFunc="updata"
                             v-bind="yfEsSearchData"
                             :inputToolTip="inputToolTip"
                             :btnAttrs="btnAttrs"
                             ref="yfEsSearch"
                             :formatList="formatList"
                             :beforeLoad="beforeLoad"></yf-es-search>
             </div>
             <!-- 高级检索 -->
            <el-button type="primary"
                       size="medium"
                       icon="iconfont icongaojijiansuo"
                       @click="isAddShow()">{{$t('retrievalIndex.advancedSearch')}}</el-button>
          </div>
          <div class="contentBox" style="height: calc(100vh - 250px); overflow: auto">
            <!-- 无数据 -->
            <div v-if="!searchList.length > 0" class="noData">
              <div style="text-align: center;">
                <span class="iconfont iconzanwu"></span>
                <p style="color: #bbc2d1">暂无数据</p>
              </div>
            </div>
            <div v-else v-for="(item, index) in searchList" :key="index"  @click="fSeeDetail(item)">
              <h3 v-html="item.problemPoint"></h3>
              <ul>
                <li>
                  <span>{{$t('retrievalIndex.fileName')}}：</span>
                  <label v-html="item.fileName"></label>
                </li>
                <li>
                  <span>{{$t('retrievalIndex.solution')}}：</span>
                  <label v-html="item.solution"></label>
                </li>
                <li>
                  <span>{{$t('retrievalIndex.applicableProject')}}：</span>
                  <label v-html="item.applicableProjectName ? item.applicableProjectName : '/'"></label>
                </li>
                <li>
                  <span>{{$t('retrievalIndex.correspondingLaw')}}：</span>
                  <label v-html="item.correspondingLawFirmsName ? item.correspondingLawFirmsName : '/'"></label>
                </li>
                <li>
                  <span>{{$t('retrievalIndex.relatedSources')}}：</span>
                  <label v-html="item.relatedSources"></label>
                </li>
              </ul>
            </div>
          </div>
          <div class="pageBox">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="clickType === 'P' ? yfEsSearchData.pageConfig.pageIndex : gPageData.pageIndex"
              :page-sizes="[3, 5, 10, 15, 20]"
              :page-size="clickType === 'P' ? yfEsSearchData.pageConfig.pageSize : gPageData.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :prev-text="$t('retrievalIndex.prevText')"
              :next-text="$t('retrievalIndex.nextText')"
              :total="clickType === 'P' ? yfEsSearchData.pageConfig.totalCount : gPageData.totalCount">
            </el-pagination>
          </div>
        </div>
        <div class="rightBox">
          <!-- 热搜榜 -->
          <div>
            <h3 style="display: flex; align-items: center;">
              <svg class="font-icon" aria-hidden="true">
                <use xlink:href="#iconresou"></use>
              </svg>
              <!-- <span class="iconfont iconresou"></span> -->
              {{$t('retrievalIndex.hotSearch')}}
            </h3>
            <ul>
              <li v-for="(item, index) in hotSearch" :key="index">{{index+1}}.<span>{{item}}</span></li>
            </ul>
          </div>
          <!-- 历史搜索 -->
          <div>
            <h3><span class="iconfont iconlishi"></span>{{$t('retrievalIndex.historySearch')}}
              <el-button type="primary"
                         icon="iconfont iconshanchu1"
                         size="mini"
                         @click="fBatch('all')">
                {{$t('retrievalIndex.allReset')}}</el-button></h3>
            <ul>
              <li v-for="(item, index) in historySearch" :key="index">
                {{index+1}}.
                <span>{{item.searchContent}}</span>
                <auth-button size="mini"
                            :title="$t('common.del')"
                            @click="fBatch(item)"
                            icon="iconfont iconycjian"
                            class="iconCircle marginLeft pssc-css"></auth-button>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </template>
    </up-down-layout>
    <!-- 高级检索 -->
    <advanced-search ref="advancedForm" :visible.sync="dialogFormVisible" :parameter="gPageData" @advSearchData="advSearchData" :clickPosition="clickPosition"></advanced-search>
    <retrieval-content-index ref="retrievalContentIndex" :detailsData="detailsData" v-if="detailsData.dialogVisible"></retrieval-content-index>
  </div>
</template>

<script>
import { yfEsSearch, upDownLayout, authButton } from 'newepoch-components'
import retrievalApi from '@/api/assetaudit/knowledgeBase/retrievalApi'
import AssetauditApi from '@/api/assetaudit/assetauditApi'
import AdvancedSearch from '@/pages/assetaudit/cKnowledgeBase/advancedSearch'
import retrievalContentIndex from '@/pages/assetaudit/retrieval/retrievalContentIndex'
import * as format from '@/filters/index'
export default {
  components: { yfEsSearch, upDownLayout, AssetauditApi, AdvancedSearch, retrievalContentIndex, authButton },
  name: 'retrievalIndex',
  data () {
    return {
      inputToolTip: this.$t('common.keywordPrompt2'),
      btnAttrs: {
        size: 'medium'
      },
      dialogFormVisible: false,
      shouldBefore: false,
      yfEsSearchData: { // 查询参数
        // configUrl: 'http://es.cdyfsz.com',
        // module: 'ckb_knowledge_base',
        filterKeys: [{ name: 'field_group', modle: 'must' }],
        sortKeys: '',
        shouldBefore: true,
        pageConfig: {
          pageIndex: 1,
          pageSize: 3,
          totalCount: 0
        },
        autoSearch: false,
        placeholder: this.$t('retrievalIndex.inputKeyWord'),
        recommendModel: true,
        recommendKey: { name: 'field_group', modle: 'must' },
        recommendDefaultKey: [
          { name: 'voltooide_status', type: 'term', value: '0' },
          { name: 'data_status', type: 'term', value: '01' },
          { name: 'del_status', type: 'term', value: '0' }
        ],
        defauleKeys: [
          { name: 'voltooide_status', type: 'term', value: '0' },
          { name: 'data_status', type: 'term', value: '01' },
          { name: 'del_status', type: 'term', value: '0' }
        ]
      },
      headerVisible: false,
      handleFlag: false,
      searchList: [], // 列表数据
      hotSearch: [], // 热搜数据
      historySearch: [], // 历史搜索
      clickType: 'P', // 搜索 P 高级搜索 G
      gPageData: { // 高级搜索分页
        pageIndex: 1,
        pageSize: 3,
        totalCount: 0
      },
      clickPosition: 'btn', // 高级搜索按钮 btn 高级搜索分页 page
      form: {},
      editModel: '',
      isLoadByClick: false,
      detailsData: {
        dialogVisible: false,
        keyId: ''
      }
    }
  },
  created () {
    this.getTopsearch()
    this.getSearchhistory()
  },
  mounted () {
    this.envSetFun()
  },
  methods: {
    // 设置关键词环境变量
    envSetFun () {
      // this.yfEsSearchData.configUrl = process.env.VUE_APP_CONFIG_URL
      // this.yfEsSearchData.module = process.env.VUE_APP_KNOWLEDGE_BASE
      this.$set(this.yfEsSearchData, 'configUrl', process.env.VUE_APP_CONFIG_URL)
      this.$set(this.yfEsSearchData, 'module', process.env.VUE_APP_KNOWLEDGE_BASE)
    },
    // 下拉列表显示数据
    formatList (row) {
      return row.problemPoint
    },
    // 查询
    fAddRetrieval () {
      let searchVal = this.$refs.yfEsSearch.esValue.trim() // 去掉前后空格
      retrievalApi.addRetrieval.create({ searchContent: searchVal, clickKeyword: '', clickKnowledgeId: 0 }).then(res => {
        if (res.code && res.code === '0') {
          this.getTopsearch()
          this.getSearchhistory()
        }
      })
    },
    // 查询返回的值
    updata (data) {
      this.$LoadingClose()
      this.clickType = 'P'
      this.searchList = []
      this.yfEsSearchData.pageConfig.pageIndex = data.pageIndex
      this.yfEsSearchData.pageConfig.pageSize = data.pageSize
      this.yfEsSearchData.pageConfig.totalCount = data.total
      let s = this.$refs.yfEsSearch.esValue
      if (data.datas.length === 0) {
        // this.$message.warning(this.$t('common.zwsj'))
      } else {
        data.datas.forEach(item => {
          let relatedSourcesArr = item.relatedSources.split(',')
          item.fileName = this.setRed(s, item.fileName)
          item.problemPoint = this.setRed(s, item.problemPoint)
          item.solution = this.setRed(s, item.solution)
          item.applicableProject = this.setRed(s, item.applicableProject)
          item.correspondingLaw = this.setRed(s, item.correspondingLaw)
          item.relatedSources = this.setRed(s, relatedSourcesArr.map(val => format.formatDict(val, 'MATERIAL_SOURCE')).join(','))
        })
        this.searchList = data.datas
      }

      // 点查询 刷新热搜榜和历史搜索
      if (this.isLoadByClick) {
        // 更新右边
        this.fAddRetrieval()
        this.isLoadByClick = false
      }
    },
    // 第一次查询 数据加载
    beforeLoad (load) {
      // 这里设值一个参数来判断是点击触发的数据更新
      if (this.$refs.yfEsSearch.esValue === null) {
        this.$message.warning(this.$t('retrievalIndex.noSearch'))
      } else if (this.$refs.yfEsSearch.esValue.trim() === '') {
        this.$message.warning(this.$t('retrievalIndex.noSearch'))
      } else {
        this.isLoadByClick = true
        this.yfEsSearchData.pageConfig.pageIndex = 1
        this.$LoadingShow()
        load()
      }
    },
    // 分页 每页
    handleSizeChange (val) {
      if (this.clickType === 'P') {
        this.yfEsSearchData.pageConfig.pageSize = val
        this.$refs.yfEsSearch.loadData()
      } else if (this.clickType === 'G') {
        this.gPageData.pageSize = val
        this.clickPosition = 'page'
      }
    },
    // 分页 当前页
    handleCurrentChange (val) {
      if (this.clickType === 'P') {
        this.yfEsSearchData.pageConfig.pageIndex = val
        this.$refs.yfEsSearch.loadData()
      } else if (this.clickType === 'G') {
        this.gPageData.pageIndex = val
        this.clickPosition = 'page'
      }
    },
    // 热搜列表
    getTopsearch () {
      retrievalApi.topsearch.getList().then(res => {
        if (res.code && res.code === '0') {
          this.hotSearch = res.data
        }
      })
    },
    // 历史检索
    getSearchhistory () {
      retrievalApi.searchhistory.getList().then(res => {
        if (res.code && res.code === '0') {
          this.historySearch = res.data
        }
      })
    },
    // 删除历史检索
    fBatch (data) {
      let arr = []
      if (data !== 'all') {
        arr.push(data.keyId)
      }

      if (this.historySearch.length === 0) {
        this.$message.warning(this.$t('retrievalIndex.noDel'))
        return
      }

      retrievalApi.searchhistory.batchs({ keyIds: arr, allDelFlag: data === 'all' ? '1' : '0' }).then(res => {
        if (res.code && res.code === '0') {
          this.getSearchhistory()
          this.$message.success(this.$t('retrievalIndex.resetSuccess'))
        }
      })
    },
    // 高级检索 弹窗打开
    isAddShow () {
      // 清空查询的数据
      this.clickPosition = 'btn'
      this.dialogFormVisible = true
    },
    // 高级检索数据返回
    advSearchData (resData) {
      this.searchList = []
      this.clickType = 'G'
      this.$refs['yfEsSearch'].esValue = ''
      if (resData.code && resData.code === '0') {
        resData.data.datas.forEach(item => {
          let relatedSourcesArr = item.relatedSources.split(',')
          item.relatedSources = relatedSourcesArr.map(val => format.formatDict(val, 'MATERIAL_SOURCE')).join(',')
        })
        this.searchList = resData.data.datas
        if (this.searchList && this.searchList.length === 0) { // 高级检索为空时提示
          // this.warning(this.$t('common.zwsj'))
        }
        this.gPageData.pageIndex = resData.data.pageIndex
        this.gPageData.pageSize = resData.data.pageSize
        this.gPageData.totalCount = resData.data.totalRow
      }
    },
    // 查看详情
    async fSeeDetail (itemData) {
      let temp
      this.detailsData.dialogVisible = true
      this.detailsData.keyId = itemData.keyId.toString()
      retrievalApi.clickPlan.update(itemData.keyId)
      await retrievalApi.detail.get(this.detailsData.keyId).then(res => {
        if (res.code && res.code === '0') {
          temp = res
        }
      })
      await retrievalApi.addRetrieval.create({ // 传值查询
        // searchContent: itemData.fieldGroup,
        searchContent: '', // 修改-去掉搜索内容
        clickKeyword: temp.data.problemPoint,
        clickKnowledgeId: itemData.keyId
      }).then(res => {
        if (res.code && res.code === '0') {
          this.getTopsearch()
          this.getSearchhistory()
        }
      })
    },
    // 查询的展示值 搜索值标红
    setRed (word, str) {
      if (str !== null && str !== undefined && str !== '') {
        const keywords = Array.from(new Set(Array.from(word)))
        const html = Array.from(str).map(text => ({ text }))
        keywords.forEach(words => {
          html.forEach(item => {
            if (words === item.text) {
              item.text = `<font color=red>${item.text}</font>`
            }
          })
        })
        return html.map(item => item.text).join('')
      } else {
        return ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.retrievalListBox{
  .searchBox{
    padding-right: 8px;
  }
  /deep/ .es-search{
    padding-right: 10px;
  }
  /deep/ .es-search .el-button{
    margin-left: 10px;
  }
}
/deep/ .crm-footer{
  border: 0px !important;
  background:#f3f3f4
}
.searchBox{
  background-color:#ffffff;
  .el-button--medium{
    padding: 9px 20px !important;
  }
}
.rightBox{
  > div{
    background-color:#ffffff;
  }
}
.contentBox{
  background-color:#f3f3f4;
  border-radius: 4px;
  >div{
    padding: 10px 20px !important;
  }
}
// icon的css
.font-icon {
  margin-right: 3px;
  width: 19px;
  height: 19px;
  fill: currentColor;
  overflow: hidden;
}
.noData{
  background: #ffffff !important;
  height: calc(100vh - 270px);
  border: 0 !important;
  display: flex;
  justify-content: center;
  align-items: center;
  .iconfont{
    font-size: 50px;
    color: #d9dce3;
  }
}
</style>
