<template>
  
  <div style="background: white; height: 100%" >
    <el-container>
      <el-aside width="300px">
        <filter_search ref="filter_search" @customTab="handleCustomFields" :numberQuery="condition.NO" :searchOption="condition.searchCondition" :customFields="customFields" :projectId="condition.otherCondition?condition.otherCondition.projectId:undefined"></filter_search>
      </el-aside>
      <el-container>
        <el-header style="height:auto !important;padding:0 !important;">
          <div style="width:100%">
            <!-- <div class="display_flex" style="margin-top: 0px;">
              <search :field="field" :searchResult="true" :searchValue="false" :countryList="queryParams.countryList"
                @search="search"></search>
              <div class="display_flex" style="width:calc(100% - 550px);">
                <myTooltip :content="condition.showCondition" effect="light">
                  <div class="noWrap margin-right_10" style="max-width:calc(100% - 50px)">
                    <span v-if="condition.showCondition">检索式：</span>{{condition.showCondition}}
                  </div>
                </myTooltip>
                <div>
                  <el-dropdown trigger="click">
                    <span class="el-dropdown-link">
                        <i class="el-icon-more"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native.prevent="editSearchCondition">
                            编辑
                        </el-dropdown-item>
                        <el-dropdown-item @click.native.prevent="searchFinish">
                            检索
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
                </div>
              </div>
            </div> -->
            <div class="display_flex filterCondition">
              <el-form :inline="true">
                <el-form-item label="检索范围:">
                  <el-select size="small" v-model="condition.DBType" @change="changeDBType" style="width:100%"  placeholder="请选择">
                    <template v-if="condition.DBType == 'inner_WD' || condition.DBType == 'inner_CN'">
                      <el-option label="中国专利检索（内）" value="inner_CN"></el-option>
                      <el-option label="全球专利检索（内）" value="inner_DB"></el-option>
                    </template>
                    <template v-else>
                      <el-option label="中国专利检索" value="CN"></el-option>
                      <el-option label="世界专利检索" value="DB"></el-option>
                    </template>
                  </el-select>
                </el-form-item>
                <el-form-item label="数据库:" v-if="condition.DBType == 'inner_WD' || condition.DBType == 'inner_CN'">
                  <el-select size="small" v-model.number="condition.otherCondition.projectId" @change="changeProject" style="width:100%" filterable remote clearable placeholder="请选择" v-SelectLazyLoading="lazyLoading" :remote-method="remoteMethod" @focus="remoteMethod('')">
                      <el-option
                          v-for="item in projectQuery.data"
                          :key="item.id"
                          :label="item.name"
                          :value="parseInt(item.id)"
                      >
                      </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
            <div class="display_flex filterCondition">
              <div class="label">检索条件：</div>
              <myTextarea size='small' style="width:100%;" v-model="condition.searchCondition"></myTextarea>
              <el-button type="primary" size="small" class="margin-left_10" @click="inputSearch()">检索</el-button>
              <el-button type="primary" size="small" @click="filterSearch">过滤</el-button>
            </div>
            <div v-if="filterConditions.length>0" class="display_flex filterCondition">
              <div class="label">筛选条件：</div>
              <div class="content">
                <span class="margin-right_10" v-for="(item,index) in filterConditions" :key="index">
                  <span v-if="index>0"> AND </span>
                  <span style="font-weight:bold">{{ item.field.show }}<i class="el-icon-close" @click="delFilterCondition({type:2,index:index})" style="cursor: pointer;"></i>：</span>
                  <span>
                    <span v-for="(tag,ind) in item.value" :key="'tag'+ind">
                      <span v-if="ind>0"> OR </span>
                      <el-tag
                        closable
                        size="small"
                        :disable-transitions="false"
                        @close="delFilterCondition({type:1,data:item.value,index:ind,parentIndex:index})">
                        {{tag.show}}
                      </el-tag>
                    </span>
                  </span>
                  
                </span>
              </div>
            </div>
            <menuInRow>
              <menu-in-row-item v-for="item in viewList" :key="item.value" :name="item.value" @click="handleChangeView(item)">
                <div>
                  <svg-icon :icon-class="item.svg"></svg-icon>
                  <span class="margin-left_5" :style="viewSelected === item.value ?'color:red':''">{{item.title}}</span>
                </div>
              </menu-in-row-item>
              <menu-in-row-item>
                <div>|</div>
              </menu-in-row-item>
              <menu-in-row-item name="handleAnalyses" @click="handleAnalyses">
                <div>
                  <svg-icon icon-class="图表分析"></svg-icon>
                  <span class="margin-left_5">图表分析</span>
                </div>
              </menu-in-row-item>
              <menu-in-row-item name="highlight">
                <div>
                  <el-popover placement="bottom" title="关键词高亮" width="320" trigger="click">
                    <patent-keywords-highlight :project-id="projectId" />
                    <div slot="reference" >
                      <svg-icon icon-class="wodegaoliang"></svg-icon>
                      <span class="margin-left_5">高亮</span>
                      <i class="el-icon-arrow-down el-icon--right"></i>
                    </div>
                  </el-popover>
                </div>
              </menu-in-row-item>
              <menu-in-row-item name="fieldManage" @click="handleFieldManage">
                <div>
                  <svg-icon icon-class="lanweiguanli"></svg-icon>
                  <span class="margin-left_5">显示栏位管理</span>
                </div>
              </menu-in-row-item>
                <menu-in-row-item v-if="condition.reportType==1||condition.reportType == 2||condition.reportType == 3" name="saveCondition" @click="saveSearchCondition">
                  <div>
                    <svg-icon icon-class="保存检索式"></svg-icon>
                    <span class="margin-left_5">保存检索式</span>
                  </div>
                </menu-in-row-item>
              
              <menu-in-row-item>
                <div>|</div>
              </menu-in-row-item>
              <menu-in-row-item name="exportPatent" @click.native="handleExport(selectedTotal>0?true:false)">
                <div>
                  <svg-icon icon-class="daochu"></svg-icon>
                  <span class="margin-left_5">专利导出</span>
                  <!-- <el-dropdown trigger="hover" placement="bottom-start">
                    <div>
                      <svg-icon icon-class="daochu"></svg-icon>
                      <span class="margin-left_5">专利导出</span>
                      <i class="el-icon-arrow-right el-icon--right"></i>
                    </div>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item @click.native="handleExport(false)">当前全部</el-dropdown-item>
                      <el-dropdown-item @click.native="handleExport(true)">当前所选</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown> -->
                </div>
              </menu-in-row-item>
              <menu-in-row-item name="exportPDF" @click.native="exportPDF(selectedTotal>0?true:false)">
                <div>
                  <svg-icon icon-class="daochu"></svg-icon>
                  <span class="margin-left_5">PDF首页导出</span>
                  <!-- <el-dropdown trigger="hover" placement="left-start">
                    <div>
                      <svg-icon icon-class="daochu"></svg-icon>
                      <span class="margin-left_5">PDF首页导出</span>
                      <i class="el-icon-arrow-right el-icon--right"></i>
                    </div>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item @click.native="exportPDF(false)">当前全部</el-dropdown-item>
                      <el-dropdown-item @click.native="exportPDF(true)">当前所选</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown> -->
                </div>
              </menu-in-row-item>
              <menu-in-row-item name="importPatent" @click="importToProject">
                <div>
                  <svg-icon icon-class="daoru"></svg-icon>
                  <span class="margin-left_5">导入到项目</span>
                </div>
              </menu-in-row-item>
              
            </menuInRow>
          </div>
          
        </el-header>
        <el-main v-loading="loading" style="padding: 0 !important;">
          <div class="patent-list-container">
            <div class="height_100"> 
              <component ref="patentViewList" :is="viewSelected" :semanteme="semanteme" :outside="outside" :retrieveRecordId="retrieveRecordId"  :noveltySearch="noveltySearch" :column="columnList" :tableData="tableData"  @clickPatentNo="handleClick" :canSort="condition.component != 'patentNoSearch'?true:false"
                @select-change="handleSelect" :selected.sync="queryParams.selected" :queryParams="queryParams" :patentNoList.sync="patentNoList" :refresh='true'
                :view-field="patentViewField" @on-sort="handleSort" @addSelect="getChoosePatentNo" :projectId="projectId" :contrastFileList="saveRemarkList" @saveRemark="saveRemark" :conditionObj="conditionObj"></component>
            </div>
          </div>
          
        </el-main>
        <el-footer class="workspace-content-patent-page foot-total">
          <div>
            <span v-if="selectedTotal > 0">
              已勾选 <b>{{ selectedTotal }}</b> 条
            </span>
            <el-popover placement="bottom" title="" width="220" trigger="click">
              <el-main class="patent-fast-edit-popover" v-loading="selectNumberLoading">
                <div class="btn" @click="handleCancelSelectNumber">取消选择</div>
                <div class="btn" @click="handleSelectNumber(0)">本页选择</div>
              </el-main>
              <el-button type="info" size="small" class="margin-left_10" slot="reference"> 选择专利<i
                  class="el-icon-arrow-down el-icon--right"></i></el-button>
            </el-popover>
          </div>
          <div class="foot-total">
            <span class="total">共{{ total }}条</span>
            <el-pagination background layout="total, sizes, prev, pager, next, jumper"
              :current-page.sync="queryParams.current" :page-size.sync="queryParams.size" :page-sizes="pageSizes"
              :page-count="getPageCount()" @current-change="handleCurrentChange" @size-change="changeSize">
            </el-pagination>
          </div>
        </el-footer>
      </el-container>
    </el-container>


    <field ref="field" type="patent" :projectId="0" @getFieldList="getFieldList"></field>
    <!-- <projectListDialog ref="projectListDialog" :importData="searchData"></projectListDialog> -->
    <projectListDialog ref="projectListDialog" :importData="condition"></projectListDialog>

    <addAndEditSearchRecords ref="addAndEditSearchRecords" :projectId="condition.importToId"></addAndEditSearchRecords>
    <inventionPointDialog v-if="noveltySearch" :projectId="projectId" :retrieveRecordId="retrieveRecordId"  :contrastFileList="saveRemarkList" @updateInventionPoint="getPatentSimilarMess"></inventionPointDialog>
    <reportTemplateDialog ref="reportTemplateDialog"></reportTemplateDialog>
    <!-- 过滤 -->
    <filterDialog ref="filterDialog" :DBType="condition.DBType" @search="search"></filterDialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import moment from 'moment';
