<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" :key="item.value" 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>

        </div>

        <!-- <div style="max-width:calc(100% - 620px)">
          <p><span>条件：</span>{{ searchData.searchCondition }}</p>
        </div> -->
        <div style="max-width: 800px;margin-top: 0px;display: flex;justify-content: center;align-items: center;">
          <search :field="field" :searchResult="true" :searchValue="false" :countryList="queryParams.countryList"
            @search="search"></search>
          <p><el-link style="width: 50px;margin-left: -60px;color: #409EFF;" @click="searches">检索式</el-link></p>
        </div>
        <div>
          <el-button type="primary" size="small" @click="importToProject">导入专利</el-button>
          <el-button size="small" type="warning" @click="handleFieldManage">显示栏位管理</el-button>
        </div>
      </el-header>
      <el-main id="patent-list-container" v-loading="loading">
        <div class="height_100">
          <component ref="patentViewList" :is="viewSelected" :outside="true" :column="columnList" :tableData="tableData"  @clickPatentNo="handleClick"
            @select-change="handleSelect" :selected.sync="queryParams.selected" :patentNoList.sync="patentNoList" :refresh='true'
            :view-field="patentViewField" @on-sort="handleSort" @addSelect="getChoosePatentNo"></component>
        </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>
              <!-- <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>
        <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="getList">
          </el-pagination>
        </div>
      </el-footer>
    </el-container>


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

    <el-dialog custom-class="checkCondition" title="查看/编辑检索式" :visible.sync="visible" width="500px"
      :before-close="() => { visible = false }" :close-on-click-modal="false" append-to-body>
      <div>
        <el-input type="textarea" :rows="4" v-model="condition.searchCondition"></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="searchFinish">检 索</el-button>
        <el-button type="primary" v-if="condition.reportType==1||condition.reportType == 2" @click="saveSearchCondition">保存检索式</el-button>
      </span>
    </el-dialog>
    <addAndEditSearchRecords ref="addAndEditSearchRecords" :projectId="condition.importToId"></addAndEditSearchRecords>
  </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';
export default {
  components: {
    PatentTableListView,
    PatentAbstractListView,
    PatentPictureListView,
    field,
    projectListDialog,
    search,
    addAndEditSearchRecords
  },
  props: {
    searchData: {}
  },
  data() {
    return {
      columnList: [],
      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: null,
      endNumber: null,
      quickSelect: false,
      quickSelectArr: [],
      /**检索式 */
      // 公用数据
      field: JSON.parse(JSON.stringify(this.$constants.searchField)),
      // 打开弹窗
      visible: false,
      // 检索式及其他信息
      condition: this.searchData,
    };
  },
  watch: {},
  computed: {
    ...mapGetters(['userinfo']),
  },
  created() { },
  async mounted() {
    this.columnList = await this.$commonJS.getCustomField('patent',{ projectId: 0, taskId: null })
    if (this.$s.getSession('queryParams') && this.$s.getSession('queryParams').params.retrieveRecordId) {
      this.queryParams.retrieveRecordId = this.$s.getSession('queryParams').params.retrieveRecordId
    }

    await this.getList();

  },
  methods: {
    //保存检索式
    saveSearchCondition(){
      var form = {
        searchCondition:this.condition.searchCondition,
        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,
      }
      this.$s.setSession('search', search)
      this.$s.setSession('import',this.searchData)
      this.$router.push(
        {
          path: '/patentDetails/' + row.patentNo,
          query: {
            outside:true
          }
        }
      )
    },
    //子组件返回检索式 
    async search(val) {
      if (val.searchStr == '') {
        this.$message.error('检索信息不能为空')
        return false
      }
      if (val.isRepeat) {
        this.condition.searchCondition = `${this.condition.searchCondition} AND ${val.searchStr}`
      } else {
        this.condition.searchCondition = val.searchStr
      }
      await this.searchBth()
    },
    searchBth() {
      this.queryParams.retrieveRecordId = null
      this.getList()
      this.$router.push({
        path: '/searchResult',
        query: {
          data: JSON.stringify(this.condition),
        }
      })
      
    },
    // 打开检索式弹窗
    searches() {
      this.visible = true
    },
    // 编辑、查看检索式
    async searchFinish() {
      await this.searchBth()
      this.visible = false
    },
    //导入到专题库
    importToProject() {
      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);
    },
    //切换页数
    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.searchData.searchCondition, //检索式
        // DBType: this.searchData.DBType, //”CN”或”WD”,表示检索中文库或世界库
        CurrentQuery: this.condition.searchCondition, //检索式
        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
      };
      // 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;
      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
          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.getImageAndStatus()
          this.loading = false;
        }
      })
        .catch((error) => {
          this.loading = false;
        });

    },
    //获取摘要附图和法律状态
    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)
          }
        })
      })
      
    },
    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 = 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) {
      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;
  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>
