<template>
  <div class="height_100">
    <el-container>
      <!-- 统计 -->
      <el-aside class="height_100" :width="showLeft ? '300px' : '0px'" v-show="showLeft">
        <div class="height_100">
          <customFields ref="customFields" :projectId="projectId" :searchOption="searchStr" :customFields="customFields"
            @customTab="handleCustomFields" :searchPatentCheck="searchPatentCheck">
          </customFields>
        </div>
      </el-aside>
      <!-- 专利列表 -->
      <el-container>
        <el-header style="display:flex;justify-content:space-between">
          <div style="display:flex">
            <el-tooltip class="item" effect="dark" :content="(showLeft ? '隐藏' : '显示') + '左侧菜单'" placement="top">
              <i :class="showLeft ? 'el-icon-s-fold' : 'el-icon-s-unfold'"
                style="font-size: 25px;position: relative; top: 5px; color: #2f2f2f; cursor: pointer"
                @click="showLeft = !showLeft"></i>
            </el-tooltip>

            <searchPatent ref="searchPatent" :searchFiled="searchFiled" :searchPatentCheck="searchPatentCheck"
              @searchValue="handleSearchValue"></searchPatent>

            <!-- <mySearch :SearchFields="searchFiled" @search="search" :searchValue="searchOption"></mySearch> -->
            <el-popover placement="bottom" title="关键词高亮" width="320" trigger="click">
              <patent-keywords-highlight :project-id="projectId" />
              <el-button slot="reference" size="small" type="primary" class="margin-right_10 margin-left_10">
                高亮<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
            </el-popover>
          </div>
          <div>
            <el-button-group class="margin-left_10">
              <el-tooltip v-for="item in viewList" :key="item.value" class="item" effect="dark" :content="item.title"
                placement="top">
                <el-button @click="handleChangeView(item)" size="small"
                  :type="viewSelected === item.value ? 'primary' : ''">
                  <i :class="item.btn" style="font-size: 12px !important;"></i>
                </el-button>
              </el-tooltip>
            </el-button-group>
            <el-dropdown trigger="click" split-button type="primary" size="small">
              <span @click="handleFieldManage">显示栏位管理</span>
              <el-dropdown-menu slot="dropdown" class="text-align_center">
                <el-dropdown-item @click.native="handleFile">报告文档</el-dropdown-item>
                <!-- <el-dropdown-item @click.native="handleQuestion" v-if="$permission('/workspace/event')">事
                  件</el-dropdown-item> -->
                <el-dropdown-item @click.native="handleField" v-disabled="false">自定义栏位管理</el-dropdown-item>
                <el-dropdown-item @click.native="exportPDF">导出PDF首页</el-dropdown-item>
                <!-- <el-dropdown-item @click.native="handleBatch"
                  :disabled="!($permission('/workspace/folder/batchUploadSpecification') && $r(projectId, [1, 2]))">批量上传说明书</el-dropdown-item>
                <el-dropdown-item> -->
                <el-dropdown trigger="hover" placement="right-start">
                  <p>
                    导出专利<i class="el-icon-arrow-right el-icon--right"></i>
                  </p>
                  <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>
                <el-dropdown-item>
                  <el-dropdown trigger="hover" placement="right-start">
                    <p>
                      {{ familyObj[queryParams.groupField] }}<i class="el-icon-arrow-right el-icon--right"></i>
                    </p>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item v-for="(item, key) in familyObj" :key="key" @click.native="onChangeFamily(key)">{{
                        item }}</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-dropdown trigger="hover" placement="right-start">
                    <p>
                      合并<i class="el-icon-arrow-right el-icon--right"></i>
                    </p>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item @click.native="handleMerge(2)">发明人</el-dropdown-item>
                      <el-dropdown-item @click.native="handleMerge(0)">申请人/权利人</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-dropdown trigger="hover" placement="right-start">
                    <p>
                      创建报告<i class="el-icon-arrow-right el-icon--right"></i>
                    </p>
                    <el-dropdown-menu slot="dropdown" style="margin-top:0px">
                      <!-- 遍历按钮 -->
                      <el-dropdown-item @click.native="handleAnalysesFto">FTO调查</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-dropdown-item>
                <el-dropdown-item @click.native="handleAnalyses">图表分析</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>

        </el-header>
        <el-main v-loading="loading">
          <div class="height_100">
            <component ref="patentViewList" :is="viewSelected" @download="handleDownload" @change-read="handleChangeRead"
              :projectId="projectId" :patentNoList.sync="patentNoList" @addSelect="getChoosePatentNo"
              @clickPatentNo="handleClick" :column="customList" @index-setting="handleIndexSetting" @on-sort="handleSort"
              :queryParams="queryParams" :tableData="tableData" :refresh='refresh'></component>
          </div>
        </el-main>
        <el-footer class="pagination" style="display:flex;justify-content:space-between;align-items:center">
          <div style="display:flex;align-items:center">
            <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>
                <div class="btn" @click="handleSelectNumber(1)">全部选择</div>
                <el-divider></el-divider>
                <div class="select-number">
                  <span>从</span>
                  <el-input size="mini" v-model="queryParams.startNumber" @change="change1"></el-input>
                  <span>到</span>
                  <el-input size="mini" v-model="queryParams.endNumber" @change="change2"></el-input>
                  <el-button type="text" size="" @click="handleSelectNumber(2)">确定</el-button>
                </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 v-show="patentNoList.length" class="margin-left_10">
              <el-dropdown size="medium">
                <el-button type="primary" size="small">
                  批量操作<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <!-- <el-dropdown-item @click.native="handleRead(1)"
                    :disabled="!$permission('/workspace/folder/isRead')">已读</el-dropdown-item>
                  <el-dropdown-item @click.native="handleRead(0)"
                    :disabled="!$permission('/workspace/folder/isRead')">未读</el-dropdown-item> -->
                  <el-dropdown-item @click.native="handleIndex">批量标引</el-dropdown-item>
                  <el-dropdown-item @click.native="checkPatentWorth" v-if="patentNoList.length">价值曲线</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <!-- 编辑暂时隐藏，默认置为true -->
            <!-- <div class="margin-left_10">
              <el-checkbox @change="changeRefresh" :checked="refresh">
                <span>编辑</span>
              </el-checkbox>
            </div> -->
          </div>
          <div>
            <el-pagination background layout="total, sizes, prev, pager, next, jumper"
              :current-page.sync="queryParams.current" :page-sizes="sizeArr" :page-size.sync="queryParams.size"
              @current-change="handleCurrentChange" @size-change="getList" :total="total">
            </el-pagination>
          </div>

        </el-footer>
      </el-container>
    </el-container>

    <Field-Drawer ref="FieldDrawer"></Field-Drawer>
    <field ref="field" type="patent" @getFieldList="getFieldList"></field>
    <!-- 报告文档 -->
    <reportFileDrawer ref="reportFileDrawer"></reportFileDrawer>
    <!-- 创建FTO报告 -->
    <addAndEditReport ref="addAndEditReport"></addAndEditReport>
    <!-- 批量那个标引 -->
    <PatentBatchIndexVue ref="PatentBatchIndexVue" :projectId="projectId"></PatentBatchIndexVue>
    <!-- 合并发明人/合并权利人、申请人 -->
    <patentInventorMergeDrawer ref="patentInventorMergeDrawer" @mergeClose="mergeClose"></patentInventorMergeDrawer>
  </div>