import PatentTableListView from "@/views/project/patentCollection/components/views/Table.vue";
import PatentAbstractListView from "@/views/project/patentCollection/components/views/Abstract";
import PatentPictureListView from "@/views/project/patentCollection/components/views/Picture";
import field from '@/views/components/dialog/fields.vue';
import projectListDialog from "../components/projectListDialog.vue";
import search from '@/utils/model/search/search.vue'
import addAndEditSearchRecords from '@/views/report/analysisAndOpinion/components/searchRecords/dialog/addAndEditSearchRecords.vue';
import reportTemplateDialog from '@/views/noveltySearch/components/dialog/reportTemplate/reportTemplateDialog.vue';


import filter_search from './filter_search.vue';

import PatentKeywordsHighlight from '@/views/project/components/PatentKeywordsHighlight.vue'
import indexMixins from './indexMixins'

import filterDialog from './filterDialog.vue';
export default {
  components: {
    PatentTableListView,
    PatentAbstractListView,
    PatentPictureListView,
    field,
    projectListDialog,
    search,
    addAndEditSearchRecords,
    reportTemplateDialog,
    filter_search,
    PatentKeywordsHighlight,
    filterDialog
  },
  mixins:[indexMixins],
  props: {
    searchData: {},
    noveltySearch:{},
    retrieveRecordId:{},
    projectId:{},
    outside:{
      type:Boolean,
      default:true
    },
    innerProjectId:{},
    semanteme:''
  },
  data() {
    return {
      columnList: [],
      pageSizes: [10, 20, 30, 40, 50],
      viewSelected: "patent-abstract-list-view",
      viewList: [
        {
          value: "patent-table-list-view",
          title: "表格视图",
          btn: "el-icon-tickets",
          svg:'liebiao'
        },
        {
          value: "patent-abstract-list-view",
          title: "摘要视图",
          btn: "el-icon-news",
          svg:'tuwenliebiao'
        },
        {
          value: "patent-picture-list-view",
          title: "图片视图",
          btn: "el-icon-picture-outline",
          svg:'tupian'
        },
      ],
      patentNoList: [],
      queryParams: {
        selected: [],
        current: 1,
        size: 10,
        isAdd: [],
        isDelete: [],
        OrderBy: "AD",
        OrderByType: "DESC",
        retrieveRecordId: this.retrieveRecordId,
        asCompare: this.asCompare
      },
      patentViewField: [],
      tableData: [],
      total: 0,
      selectNumberLoading: false,
      loading: false,
      selectedTotal: 0,
      startNumber: 1,
      endNumber: 0,
      quickSelect: false,
      quickSelectArr: [],
      /**检索式 */
      // 公用数据
      field: [],
      // 检索式及其他信息
      condition: this.searchData,
      filterConditions:[],
      conditionObj:{},
      saveRemarkList:[],
      customFields:[],
    };
  },
  watch: {
    retrieveRecordId(){
      this.queryParams.retrieveRecordId = this.retrieveRecordId
    },
    noveltySearch(val){
      if(val){
        this.queryComparePatent()
      }
    }
  },
  computed: {
    userinfo(){
      return this.$s.getObj('userinfo')
    },
  },
  created() { },
  async mounted() {
    this.initProjectSelect()
    this.$set(this.condition,'originalCondition',this.condition.searchCondition)
    this.getField()
    this.columnList = await this.$commonJS.getCustomField('patent',{ projectId: 0, taskId: null })
    if(this.noveltySearch){
      this.queryComparePatent()
    }
    //解析检索式
    this.analyzingCondition()
    //获取专利清单
    await this.getList();
    

  },
  methods: {
    getField(){
      var params = this.$s.getSession('conditionImport')
      var DBType = 'CN'
      if(params && params.data && params.data.DBType){
        DBType = params.data.DBType
      }
      var data = JSON.parse(JSON.stringify(this.$constants.searchField))
      var fields = []
      for(var i = 0;i<data.length;i++){
        var item = data[i]
        if(item.DBType.indexOf(DBType)==-1 || item.value == 'project'){
          continue
        }
        var children = item.children.filter(child=>{
          return child.value!='GJ' && child.DBType.indexOf(DBType)!=-1
        })
        if(DBType != 'CN' && DBType != 'WD'){
          if(item.otherField && item.otherField.length>0){
            children.push(...item.otherField)
          }
        }
        if(children && children.length>0){
          fields.push(
            {
              ...item,
              children:children
            }
          )
        }
      }
      this.field = fields
    },
    //解析检索式
    analyzingCondition(sign){
      var conditionObj = {}
      if(this.condition && this.condition.searchCondition){
        conditionObj = this.$commonJS.extractFieldsAndValues(this.condition.searchCondition) || {}
      }
      if(this.filterConditions && this.filterConditions.length){
        this.filterConditions.forEach((item,index)=>{
          if(!conditionObj[item.field.search]){
            conditionObj[item.field.search] = []
          }
          conditionObj[item.field.search].push(...item.value.map(value=>`"${value.search}"`))
        })
      }
      if(sign){
        return conditionObj
      }
      this.conditionObj = conditionObj
    },
    //查询对比文件
    queryComparePatent(){
      var params = {
        projectId:this.projectId
      }
      this.$api.queryComparePatent(params).then(response=>{
        if(response.code == 200){
          this.saveRemarkList = response.data.data
        }
      })
    },
    reporting(){
      this.$refs.reportTemplateDialog.open(this.projectId)
    },
    saveRemark(data){
      if(this.noveltySearch){
        this.queryComparePatent()
      }
    },
    //保存检索式
    saveSearchCondition(){
      var form = {
        searchCondition:this.getConditionStr(),
        searchBase:'小世系统',
        allNum:this.total,
        searchPerson:this.userinfo.name,
        searchTime:moment().format("YYYY-MM-DD")
      }
      this.$refs.addAndEditSearchRecords.open(form)
    },
    handleClick(row, location) {
      var params = {
        ...this.searchData,
        ...this.queryParams,
      }
      var search = {
        searchOption: params,
        location: location,
      }
      if(!this.outside){
        search.searchOption = {
          searchQuery: this.getConditionStr() || '',
          moreConditions:true
        }
        if(this.queryParams.OrderBy && this.queryParams.OrderByType){
          var orderDTOList = [
            {
              orderBy:this.queryParams.OrderBy,
              orderType:this.queryParams.OrderByType == 'DESC'?1:0
            }
          ]
          search.searchOption.orderDTOList = orderDTOList
        }
      }
      this.$s.setSession('search', search)
      this.$s.setSession('import',this.searchData)
      this.$router.push(
        {
          path: '/patentDetails/' + row.patentNo,
          query: {
            outside:this.outside,
            noveltySearch:this.noveltySearch,
            projectId:this.projectId,
            innerProjectId:this.innerProjectId || (this.condition.otherCondition?this.condition.otherCondition.projectId:0),
            retrieveRecordId:this.queryParams.retrieveRecordId
          }
        }
      )
    },
    // 统计组件传的值
    handleCustomFields(val) {
      this.filterConditions.push(...val)
      // var str = this.getConditionStrByCount(val)
      // this.condition.searchCondition = `${this.condition.searchCondition} AND ${str}`
      this.searchBth()
      this.refreshCount()
    },
    //统计格式的条件转检索式
    getConditionStrByCount(val){
      var str = ''
      val.forEach((item,index)=>{
        var value = ''
        if(item.op == '≡'){
          value = item.value.map(value=>`IET@ "${value.search}"`).join(" OR ")
        }else if(item.op == '='){
          value = item.value.map(value=>value.search).join(" OR ")
        }
        // str = str + `${item.field.search} ${item.op} (${value})`
        str = str + `${item.field.search} = (${value})`
        if(index > 0 && index < val.length){
          str = str + ' AND '
        }
      })
      return str
    },
    //删除筛选条件
    delFilterCondition(obj){
      const {type,index} = obj
      if(type == 1){
        var data = obj.data
        if(data.length == 1){
          var parentIndex = obj.parentIndex
          this.filterConditions.splice(parentIndex,1)
        }else{
          data.splice(index,1)
        }
      }else{
        this.filterConditions.splice(index,1)
      }
      // var str = this.getConditionStrByCount(this.filterConditions)
      // this.condition.searchCondition = `${this.condition.originalCondition}` + (str?` AND ${str}`:'')
      this.searchBth()
      this.refreshCount()
    },
    //刷新统计数据
    refreshCount(){
      if(this.condition.DBType!='CN' && this.condition.DBType!='WD'){
        this.$refs.filter_search.refreshOptions()
      }
    },
    //子组件返回检索式 
    async search(val) {
      if (val.searchStr == '') {
        this.$message.error('检索信息不能为空')
        return false
      }
      if (val.isRepeat) {
        // this.condition.searchCondition = `${this.condition.searchCondition} AND ${val.searchStr}`
        // this.condition.showCondition = `${this.condition.showCondition} AND ${val.searchStr}`
        this.getFilterCondition(val)
      } else {
        var searchStr = val.searchStr
        if(this.condition.DBType == 'inner_CN'){
          searchStr = searchStr + ' AND CO=CN'
        }
        this.condition.searchCondition = searchStr
        this.condition.showCondition = searchStr
        // this.condition.originalCondition = searchStr
        this.$set(this.condition,'originalCondition',searchStr)
        this.changeOriginalCondition(val)
      }
      this.refreshCount()
      this.searchBth()
      
    },
    //获取筛选条件（二次检索）
    getFilterCondition(val){
      var data = []
      if(val.data){
        val.data.forEach(item=>{
          var value = []
          if(typeof item.value == 'object'){
            for(var i = 0;i<item.value.length;i++){
              value.push(
                {
                  search: item.value[i],
                  show: item.show.value[i]
                }
              )
            }
          }else{
            value.push(
              {
                search: item.value,
                show: item.show.value || item.value
              }
            )
          }
          var obj = {
            field:{
              search: item.field,
              show: item.show.label
            },
            op: "=",
            value:value
          }
          data.push(obj)
        })
      }
      this.filterConditions.push(...data)
    },
    //修改原始检索条件
    changeOriginalCondition(val){
      if(val.data){
        var params = this.$s.getSession('conditionImport')
        if(!params || !params.data){
          return
        }
        params.data.otherCondition = null
        if(params.data.component != 'AdvancedSearch' && params.data.component != 'patentNoSearch'){
          if(val.isRepeat){
            if(params.data.data && params.data.data.length>0){
              params.data.data.push(val.data[0])
            }else{
              params.data.data=[val.data[0]]
            }
            var data = []
            params.data.data.forEach(item=>{
              if(item.dataType == 3){
                if(item.value && item.value.length>0){
                  data.push(item)
                }
              }else{
                if(item.value){
                  data.push(item)
                }
              }
            })
            params.data.data = data
          }else{
            params.data.data = val.data
          }
          params.data.component = 'customSearch'
          this.$s.setSession('conditionImport',params)
        }else if(params.data.component == 'AdvancedSearch' || params.data.component == 'patentNoSearch'){
          params.data.data = this.condition.searchCondition
          params.data.component = 'AdvancedSearch'
          this.$s.setSession('conditionImport',params)
        }
      }
    },
    //编辑检索式，跳转到检索界面
    editSearchCondition(){
      var params = this.$s.getSession('conditionImport')
      if(!params || !params.data){
        var data = {
          DBType:this.condition.DBType,
          component:'AdvancedSearch',
          data:this.condition.searchCondition
        }
        this.$s.setSession('conditionImport',{
          data:data,
        })
      }
      this.$router.push({
        path: '/conditionImport',
        query:{
          isEdit:true,
          importData:JSON.stringify(this.searchData),
          noveltySearch:this.noveltySearch,
          projectId:this.projectId,
          defaultSearchDB:params.data.defaultSearchDB?JSON.stringify(params.data.defaultSearchDB):undefined
        }
      })
    },
    searchBth() {
      if(this.outside){
        this.queryParams.retrieveRecordId = null
      }
      this.queryParams.current = 1
      //解析检索式
      this.analyzingCondition()
      this.getList()
      if(this.outside){
        this.reLoadQuery()
      }
      
    },

    // 编辑、查看检索式
    async searchFinish() {
      this.filterConditions = []
      this.condition.searchCondition = this.condition.originalCondition
      this.refreshCount()
      await this.searchBth()
    },
    //导入到专题库
    importToProject() {
      if(this.outside){
        var form = {
          // ...this.searchData,
          ...this.condition,
          orderBy: this.queryParams.OrderBy,
          orderByType: this.queryParams.OrderByType,
          // startNumber: this.selectedTotal > 0 ? this.startNumber : 1,
          // endNumber: this.selectedTotal > 0 ? this.endNumber : this.total,
          patentNos: this.queryParams.isAdd,
          // isDeletePatentNos: this.queryParams.isDelete,
        }
        this.$refs.projectListDialog.open(form);
        return
      }
      if(!this.projectId){
        return 
      }
      var params = {
        stringRequest:{
          projectId: this.innerProjectId || (this.condition.otherCondition?this.condition.otherCondition.projectId:''),
          searchQuery: this.getConditionStr() || '',
          orderDTOList:this.sort,
        },
        startNumber:1, //开始位置
        endNumber:(this.queryParams.isAdd && this.queryParams.isAdd.length>0)?0:this.total,//结束位置
        fromProjectId:this.innerProjectId, //来源专题库项目id
        toProjectId:this.projectId, //目标报告项目id
        isAdd:this.queryParams.isAdd, //去除专利号
      }
      if(this.queryParams.OrderBy && this.queryParams.OrderByType){
        var orderDTOList = [
          {
            orderBy:this.queryParams.OrderBy,
            orderType:this.queryParams.OrderByType == 'DESC'?1:0
          }
        ]
        params.stringRequest.orderDTOList = orderDTOList
      }
      var message = this.$message({
        type:'warning',
        message: '正在将专利导入报告中...',
        duration: 0 // 设置为0表示不自动关闭
      })

      this.$api.addProjectPatentToReport(params).then(res=>{
        if(res.code == 200){
          message.close()
          this.$message(
            {
              type:'success',
              message:'导入成功'
            }
          )
        }
      }).catch(error=>{
        message.close()
        this.$message(
            {
              type:'error',
              message:'导入失败'
            }
          )
      })
      
    },
    //切换页数
    async handleCurrentChange(val) {
      this.queryParams.current = val;
      this.patentNoList = []
      await this.getList();
      this.$nextTick(() => {
        if (this.quickSelect) {
          this.commonSwitch()
        } else {
          if (this.queryParams.isAdd.length > 0) {
            this.getHaveChoose([])
          }
        }
      })
    },
    //切换页大小
    async changeSize(val){
      this.queryParams.size = val
      this.queryParams.current = 1
      this.patentNoList = []
      await this.getList();
      this.$nextTick(() => {
        if (this.quickSelect) {
          this.commonSwitch()
        } else {
          if (this.queryParams.isAdd.length > 0) {
            this.getHaveChoose([])
          }
        }
      })
    },
    //获取最大页数
    getPageCount() {
      if(this.outside){
        var a = Math.ceil(Number(this.total) / Number(this.queryParams.size))
        return a > 200 ? 200 : a
      }else{
        return Math.ceil(Number(this.total) / Number(this.queryParams.size))
      }
      
    },
    //开始条数校验
    change1(val) {
      if (!isNaN(val)) {
        if (!val || val <= 0) {
          this.queryParams.startNumber = 1
        } else {
          if (this.queryParams.startNumber > this.total) {
            this.queryParams.startNumber = this.total
          }
        }
      } else {
        this.queryParams.startNumber = 1
      }
    },
    //结束条数校验
    change2(val) {
      if (!isNaN(val)) {
        if (!val || val <= 0) {
          this.queryParams.endNumber = this.total
        } else {
          if (this.queryParams.endNumber > this.total) {
            this.queryParams.endNumber = this.total
          }
        }
      } else {
        this.queryParams.endNumber = this.total
      }
    },

    //获取检索式字符串
    getConditionStr(){
      var searchQuery = this.getConditionStrByCount(this.filterConditions||[])
      if(this.condition.searchCondition){
        if(searchQuery){
          searchQuery = `${this.condition.searchCondition} AND ${searchQuery}`
        }else{
          searchQuery = `${this.condition.searchCondition}`
        }
      }
      return searchQuery
    },
    //查询内部数据库数据
    async getInnerProjectPatent(){
      var searchQuery = this.getConditionStr()
      
      let params = {
        current: this.queryParams.current, //页码（最多 200 页）
        size: this.queryParams.size, //每页返回条数（最多 50 条）
        projectId: this.innerProjectId,
        searchQuery: searchQuery,//检索条件
        semanteme:this.semanteme,
        //专利号检索
        numberQuery:this.condition.NO,
        redisKey:this.condition.redisKey,
      }
      if(this.condition.otherCondition && this.condition.otherCondition.projectId){
        params.projectId = this.condition.otherCondition.projectId
      }
      if(this.queryParams.OrderBy && this.queryParams.OrderByType){
        var orderDTOList = [
          {
            orderBy:this.queryParams.OrderBy,
            orderType:this.queryParams.OrderByType == 'DESC'?1:0
          }
        ]
        params.orderDTOList = orderDTOList
      }
      this.loading = true;
      this.$store.commit("SET_PATENT_RECORDS", []);
      await this.$api.QueryPatent(params).then((response) => {
        if (response.code == 200) {
          this.total = response.data.total;
          this.$set(this.queryParams, 'startNumber', this.endNumber > 0 ? this.startNumber : 1)
          this.$set(this.queryParams, 'endNumber', this.endNumber > 0 ? this.endNumber : this.total)
          let records = response.data.data
          if(params.semanteme){
            records.forEach(item=>{
              if(!item.score){
                item.score =  'error'
              }else{
                var score = (item.score * 100 + '').substring(0, 5)
                item.score =  Number(score)
              }
              
            })
          }
          this.tableData = records
          this.$store.commit("SET_PATENT_RECORDS", records);
          this.loading = false;
          if(response.data.redisKey && !this.condition.redisKey){
            this.condition.redisKey = response.data.redisKey
            this.condition.NO=''
            this.reLoadQuery()
          }
        }
      }).catch((error) => {
          this.loading = false;
        });
    },
    //查询专利
    async getList() {
      if(!this.outside){
        await this.getInnerProjectPatent()
        return
      }
      let queryParams = JSON.parse(JSON.stringify(this.queryParams));
      var params = {
        // CurrentQuery: this.searchData.searchCondition, //检索式
        // DBType: this.searchData.DBType, //”CN”或”WD”,表示检索中文库或世界库
        CurrentQuery: this.getConditionStr(), //检索式
        DBType: this.condition.DBType, //”CN”或”WD”,表示检索中文库或世界库
        PageNum: this.queryParams.current, //页码（最多 200 页）
        RowCount: this.queryParams.size, //每页返回条数（最多 50 条）
        OrderBy: this.queryParams.OrderBy, //排序字段：“AD”，“PD”，“GD”, “ID”（检索引擎自生成字段，排序顺序固定）
        OrderByType: this.queryParams.OrderByType, //排序方式：“ASC”，“DESC” 即正序倒序
        retrieveRecordId: this.queryParams.retrieveRecordId,

        //专利号检索
        numberQuery:this.condition.NO,
        redisKey:this.condition.redisKey,
      };
      if(!this.queryParams.retrieveRecordId){
        params.projectId = this.projectId
        var conditionImport = this.$s.getSession('conditionImport')
        params.searchSetting=conditionImport?JSON.stringify(conditionImport):''
      }
      // console.log(this.$s.getSession('retrieveRecordId'),)
      queryParams.params = params;
      this.$store.commit("SET_PATENT_PARAMS", queryParams);
      this.$store.commit("SET_PATENT_RECORDS", []);
      this.loading = true;
      this.$commonJS.scrollToTop()
      await this.$api.patentSelect(params).then((response) => {
        if (response.code == 200) {
          this.total = response.data.total;
          this.$set(this.queryParams, 'startNumber', this.endNumber > 0 ? this.startNumber : 1)
          this.$set(this.queryParams, 'endNumber', this.endNumber > 0 ? this.endNumber : this.total)
          let records = response.data.data
          this.tableData = records
          params.retrieveRecordId = response.data.retrieveRecordId
          if(!this.queryParams.retrieveRecordId && response.data.retrieveRecordId && !response.data.redisKey){
            this.queryParams.retrieveRecordId = response.data.retrieveRecordId
            this.reLoadQuery()
          }
          
          this.$store.commit("SET_PATENT_PARAMS", queryParams);
          this.$store.commit("SET_PATENT_RECORDS", records);
          this.getImageAndStatus()
          this.getPatentSimilarMess()
          this.loading = false;
          if(response.data.redisKey && !this.condition.redisKey){
            this.condition.redisKey = response.data.redisKey
            this.condition.NO=''
            this.reLoadQuery()
          }
        }
      })
        .catch((error) => {
          this.loading = false;
        });

    },
    //刷新网页参数
    reLoadQuery(){
      this.$router.replace({
        path: '/searchResult',
        query: {
          data: JSON.stringify(this.condition),
          noveltySearch:this.noveltySearch,
          projectId:this.projectId,
          retrieveRecordId:this.queryParams.retrieveRecordId,
          outside:this.outside,
          innerProjectId:this.innerProjectId,
          semanteme:this.semanteme
        }
      })
    },
    //获取摘要附图和法律状态
    getImageAndStatus(){
      this.tableData.forEach(item=>{
        var params = {
          appNo: item.rowApplicationNo,
        }
        // this.$api.getPictureGuid(params).then(response => {
        //   if (response.code == 200) {
        //     this.$set(item, 'pictureGuid', response.data)
        //   }
        // })
        this.$api.getLegalStatus(params).then(response => {
          if (response.code == 200) {
            this.$set(item, 'legalStatus', response.data)
          }
        })
      })
      
    },
    //获取专利相似度
    getPatentSimilarMess(){
      if(this.tableData.length == 0 || !this.noveltySearch){
        return
      }
      this.tableData.forEach(item=>{
        let params = {
          projectId:this.projectId,
          patentScoreDTOList:[]
        }
        var obj = {
          patentNo:item.patentNo,
          appNo:item.appNo,
          rowApplicationNo:item.rowApplicationNo,
          publicNo:item.publicNo,
          grantNo:item.grantNo
        }
        params.patentScoreDTOList.push(obj)
        this.$api.getPatentSimilarMess(params).then(response=>{
          if(response.code == 200){
            var data = response.data.patentScoreDTOList
            if(!data){
              this.$set(item, 'score', 'error')
              return
            }
            for(var i = 0;i<this.tableData.length;i++){
              var item1 = this.tableData[i]
              var index = data.findIndex(j=>{
                return j.patentNo == item1.patentNo
              })
              if(index!=-1){
                var score = (data[index].score * 100 + '').substring(0, 5)
                this.$set(item1, 'score', Number(score))
                data.splice(index,1)
              }else{
                this.$set(item1, 'score', 'error')
              }
            }
          }
        }).catch(error=>{
          this.$set(item, 'score', 'error')
        })
      })
      return
      var params = {
        projectId:this.projectId,
        patentScoreDTOList:[]
      }
      this.tableData.forEach(item=>{
        var obj = {
          patentNo:item.patentNo,
          appNo:item.appNo,
          rowApplicationNo:item.rowApplicationNo,
          publicNo:item.publicNo,
          grantNo:item.grantNo
        }
        params.patentScoreDTOList.push(obj)
      })
      this.$api.getPatentSimilarMess(params).then(response=>{
        if(response.code == 200){
          var data = response.data.patentScoreDTOList
          for(var i = 0;i<this.tableData.length;i++){
            var item = this.tableData[i]
            var index = data.findIndex(j=>{
              return j.patentNo == item.patentNo
            })
            if(index!=-1){
              this.$set(item, 'score', data[index].score.toFixed(4))
              data.splice(index,1)
            }
          }
        }
      })
    },
    handleSelect(data) {
      // this.queryParams.selected = data
    },
    async handleChangeView(item) {
      // console.log(item)
      if (this.viewSelected == item.value) {
        return false
      }
      if (this.viewSelected != "patent-picture-list-view" && item.value != "patent-picture-list-view") {
        this.queryParams.size = 10;
        this.viewSelected = item.value;
      } else if (this.viewSelected == "patent-picture-list-view" || item.value == "patent-picture-list-view") {
        if (item.value === "patent-picture-list-view") {
          this.$set(this.queryParams, "size", 20);
        } else {
          this.queryParams.size = 10;
        }
        this.viewSelected = item.value;
        this.getList();
      }
    },
    async handleFieldManage() {
      this.$refs.field.open(this.columnList)
    },
    //获取自定义栏位
    getFieldList(data) {
      this.columnList = []
        this.$nextTick(()=>{
            this.columnList = data
        })
    },
    //快速选择
    handleSelectNumber(type) {
      switch (type) {
        case 0: //本页选择
          this.patentNoList = [...new Set(this.patentNoList.concat(this.tableData.map((item) => item.patentNo))),];
          this.queryParams.isAdd = [...new Set(this.queryParams.isAdd.concat(this.tableData.map((item) => item.patentNo))),];
          break;
        case 1: //全部选择
          this.startNumber = 1;
          this.endNumber = this.total;
          this.$set(this.queryParams, 'startNumber', 1)
          this.$set(this.queryParams, 'endNumber', this.total)
        case 2: //范围选择
          this.queryParams.isDelete = [];
          this.queryParams.isAdd = [];
          this.patentNoList = [];
          this.quickSelect = true;
          if (type == 2) {
            if (!Number(this.queryParams.startNumber) || !Number(this.queryParams.endNumber)) {
              this.$set(this.queryParams, 'startNumber', this.endNumber > 0 ? this.startNumber : 1)
              this.$set(this.queryParams, 'endNumber', this.endNumber > 0 ? this.endNumber : this.total)
              break;
            }
            this.startNumber = this.queryParams.startNumber;
            this.endNumber = this.queryParams.endNumber;
          }
          this.commonSwitch();
          break;
      }
      this.getSelectedTotal()
    },
    //每页全部选择或范围选择的专利
    commonSwitch() {
      var arr = []
      if (this.queryParams.size * this.queryParams.current >= this.startNumber) {
        if (this.queryParams.size * this.queryParams.current >= this.endNumber) {
          if (this.queryParams.size * (this.queryParams.current - 1) + 1 <= this.startNumber) {
            var a = this.startNumber - (this.queryParams.size * (this.queryParams.current - 1) + 1);
            var b = this.endNumber - (this.queryParams.size * (this.queryParams.current - 1) + 1);
            for (var y = a; y <= b; y++) {
              arr.push(this.tableData[y].applicationNo)
            }
          } else {
            var a = this.queryParams.size * (this.queryParams.current - 1) + 1 - (this.queryParams.size * (this.queryParams.current - 1) + 1);
            var b = this.endNumber - (this.queryParams.size * (this.queryParams.current - 1) + 1);
            for (var y = a; y <= b; y++) {
              arr.push(this.tableData[y].applicationNo)
            }
          }
        } else {
          if (this.queryParams.size * (this.queryParams.current - 1) + 1 <= this.startNumber) {
            var a = this.startNumber - (this.queryParams.size * (this.queryParams.current - 1) + 1);
            var b = this.queryParams.size * this.queryParams.current - (this.queryParams.size * (this.queryParams.current - 1) + 1);
            for (var y = a; y <= b; y++) {
              arr.push(this.tableData[y].applicationNo)
            }
          } else {
            var a = this.queryParams.size * (this.queryParams.current - 1) + 1 - (this.queryParams.size * (this.queryParams.current - 1) + 1);
            var b = this.queryParams.size * this.queryParams.current - (this.queryParams.size * (this.queryParams.current - 1) + 1);
            for (var y = a; y <= b; y++) {
              arr.push(this.tableData[y].applicationNo)
            }
          }
        }
      }
      // this.patentNoList = JSON.parse(JSON.stringify(arr))
      this.quickSelectArr = JSON.parse(JSON.stringify(arr))
      this.getHaveChoose(arr)
    },
    //获取已选择的专利
    getHaveChoose(arr) {
      var arr1 = [...new Set(arr.concat(this.queryParams.isAdd))]
      this.patentNoList = arr1.filter((x) => this.queryParams.isDelete.indexOf(x) == -1)
    },
    //获取已选择的总条数
    getSelectedTotal() {
      this.selectedTotal = Number(this.endNumber) - Number(this.startNumber) + 1 + Number(this.queryParams.isAdd.length) - Number(this.queryParams.isDelete.length)
    },
    //获取手动选择的专利
    getChoosePatentNo(patentNo) {
      if (this.quickSelect) {
        var index = this.queryParams.isDelete.findIndex(item => {
          return item == patentNo
        })
        if (index == -1) {
          var index2 = this.quickSelectArr.findIndex(item => {
            return item == patentNo
          })
          if (index2 == -1) {
            this.setIsAdd(patentNo)
          } else {
            this.queryParams.isDelete.push(patentNo)
          }
        } else {
          this.queryParams.isDelete.splice(index, 1)
        }
      } else {
        this.setIsAdd(patentNo)
      }
      this.getSelectedTotal()
    },
    //是否加入isAdd里面
    setIsAdd(patentNo) {
      var index = this.queryParams.isAdd.findIndex(item => {
        return item == patentNo
      })
      if (index != -1) {
        this.queryParams.isAdd.splice(index, 1)
      } else {
        this.queryParams.isAdd.push(patentNo)
      }
    },
    //取消选择
    handleCancelSelectNumber() {
      this.patentNoList = [];
      this.queryParams.isAdd = []
      this.queryParams.isDelete = []
      this.startNumber = 1
      this.queryParams.startNumber = 1
      this.queryParams.endNumber = this.total
      this.endNumber = 0
      this.quickSelect = false
      this.selectedTotal = 0
      // this.getList()
    },
    //排序
    handleSort(data) {
      const o = {
        publicAccreditDate: "GD",
        publicDate: "PD",
        applicationDate: "AD",
      };
      var orderType = {
        ascending: "ASC",
        descending: "DESC"
      }
      this.queryParams.OrderBy = o[data.prop] || data.prop;
      this.queryParams.OrderByType = orderType[data.order];
      this.getList();
    },
  },
};
</script>
<style lang="scss" scoped>
.filterCondition{
  padding: 10px 20px;
  .label{
    min-width: 80px;
  }
  .content{
    width:100%;
    font-size: 14px;
    padding: 10px;
    border: 1px solid var(--bg);
    border-radius: 8px;
  }
}
.display_flex{
  display: flex;
  align-items: center;
}
.footer2{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.total {
  margin-right: 10px;
  font-weight: 400;
  color: #606266;
  display: inline-block;
  font-size: 13px;
  min-width: 35.5px;
  height: 28px;
  line-height: 28px;
  vertical-align: top;
  box-sizing: border-box;
}

.foot-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.patent-fast-edit-popover {
  padding: 0 !important;

  .btn {
    color: #000;
    line-height: 30px;
    border-radius: 5px;
    padding-left: 10px;
    text-align: left;
    font-size: 14px;
    cursor: pointer;

    &:hover {
      background: #adadad;
      color: #fff;
    }
  }

  .disabled {
    cursor: not-allowed !important;
  }

  .bottom {
    text-align: right;
    color: #1e9fff;
    line-height: 40px;
    padding-left: 10px;
    font-size: 18px;
  }

  .el-divider--horizontal {
    margin: 10px 0 !important;
  }

  .select-number {
    .el-input {
      width: 70px;
    }

    span {
      padding: 0 3px;
    }
  }
}
</style>
