<template>
  <div class="patent-query-filter">
    <el-container>
      <el-header class="patent-query-filter-header">
        <div class="query-read-status" v-for="(item, key) in readList" :class="{ 'query-read-status_is-active' : key === returnData.read }" @click="handleReadQuery(key)">
          <span class="a">(<span class="b">{{ readStatus[key] }}</span>)</span>
          <span class="c">{{ item }}</span>
        </div>
      </el-header>
      <el-main class="patent-query-filter-main">
        <el-collapse v-model="activeNames" @change="handleChange">
          <el-collapse-item v-for="item in field.filter(f => !f.hidden)" :title="item.name" :name="item.key" v-if="sourceQuery[item.key]">
            <div v-if="isClassNumber(item.key)" class="patent-query-filter-main-select">
              <el-select v-model="sourceQuery[item.key].classId" size="small" placeholder="请选择" @change="handleClassIdChange(item)">
                <el-option v-if="['13', '15'].indexOf(item.key) !== -1" value="1" label="部"></el-option>
                <el-option v-else value="1" label="分类号"></el-option>
                <el-option value="2" label="大类"></el-option>
                <el-option value="3" label="小类"></el-option>
                <el-option v-if="['13', '15'].indexOf(item.key) !== -1" value="4" label="大组"></el-option>
                <el-option v-if="['13', '15'].indexOf(item.key) !== -1" value="5" label="小组"></el-option>
              </el-select>
            </div>
            <div class="patent-query-filter-search">
              <div class="patent-query-filter-search-input">
                <el-input v-if="['25-12', '26-12'].indexOf(item.key) === -1" v-model="sourceQuery[item.key].label" size="small" placeholder="请输入查询内容"></el-input>
                <div v-else class="year-data-picker">
                  <el-date-picker clear-icon size="small" v-model="sourceQuery[item.key].datePicker[0]" type="year" value-format="yyyy"></el-date-picker>
                  <span>至</span>
                  <el-date-picker clear-icon size="small" v-model="sourceQuery[item.key].datePicker[1]" type="year" value-format="yyyy"></el-date-picker>
                </div>
              </div>
              <el-button @click="handleSearch(item)" size="small" type="primary" icon="el-icon-search" circle></el-button>
            </div>
            <el-checkbox-group v-if="['40-0'].indexOf(item.key) ===-1" v-model="sourceQuery[item.key].checked" @change="onChange(item.key)">
              <div class="source-checkbox">
                <el-checkbox v-for="source in sourceData[item.key]" :label="source.value">
                  <span class="source-checkbox-label" :title="source.label">{{ source.label }}</span>
                  <span class="source-checkbox-count">({{ source.count }})</span>
                </el-checkbox>
              </div>
            </el-checkbox-group>
            <el-checkbox-group v-if="['40-0'].indexOf(item.key) !==-1" v-model="sourceQuery[item.key].checked" @change="onChange(item.key)">
              <div class="source-checkbox">
                <el-checkbox v-for="source in sourceData[item.key]" :label="source.label">
                  <span class="source-checkbox-label" :title="source.label">{{ source.label }}</span>
                  <span class="source-checkbox-count">({{ source.count }})</span>
                </el-checkbox>
              </div>
            </el-checkbox-group>
            <div class="patent-query-filter-search-bottom">
              <el-button type="success" size="small" @click="handleSelectAll(item)" :loading="sourceQuery[item.key].loading">全选</el-button>
              <el-button type="danger" size="small" @click="handleSelectCancel(item)">取消</el-button>
              <el-button v-if="!sourceQuery[item.key].isEnd" type="primary" size="small" @click="handleLoadMore(item)" :loading="sourceQuery[item.key].loading">加载更多</el-button>
              <span v-else></span>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-main>
      <el-footer class="patent-query-filter-footer">
        <el-button type="primary" size="small" @click="handleMoreQuery">更多过滤项</el-button>
      </el-footer>
    </el-container>

    <el-dialog title="管理过滤字段" :visible.sync="visible" width="630px" :append-to-body="true" :close-on-click-modal="false" destroy-on-close :before-close="close" top="10vh">
      <div class="paten-query-filter-dialog">
        <el-transfer
            class="transfer"
            v-model="selected"
            filterable
            :filter-method="filterMethod"
            :titles="['未选择', '已选择']"
            :button-texts="['', '']"
            :format="{ noChecked: '${total}', hasChecked: '${checked}/${total}' }"
            @right-check-change="rightCheckChange"
            @change="handleChange2"
            :data="form">
          <span slot-scope="{ option }">{{ option.name }}</span>
          <div slot="left-footer"></div>
          <div class="transfer-footer" slot="right-footer">
            <el-button @click="handleQueryOrder(-1)" type="primary" size="small" icon="el-icon-top" circle></el-button>
            <el-button @click="handleQueryOrder(1)" size="small" icon="el-icon-bottom" circle></el-button>
          </div>
        </el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" class="float_left" @click="getPatentQueryField(true)" :loading="btnLoading2">重置</el-button>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="updatePatentQueryField" :loading="btnLoading">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { patentQueryMixins } from "../mixins";