</template>

<script>
import { downLoad2, getTreeDataList, getTreeLastChildren, getPatentCountry } from "@/utils"
import { fastSelectPatent } from './components/mixins/fastSelectPatent'
import FieldDrawer from '@/views/components/drawer/Field.vue'
import PatentAbstractListView from './components/views/Abstract'
import PatentTableListView from './components/views/Table.vue'
import PatentPictureListView from './components/views/Picture'
// import PatentPDFListView from './components/views/PDF.vue'
import field from '@/views/components/dialog/fields.vue';
import customFields from '@/views/report/components/patentList/components/customFields/index.vue';
import searchPatent from '@/views/report/components/patentList/components/searchPatent.vue';
import reportFileDrawer from '@/views/report/components/drawer/reportFileDrawer.vue'
import addAndEditReport from '@/views/report/components/dialog/addAndEditReport.vue'
import PatentBatchIndexVue from './components/dialog/PatentBatchIndex.vue'
import patentInventorMergeDrawer from './components/drawer/MergeInventor.vue'
import PatentKeywordsHighlight from '../components/PatentKeywordsHighlight.vue'
export default {
  mixins: [fastSelectPatent],
  components: {
    FieldDrawer,
    PatentAbstractListView,
    PatentTableListView,
    PatentPictureListView,
    field,
    customFields,
    searchPatent,
    reportFileDrawer,
    addAndEditReport,
    PatentBatchIndexVue,
    patentInventorMergeDrawer,
    PatentKeywordsHighlight
  },
  props: {},
  data() {
    return {
      //是否隐藏左侧
      showLeft: true,
      //检索字段
      searchFiled: [],
      // //检索条件
      // searchOption: {
      //   name: localStorage.searchContent,
      // },
      //视图方式
      viewList: [
        {
          value: 'patent-table-list-view',
          title: '表格视图',
          btn: 'el-icon-tickets',
        },
        {
          value: 'patent-abstract-list-view',
          title: '摘要视图',
          btn: 'el-icon-news',
        },
        {
          value: 'patent-picture-list-view',
          title: '图片视图',
          btn: 'el-icon-picture-outline',
        },
        {
          value: 'PatentPDFListView',
          title: 'PDF视图',
          btn: 'iconfont icon-pdf',
        }
      ],
      //选择的视图
      viewSelected: "patent-table-list-view",
      //显示栏位
      customList: [],
      //同族
      familyObj: {
        '0': '不区分同族',
        'simpleFamilyId': '简单同族',
        'inpadocFamilyId': 'INPADOC同族',
        'patsnapFamilyId': '扩展同族',
      },
      //页大小
      sizeArr: [10, 20, 30, 40, 50, 100],
      //排序
      sort: [],
      //加载
      loading: false,
      // 统计勾选的值（专利著录（专利本身））
      searchPatentCheck: [],
      // 存放专利本身检索条件
      searchStr: '',
      // 存放自定义栏位的检索条件
      customFields: [],
    };
  },
  watch: {},
  computed: {
    // 专题库id
    projectId() {
      return this.$route.query.id
    },
  },
  created() { },
  async mounted() {
    this.customList = await this.$commonJS.getCustomField('patent', { projectId: this.projectId, taskId: this.taskId })
    await this.getColumn()
    // 获取专利信息
    this.getList()
  },
  methods: {
    // 处理后的条件
    handleSearchValue({ searchStr, customFields }) {
      this.searchStr = searchStr
      this.customFields = customFields
      this.$refs.customFields.close()
      this.getList()
    },
    // 统计组件传的值
    handleCustomFields(val) {
      this.searchPatentCheck = []
      val.forEach(item => {
        if (item.check && item.check.length > 0) {
          if (item.filedKind == -1) {
            this.searchPatentCheck.push(item)
          } else {
            var checkName = []
            if (item.type == 'Array' || item.type == 'tree' || item.type == 'DateTime') {
              checkName = item.options.filter(item2 => item.check.includes(item2.id || item2.name)).map(item3 => item3.name);
            }
            var obj = {
              value: item.value,
              name: item.name,
              filedKind: item.filedKind,
              check: item.check,
              checkName: checkName,//自定义栏位多选
              type: item.type,
              ifHaveChild: this.ifHaveChild
            }
            // return
            this.searchPatentCheck.push(obj)
          }
        }
      })
      this.$nextTick(() => {
        this.$refs.searchPatent.search2()
      })
    },
    // 点击专利号进行跳转
    handleClick(row, location) {
      var search = {
        searchOption: this.searchOption,
        location: location,
      }
      this.$s.setSession('search', search)
      this.$router.push(
        {
          path: '/patentDetails/' + row.patentNo,
          query: {
            projectId: this.projectId,
            projectType:'1',//判断是不是从专题库进入专利详情1为专题库2为报告(报告未传2)
          }
        }
      )
    },
    //获取table栏位及分组字段、检索字段
    //获取检索字段
    async getColumn() {
      //   let params = ['patent']//原获取检索字段
      //   await this.$api.getParamsCommon(params).then(res => {
      //     if (res.code == 200) {
      //       let conditionDTOList = JSON.parse(JSON.stringify(res.data[0].conditionDTOList))
      //       // 搜索字段
      //       this.searchFiled = this.$commonJS.getField(conditionDTOList, (u) => u.ifSearch == true, {
      //         label: 'name',
      //         value: 'value',
      //         type: 'type',
      //       })
      //     }
      //   })
      let params = [{
        tableName: 'patent',
        projectId: this.projectId,
      }]
      await this.$api.getQueryFields(params).then(res => {
        if (res.code == 200) {
          let conditionDTOList = JSON.parse(JSON.stringify(res.data.data[0].conditionDTOList))
          let field = conditionDTOList.filter(item => {
            return item.group == 'nos'
          })
          let custom = conditionDTOList.filter(item => {
            return item.group == 'customField'
          })
          let customField = custom.filter(item => {
            return item.type != 'tree' && item.type != 'Array'
          })
          let arr = field.concat(customField)
          // 搜索字段
          this.searchFiled = this.$commonJS.getField(arr, (u) => u.ifSearch == true, {
            label: 'name',
            value: 'field',
            type: 'type',
            group: 'group',
            fieldType: 'fieldType',
            groupBy: 'groupBy',
          })
        }
      })
    },
    //检索
    // search(val) {
    //   let params = {}
    //   val.forEach(item => {
    //     if (item.type == 3) {
    //       params[item.value] = item.searchValue.map(itemValue => {
    //         return itemValue.value
    //       })
    //     } else {
    //       params[item.value] = item.searchValue.label
    //     }
    //   })
    //   // 返回字符串
    //   this.searchOption = params
    //   // 调用查询接口
    //   this.queryParams.current = 1
    //   this.getList()
    // },
    //切换视图
    async handleChangeView(item) {
      this.viewSelected = item.value
      this.queryParams.current = 1
      // if (this.viewSelected == 'PatentPDFListView') {
      //   return false
      // }
      if (this.viewSelected === 'patent-picture-list-view') {
        this.$set(this.queryParams, 'size', 20)
      } else {
        this.queryParams.size = 10
      }
      this.getList()
    },
    //获取专利信息
    getList(size) {
      if (size) {
        this.queryParams.size = size
      }
      let params = {
        ...this.queryParams,//分页信息及区分同族类型
        projectId: this.projectId,
        searchQuery: this.searchStr || '',//检索条件
        customFields: this.customFields || [],
        orderDTOList: this.sort,//排序信息
      }

      // this.$store.commit("SET_PATENT_PARAMS", params);
      this.$store.commit("SET_PATENT_RECORDS", []);
      this.$api.QueryPatent(params).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.data
          this.total = res.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)
          // this.$store.commit("SET_PATENT_PARAMS", params);
          this.$store.commit("SET_PATENT_RECORDS", res.data.data);
          if (this.quickSelect) {
            this.commonSwitch()
          }
          this.isRefresh()
        }
      }).catch(error => {
        this.tableData = []
        this.total = 0
      })
    },
    //排序
    handleSort({ column, prop, order }) {
      //如需要多个字段排序，则不需要清空
      var params = {
        sort: this.sort,
        column,
        prop,
        order,
      }
      this.sort = this.$commonJS.getSortData(params)
      this.queryParams.current = 1
      this.getList()
    },
    //分页
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.getList();
    },

    //自定义栏位管理
    handleField() {
      this.$refs.FieldDrawer.open(this.projectId)
    },
    //获取自定义栏位
    getFieldList(data) {
      this.customList = data
    },
    //显示栏位管理
    async handleFieldManage() {
      this.$refs.field.open(this.customList)
    },
    //报告文档
    handleFile() {
      this.$refs.reportFileDrawer.open(this.projectId)
    },
    //创建FTO报告
    handleAnalysesFto() {
      var form = {
        reportType: 3,
        signPatentNo: '',
        matterId: [],
        scenarioId: [],
      }
      this.$refs.addAndEditReport.open(form)
    },
    //切换同族
    onChangeFamily(key) {
      this.queryParams.current = 1
      this.queryParams.groupField = key
      this.getList()
    },
    // 批量标引
    handleIndex() {
      let obj = {
        selectQuery: {
          isAdd: this.queryParams.isAdd,
          isDelete: this.queryParams.isDelete,
          startNumber: this.startNumber,
          endNumber: this.endNumber,
        },
        searchQuery: this.searchStr,
        customFields: this.customFields,
        orderDTOList:this.sort,
      }
      this.$refs.PatentBatchIndexVue.open(obj)
    },
    //导出专利
    async handleExport(val) {
      if (val) {
        if (this.startNumber < 0 && this.endNumber < 1 || this.queryParams.isAdd.length == 0) {
          this.$message.error('请先选择专利')
          return false
        }
      }
      let obj = {
        isAdd: this.queryParams.isAdd,
        isDelete: this.queryParams.isDelete,
        startNumber: this.startNumber,
        endNumber: this.endNumber,
        searchQuery: this.searchStr,
        customFields: this.customFields,
        orderDTOList:this.sort,
      }
      if (!val) {
        // 如果是导出全部，endNumber是当前的全部专利
        obj.endNumber=this.total
      }
      let router = this.$router.resolve({
        path: '/exportPatent',
        query: {
          projectId: this.projectId,
          condition: JSON.stringify(obj)
        }
      })
      window.open(router.href, '_blank')
    },
    //PDF首页导出
    exportPDF() {
      let params = {
        projectId: this.projectId,
        searchQuery: this.searchStr || '',//检索条件
        customFields: this.customFields || [],//自定义字段的检索
        isAdd: this.queryParams.isAdd,
        isDelete: this.queryParams.isDelete,
        startNumber: this.startNumber,
        // endNumber: this.endNumber,
        endNumber: this.total,//默认是当前全部
        orderDTOList:this.sort,
      }
      this.$api.exportPDFFirstPage(params).then(res => {
        if (res.code == 200) {
          const h = this.$createElement;
          this.$msgbox({
            title: '提示',
            message: h('p', null, [
              h('span', null, '任务正在导入，查看任务进度请前往 '),
              h('span', {
                style: 'color: #ff7d38;cursor: pointer;',
                on: {
                  click: () => {//
                    let router = this.$router.resolve({
                      path: '/taskList',
                      query: {
                        importToId: this.projectId,
                      }
                    })
                    window.open(router.href, '_blank')
                    this.$msgbox.close(false)
                  }
                }
              }, '立即前往',)
            ]),
            type: 'warning',
            showConfirmButton: false,
          }).then(action => {
          });
        }
      })
    },
    //图表分析
    async handleAnalyses() {
      var params = {
        searchQuery: this.searchStr || '',//检索条件
        customFields: this.customFields || [],
        orderDTOList: this.sort,//排序信息
        projectId:this.projectId
      }
      const router = this.$router.resolve({
        path: '/customChart',
        query: {
          projectId: this.projectId,
          search:JSON.stringify(params),
          patentNum:this.total
        }
      })
      window.open(router.href, '_blank');
    },
    //合并发明人//合并申请人、权利人
    handleMerge(type) {
      let obj = {
        projectId: this.projectId,
        type: type
      }
      this.$refs.patentInventorMergeDrawer.open(obj)
    },
    // 合并发明人、申请人、权利人后子组件发送的消息
    mergeClose() {
      this.getList()
    },






















    //下载PDF
    async handleDownload(patent) {
      const { data } = await this.$api.getPatentInstructionList({ current: 1, size: 9999, patentNo: patent.patentNo })
      if (data.records.length !== 0) {
        downLoad2(data.records[0].url)
      } else {
        this.$alert('专利暂未上传说明书文档', '请求错误', {
          confirmButtonText: '确定',
          type: 'error',
          callback: action => { }
        });
      }
    },
    //切换已读未读
    handleChangeRead(ids, status) {
      let params = {
        patentIds: ids,
        projectId: this.projectId,
        status: status,
        folder: this.queryParams.folder
      }
      this.fastEditLoading = true
      this.$api.updatePatentReadStatus(params).then(response => {
        this.$refs.patentQueryFilter.getPatentReadTotal()
        this.fastEditLoading = false
        this.getList()
      }).catch(error => {
        this.fastEditLoading = false
      })
    },
    //自定义栏位以及标签设置值
    handleIndexSetting(patent, field) {
      if (field) {
        this.$refs.patentIndexSetting.open(this.queryParams.projectId, patent, field)
      }
    },

    //取消编辑
    // changeRefresh() {
    //   this.patentNoList = []
    //   // this.refresh = !this.refresh
    // },





  },
};
</script>
<style lang="scss" scoped>
.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>