<template>
  <div style="background: white; height: 100%">
    <el-container style="padding: 0 20px">
      <el-header
        class="workspace-content-container-header"
        style="display: flex; justify-content: space-between"
      >
        <div>
          <el-button-group class="margin-left_10">
            <el-tooltip v-for="item in viewList" class="item" effect="dark" :content="item.title" placement="top">
              <el-button @click="handleChangeView(item)" size="small" :type="viewSelected === item.value ? 'primary' : ''" :icon="item.btn"></el-button>
            </el-tooltip>
          </el-button-group>
          <span v-if="selectedTotal>0" >
            已勾选 <b>{{ selectedTotal }}</b> 条
          </span>
        </div>
        
        <div style="max-width:calc(100% - 620px)">
          <p><span>条件：</span>{{ condition }}</p>
        </div>
        <div>
          <el-button type="primary" size="small" @click="importToProject">导入到报告</el-button>
          <el-button size="small" type="warning" @click="handleFieldManage">显示栏位管理</el-button>
          <el-popover placement="bottom" title="" width="220" trigger="click">
            <el-main class="patent-fast-edit-popover" v-loading="selectNumberLoading">
              <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>
          <el-button type="text" size="small" class="margin-left_10" @click="handleCancelSelectNumber">取消选择</el-button>
        </div>
      </el-header>
      <el-main id="patent-list-container" v-loading="loading">
        <div :style="{height:divHeight+'px'}">
          <component
            ref="patentViewList"
            :is="viewSelected"
            @select-change="handleSelect"
            :selected.sync="queryParams.selected"
            :patentNoList.sync="patentNoList"
            :view-field="patentViewField"
            @on-sort="handleSort"
            @addSelect="getChoosePatentNo"
          ></component>
        </div>
      </el-main>
      <el-footer class="workspace-content-patent-page 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="getList"
        >
        </el-pagination>
      </el-footer>
    </el-container>

    <patent-view-field @reset="getPatentViewField(true)" @update="updatePatentViewField" ref="patentViewField"/>
    <Project-List-Dialog ref="projectListDialog"></Project-List-Dialog>
  </div>
</template>

<script>
import PatentViewField from "@/views/product/components/relatedPatents/components/dialog/PatentViewField.vue";
import PatentTableListView from "./view/Table";
import PatentAbstractListView from "./view/Abstract";
import PatentPictureListView from "./view/Picture";
import ProjectListDialog from "./components/projectListDialog.vue";
export default {
  components: {
    PatentViewField,
    PatentTableListView,
    PatentAbstractListView,
    PatentPictureListView,
    ProjectListDialog,
  },
  props: ["condition", "DBType",'reportId','retrieveRecordId','asCompare'],
  data() {
    return {
      pageSizes:[10, 20, 30, 40, 50],
      viewSelected: "patent-table-list-view",
      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",
        },
      ],
      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:[],
      divHeight:null
    };
  },
  watch: {},
  computed: {
    records() {
      return this.$store.state.patent.records;
    },
  },
  created() {},
  async mounted() {
    if(this.$s.getSession('queryParams')&&this.$s.getSession('queryParams').params.retrieveRecordId){
        this.queryParams.retrieveRecordId = this.$s.getSession('queryParams').params.retrieveRecordId
      }
    this.$nextTick(()=>{
      this.divHeight = document.getElementsByClassName('el-main')[0].offsetHeight - 250
    })
  await  this.getList();
    this.getPatentViewField();
    
  },
  methods: {
    //导入到专题库
    importToProject() {
      var form = {
        conditions:this.condition,
        DBType:this.DBType,
        orderBy:this.queryParams.OrderBy,
        orderByType:this.queryParams.OrderByType,
        startNumber:this.selectedTotal>0?this.startNumber:1,
        endNumber:this.selectedTotal>0?this.endNumber:this.total,
        isAddPatentNos:this.queryParams.isAdd,
        isDeletePatentNos:this.queryParams.isDelete,
        reportId:this.reportId,
        asCompare:this.asCompare,
      }
      this.$refs.projectListDialog.open(form);
    },
    //切换页数
    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([])
          }
        }
      })
    },
    //获取最大页数
    getPageCount(){
      var a = Math.ceil(Number(this.total)/Number(this.queryParams.size))
      return a>200?200:a
    },
    //开始条数校验
    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
      }
    },
    //查询专利
    async getList() {
      let queryParams = JSON.parse(JSON.stringify(this.queryParams));
      var params = {
        CurrentQuery: this.condition, //检索式
        DBType: this.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
      };
      // console.log(this.$s.getSession('retrieveRecordId'),)
      queryParams.params = params;
      queryParams.reportId = this.reportId
      this.$store.commit("SET_PATENT_PARAMS", queryParams);
      this.$store.commit("SET_PATENT_RECORDS", []);
      this.loading = true;
      await this.$api.patentSelectImport(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.records;
            this.tableData = records
            params.retrieveRecordId = response.data.retrieveRecordId
            this.queryParams.retrieveRecordId = response.data.retrieveRecordId
            this.$store.commit("SET_PATENT_PARAMS", queryParams);
            this.$s.setSession('queryParams',queryParams)
            this.$store.commit("SET_PATENT_RECORDS", records);
            this.loading = false;
          }
        })
        .catch((error) => {
          this.loading = false;
        });
        
    },
    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();
      }
return 

      this.viewSelected = item.value;
      if (this.viewSelected === "patent-picture-list-view") {
        this.$set(this.queryParams, "size", 20);
      } else {
        this.queryParams.size = 10;
      }
      // await this.getPatentViewField();
      this.getList();
    },
    async handleFieldManage() {
      // await this.getPatentViewField()
      this.$refs.patentViewField.open(
        this.patentViewField,
        this.queryParams.retrieveRecordId,
        this.viewSelected
      );
    },
    async getPatentViewField(refresh) {
      var arr = ['标签','简单同族','Inpadoc同族','扩展同族','[标]权利人','[标]申请人','引用专利数量','被引用数量','权利要求数']
      let params = {
        project:this.queryParams.retrieveRecordId,
        type: "list",
        view: this.viewSelected,
        refresh: refresh,
      };
      const { data } = await this.$api.getUserSettingField(params);
      this.patentViewField = data.filter(item=>{ return arr.indexOf(item.name) == -1});
    },
    updatePatentViewField(data) {
      this.patentViewField = data;
    },
    //快速选择
    handleSelectNumber(type) {
      switch (type) {
        case 0: //本页选择
          this.patentNoList = [...new Set(this.patentNoList.concat(this.$store.state.patent.records.map((item) => item.applicationNo))),];
          this.queryParams.isAdd = [...new Set(this.queryParams.isAdd.concat(this.$store.state.patent.records.map((item) => item.applicationNo))),];
          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) {
      console.log(data);
      const o = {
        publicAccreditDate: "GD",
        publicDate: "PD",
        applicationDate: "AD",
      };
      this.queryParams.OrderBy = o[data.prop];
      this.queryParams.OrderByType = data.order.toUpperCase();
      this.getList();
    },
  },
};
</script>
<style lang="scss" scoped>
.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;
  align-items: center;
}
.patent-fast-edit-popover {
  padding: 0 !important;
  .btn {
    color: #000;
    line-height: 40px;
    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>