export default {
  mixins: [patentQueryMixins],
  components: {
  },
  data() {
    return {
      field: [],
      visible: false,
      loading: false,
      btnLoading: false,
      btnLoading2: false,
      queryParams: {
        projectId: 0,
        folder: []
      },
      sourceQuery: {},
      sourceData: {},
      classTemp: [],
      hasSource: [],
      activeNames: [],
      data: [],
      selected: [],
      rightSelect: [],
      form: [],
      readStatus: {},
      readList: {
        all: '全部',
        read: '已读',
        unread: '未读',
      },
      returnData: {
        read: 'all',
        field: [],
        key: ''
      },
    }
  },
  watch: {
    closeFieldDrawer() {
      this.getPatentQueryField()
    },
    submitIndexSetting() {
      this.refreshSourceData()
    }
  },
  methods: {
    async loadData() {
      this.queryParams.projectId = this.projectId
      this.queryParams.folder = this.folder
      await this.getPatentQueryField(false, true)
      this.getPatentReadTotal()
    },
    initFieldQueryForm() {
      this.form.map(item => {
        const temp = this.sourceQuery[item.key]
        if (!temp) {
          this.$set(this.sourceQuery, item.key, {
            projectId: this.queryParams.projectId,
            folder: this.queryParams.folder,
            key: item.key,
            current: 1,
            size: 10,
            order: 'desc',
            label: '',
            loading: false,
            checked: [],
            classId: '1',
            type: item.type,
            isEnd: false,
            datePicker: ['', '']
          })
        }
      })
    },
    async getPatentQueryField(refresh, loadForm) {
      let params = {
        projectId: this.queryParams.projectId,
        type: 'query',
        refresh: refresh
      }
      const { data } = await this.$api.getUserSettingField(params)
      // console.log(data)
      this.initFieldData(data)
      if (loadForm) {
        this.initFieldQueryForm()
      }
      if (refresh) {
        this.visible = false
      }
    },
    initFieldData(data) {
      this.field = data
      this.form = JSON.parse(JSON.stringify(data))
      this.selected = this.field.filter(item => !item.hidden).map(item => item.key)
    },
    getPatentQueryFieldSource(key, refresh = false) {
      let params = {
        projectId: this.sourceQuery[key].projectId,
        folder: this.sourceQuery[key].folder,
        key: this.isClassNumber(key) ? (key + '-' + this.sourceQuery[key].classId) : this.sourceQuery[key].key,
        current: this.sourceQuery[key].current,
        size: this.sourceQuery[key].size,
        order: this.sourceQuery[key].order,
        label: this.sourceQuery[key].label,
        type: this.sourceQuery[key].type,
        startDate: this.sourceQuery[key].datePicker[0],
        endDate: this.sourceQuery[key].datePicker[1],
        refresh: false,
      }
      this.sourceQuery[key].loading = true
      this.$api.getPatentQuerySourceList(params).then(response => {
        const records = response.data.records
        let temp = this.sourceData[key]
        if (!temp || refresh) {
          temp = records
        } else {
          temp.push(...records)
        }
        if (this.isClassNumber(key)) {
          this.classTemp.push(...temp)
        }
        this.sourceQuery[key].isEnd = temp.length >= response.data.total
        this.$set(this.sourceData, key, temp)
        this.sourceQuery[key].loading = false
      }).catch(error => {
        this.sourceQuery[key].loading = false
      })
    },
    handleChange(data) {
      const val = data[data.length - 1];
      if (val && this.hasSource.indexOf(val) === -1) {
        this.hasSource.push(val)
        this.getPatentQueryFieldSource(val)
      }
    },
    handleClassIdChange(item) {
      this.sourceData[item.key] = []
      this.sourceQuery[item.key].current = 1
      this.sourceQuery[item.key].label = ''
      // this.sourceQuery[item.key].checked = []
      this.getPatentQueryFieldSource(item.key)
    },
    handleSearch(item) {
      this.sourceData[item.key] = []
      // this.sourceQuery[item.key].checked = []
      this.sourceQuery[item.key].current = 1
      this.getPatentQueryFieldSource(item.key)
    },
    handleLoadMore(item) {
      this.sourceQuery[item.key].current = this.sourceQuery[item.key].current + 1
      this.getPatentQueryFieldSource(item.key)
    },
    handleSelectAll(item) {
      const key = item.key
      let params = {
        projectId: this.sourceQuery[key].projectId,
        folder: this.sourceQuery[key].folder,
        key: this.isClassNumber(key) ? (key + '-' + this.sourceQuery[key].classId) : this.sourceQuery[key].key,
        current: 1,
        size: 9999999,
        order: this.sourceQuery[key].order,
        label: this.sourceQuery[key].label,
        type: this.sourceQuery[key].type,
        startDate: this.sourceQuery[key].datePicker[0],
        endDate: this.sourceQuery[key].datePicker[1],
        refresh: false,
      }
      this.sourceQuery[key].loading = true
      this.$api.getPatentQuerySourceList(params).then(response => {
        const records = response.data.records
        this.sourceQuery[key].checked = records.map(item => item.value)
        this.onChange(key)
        this.sourceQuery[key].loading = false
      }).catch(error => {
        this.sourceQuery[key].loading = false
      })
    },
    handleSelectCancel(item) {
      const key = item.key
      this.sourceQuery[key].checked = []
      this.onChange(key)
    },
    handleReadQuery(type) {
      this.returnData.read = type
      this.returnData.key = ''
      this.refreshSourceData()
      this.$emit('on-change', this.returnData)
    },
    isClassNumber(key) {
      return ['13', '15', '16', '17'].indexOf(key) !== -1
    },
    async handleMoreQuery() {
      await this.getPatentQueryField()
      this.visible = true
    },
    handleTextQuery() {
      this.$refs.patentTextQueryFilter.open()
    },
    handleTextSearch(data) {
      const label = {
        'name': '标题',
        'abstractStr': '摘要',
        'publicNo': '公开号',
        'applicationNo': '申请号',
        'rightContent': '权利要求',
      }
      for (let key in data) {
        if (data[key]) {
          const index = this.queryData.map(item => item.key).indexOf(key)
          const value = {
            data: [{
              label: data[key],
              value: data[key]
            }],
            type: 'text',
            key: key,
            name: label[key]
          }
          if (index === -1) {
            this.queryData.push(value)
          } else {
            this.$set(this.queryData, index, value)
          }
        }
      }
      this.$emit('text-change', data)
    },
    onChange(key) {
      let field = []
      for (let name in this.sourceQuery) {
        field.push({
          value: this.sourceQuery[name].checked,
          key: name,
          classId: this.sourceQuery[name].classId,
          type: this.sourceQuery[name].type
        })
      }
      const res = new Map()
      this.updateQueryData(key, (this.isClassNumber(key) ? this.classTemp.filter((a) => !res.has(a.value) && res.set(a.value, 1)) : this.sourceData[key]), field.find(item => item.key === key))
      this.returnData.field = field
      this.returnData.key = key
      this.$emit('on-change', this.returnData)
    },
    updateQueryData(key, source, data) {
      const index = this.queryData.map(item => item.key).indexOf(data.key)
      const value = {
        data: source.filter(item => data.value.indexOf(item.value) !== -1),
        type: 'field',
        key: data.key,
        name: this.field.find(item => item.key === key).name || ''
      }
      if (index === -1) {
        this.queryData.push(value)
      } else {
        this.$set(this.queryData, index, value)
      }
    },
    close() {
      this.visible = false
    },
    rightCheckChange(data) {
      this.rightSelect = data
    },
    handleChange2() {
      let order = 1
      for (let i = 0; i < this.selected.length; i++) {
        const index = this.form.map(item => item.key).indexOf(this.selected[i])
        this.form[index].order = order++
      }
    },
    handleQueryOrder(order) {
      this.rightSelect.map(item => {
        const index = this.selected.indexOf(item)
        const cIndex = index + order
        if (cIndex < 0 || cIndex >= this.selected.length) {
          return false
        }
        let current = this.form.find(item => item.key === this.selected[index])
        let exchange = this.form.find(item => item.key === this.selected[cIndex])
        current.order = current.order + order
        exchange.order = exchange.order + (order === -1 ? 1 : -1)
        this.form.sort((a, b) => {
          return a.order - b.order
        })
        const temp = this.selected[index]
        this.selected[index] = this.selected[cIndex]
        this.selected[cIndex] = temp
      })
    },
    filterMethod(query, item) {
      // console.log(query,item)
      return item.name.indexOf(query) !== -1
    },
    updatePatentQueryField() {
     
      this.form.map(item => item.hidden = this.selected.indexOf(item.key) === -1)
      let data = {
        data: this.form,
        projectId: this.queryParams.projectId,
        type: 'query'
      }
      this.btnLoading = true
      this.$api.updateUserSettingField(data).then(response => {
        this.close()
        this.initFieldData(response.data)
        this.initFieldQueryForm()
        this.btnLoading = false
        this.$message.success('操作成功')
      }).catch(error => {
        this.btnLoading = false
      })
    },
    getPatentReadTotal() {
      this.$api.getPatentReadTotal({ projectId: this.queryParams.projectId, folder: this.queryParams.folder }).then(response => {
        this.readStatus = response.data
      })
    },
    refreshSourceData() {
      this.activeNames = []
      this.hasSource = []
      this.sourceData = {}
      for (let key in this.sourceQuery) {
        this.sourceQuery[key].current = 1
        this.sourceQuery[key].label = ''
      }
    }
  }
}
</script>

<style lang="scss">
.patent-query-filter {
  height: 100%;
  .patent-query-filter-header {
    display: flex;
    justify-content: space-between;
    height: 40px !important;
    padding: 0 !important;
  }
  .patent-query-filter-main {
    height: 100%;
    padding: 10px 0;
    .patent-query-filter-main-select {
      .el-select {
        width: 255px;
      }
    }
    .patent-query-filter-search {
      height: 40px;
      line-height: 40px;
      .patent-query-filter-search-input {
        width: 220px;
        display: inline-block;
      }
      .el-button {
        margin-left: 5px;
      }
      .el-date-editor {
        width: 90px;
      }
    }
    .patent-query-filter-search-bottom {
      text-align: center;
      margin-top: 10px;
    }
  }
  .patent-query-filter-footer {
    padding: 10px 0 !important;
    .el-button {
      float: right;
    }
  }
  .year-data-picker {
    display: flex;
    justify-content: space-between;
    .el-input__prefix {
      display: none;
    }
    .el-input__inner {
      padding: 10px;
      text-align: center;
    }
  }
  .query-read-status {
    font-size: 12px;
    height: 25px;
    line-height: 25px;
    cursor: pointer;
    background: #dcdcdc;
    border-radius: 3px;
    padding: 0 5px;
    // span {
    //   display: inline-block;
    // }
    .a {
      position:unset
    }
    .b {
      text-align: center;
      min-width: 30px;
    }
    .c {
      margin-left: 5px;
    }
  }
  .query-read-status_is-active {
    background: #409EFF !important;
    color: #ffffff !important;
  }
  .source-checkbox {
    margin-top: 10px;
    span {
      display: inline-block;
      font-size: 13px;
    }
    .el-checkbox {
      display: block;
    }
    .el-checkbox__label {
      position: relative;
      top: 5px;
    }
    .source-checkbox-count {
      color: #409EFF;
      position: relative;
      top: -4px;
      left: 10px;
    }
    .source-checkbox-label {
      max-width: 190px;
      padding-left: 5px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
}
.paten-query-filter-dialog {
  text-align: center;
  .transfer {
    text-align: left;
    display: inline-block;
  }
  .el-transfer-panel__body {
    height: 400px;
  }
  .el-transfer-panel__list.is-filterable {
    height: 350px;
  }
  .transfer-footer {
    margin: 5px;
  }
}
</style>