<template>
  <div class="patent-tree-filter">
    <el-container>
      <el-header class="basic_header">
        <el-tabs v-model="activeNameTabs" type="card" style="width:100%">
          <el-tab-pane v-for="item in menu" :key='item.path' :label="item.label" :name="item.path"></el-tab-pane>
        </el-tabs>
      </el-header>
      <el-main>
        <component :is="activeNameTabs" v-on="$listeners" :field="field" :activeName.sync="activeName"
          :fieldTree="fieldTree" @collapseClick="handleCollapse" @search="handleSearch" @handleLoading="handleLoading"
          @switchChange="switchChange" @selectChange="selectChange">
          <!-- <div slot="footerBtn">
            <el-button type="primary" size="small" @click="handleMore">更多过滤项</el-button>
          </div> -->
        </component>
      </el-main>
      <el-footer>
        <div style="display: flex;align-items: center;justify-content: end;">
          <el-button type="primary" size="small" v-if="activeNameTabs == 'queryPage'"
            @click="handleMore">更多过滤项</el-button>
          <el-button type="primary" size="small" @click="sure">确认</el-button>
        </div>

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

    <fieldsVue ref="fieldsVue" type="patent" :projectId="projectId" :taskId="taskId" :sign="true"
      @getFieldList="getFieldList"></fieldsVue>
  </div>
</template>

<script>
import queryPage from './components/tab1.vue'
import selectPage from './components/tab2.vue'
import fieldsVue from '@/views/components/dialog/fields.vue'
export default {
  props: {
    projectId: {
      default: null
    },
    taskId: {
      default: null
    },
    // 检索条件
    searchOption: {
      default: () => {
        return ''
      }
    },
    // 自定义栏位检索条件
    customFields: {
      default: () => {
        return []
      }
    },
    // 检索式的数组数据
    searchPatentCheck: {
      default: () => {
        return []
      }
    },
  },
  components: {
    queryPage,
    selectPage,
    fieldsVue,
  },
  data() {
    return {
      activeNameTabs: 'queryPage',
      menu: [
        {
          label: '查询筛选',
          path: 'queryPage'
        },
        {
          label: '分类选择',
          path: 'selectPage'
        },
      ],
      //存放可以显示的栏位
      showField:[],
      // 存放数据非树
      field: [],
      // 存放数据树
      fieldTree: [],
      // 所有的统计栏位
      filedAll: [],

      //已打开过的折叠面板
      activeName: [],
      //正在打开的折叠面板
      activeName2: [],
      // 树不关联模式
      ifHaveChild: false,
    }
  },
  watch: {
    searchOption: {
      handler() {
        this.refreshOptions()
      },
    },
  },
  async mounted() {
    // 获取显示的统计栏位
    await this.getShowCountColumns()
    // 获取所有统计栏位的数据
    this.getAllCountColumns()
  },
  methods: {
    // 条件改变时刷新已打开的折叠面板
    refreshOptions() {
      for (let i = 0; i < this.activeName.length; i++) {
        var row = this.field.find(item => {
          return item.value + 'a' + item.filedKind == this.activeName[i]
        })
        this.getOptions(row)
      }
    },
    // 检索条件取消时统计勾选项一并取消//待修改，需要考虑产品架构、技术分类、等id重复的情况
    close() {
      let data = this.searchPatentCheck
      // return
      for (let i = 0; i < data.length; i++) {

        if (data[i].filedKind == 0 && data[i].type == 'tree') {
          
        } else {
          let a = this.field.filter(item => {
            return item.value == data[i].value
          })
          if (a) {
            a[0].check = data[i].check
          }
        }

      }
    },
    // 树点击不关联模式
    async switchChange(val) {
      this.ifHaveChild = val
      for (let i = 0; i < this.activeName.length; i++) {
        var row = this.fieldTree.find(item => {
          return item.value + 'a' + item.filedKind == this.activeName[i]
        })
        await this.getOptions(row)
      }
    },
    // ipc、cpc、loc、upc切换选择
    selectChange({ val: val, data: data }) {
      this.getOptions(data)
    },
    // 点击面板中的搜索
    handleSearch(row) {
      // this.getOptions(row)
      //查统计todo统计接口
      this.esCountAnalysis(row)
    },
    // 点击当前面板
    async handleCollapse(current, data, type) {
      this.activeName = [...new Set(this.activeName.concat(data))]
      if (current && this.activeName2.indexOf(current) == -1) {
        this.activeName2.push(current)
        var currentField = this.filedAll
        if (type == 2) {
          currentField = this.fieldTree
        }
        var row = currentField.find(item => {
          return item.value + 'a' + item.filedKind == current
        })
        // 设置ipc、cpc、loc、upc选择
        this.getSelect(row)
        await this.getOptions(row)
      }
    },
    //获取选项
    async getOptions(row) {
      if (row) {
        if (row.filedKind != -1 && (row.type == 'Array' || row.type == 'tree')) {
          switch (row.filedKind + '') {
            case '0':
              await this.queryCustomOption(row)
              break;
            case '7':
              await this.queryProductCategory(row, 2)
              break;
            case '8':
              await this.queryProductCategory(row, 1)
              break;
            case '9':
              await this.queryProductCategory(row, 3)
              break;
          }
        }
        
      }
    },
    esCountAnalysis(row) {
      var countVOS = []
      if (row.filedKind == -1) {//专利本身栏位（专利著录）
        let value = ['MC', 'CPC', 'UPC', 'LOC'].includes(row.value) ? row.select : row.value
        countVOS = [
          {
            field: value,
            valueOne: row.valueOne,
            valueTwo: row.valueTwo,
            topN: row.topN,
            // fieldType: row.type
          }
        ]
      } else {//
        countVOS = [
          {
            field: 'field',
            fieldId: row.value,
            valueOne: row.valueOne,
            valueTwo: row.valueTwo,
            
            topN: 999,//自定义栏位没有加载更多
            ifHaveChild: row.type == 'tree' ? this.ifHaveChild : false,
            fieldType: row.type
          },
        ]
      }

      let params = {
        condition: this.searchOption || '',//检索条件
        projectId: this.projectId,//项目id
        taskId: this.taskId,//任务id
        countVOS: countVOS,//栏位的聚合入参
        customFields: this.customFields,//自定义栏位查询
        // valueOne: row.valueOne,//搜索第一个栏位的值
        // valueTwo: row.valueTwo,//搜索第二个栏位的值
        // topN: row.topN,//显示条数
        // ifHaveChild: this.ifHaveChild,//是否开启不关联模式
      }
      this.$api.esCountAnalysis(params).then(res => {
        if (res.code == 200) {
          var data = []
          if (row.type != 'tree') {
            data = this.field
          } else {
            data = this.fieldTree
          }
          var index = data.findIndex(item => {
            return item.value == row.value && item.filedKind == row.filedKind
          })
          if (index != -1) {//非专利本身搜索字段
            if (data[index].filedKind != -1 && (data[index].type == 'Array' || data[index].type == 'tree')) {
              data[index].nums = []
              for (let i = 0; i < res.data.detailDTOS.length; i++) {
                if (!isNaN(parseInt(res.data.detailDTOS[i].name))) {
                  data[index].nums.push(res.data.detailDTOS[i])
                } else {
                  data[index].options.push(res.data.detailDTOS[i])
                }
              }
            } else {//专利本身搜索字段
              let arr = res.data.detailDTOS.filter(item => {
                return item.name != '其他'
              })
              this.$set(data[index], 'options', arr)
              this.$set(data[index], 'topN', data[index].options[0].topN)
              if (data[index].options.length == data[index].topN) {//判断加载更多按钮是否存在
                this.$set(data[index], 'isShowBtn', true)
              } else {
                this.$set(data[index], 'isShowBtn', false)
              }
            }
            // this.$set(data[index], 'check', [])

          }
        }
      })
    },
    // 查询自定义栏位选项数据
    async queryCustomOption(row) {
      let params = {
        customFieldId: row.value,
      }
      await this.$api.queryCustomOption(params).then(response => {
        if (response.code == 200) {
          var data = []
          if (row.type != 'tree') {
            data = this.field
          } else {
            data = this.fieldTree
          }
          var index = data.findIndex(item => {
            return item.value == row.value && item.filedKind == row.filedKind
          })
          if (index != -1) {
            this.$set(data[index], 'options', response.data.data)
            this.$set(data[index], 'check', [])
          }
        }
      }).catch(error => {
        this.$set(row, 'option', [])
        this.$set(row, 'check', [])
      })
    },
    //获取产品或产品类别架构以及技术分类
    async queryProductCategory(item, type) {
      let params = {
        projectId: this.projectId,
        taskId: this.taskId,
        type: type,//类型：1产品类别，2产品，3技术分类，4自定义树
        typeId: item.value,//产品或类别id
      }
      await this.$api.queryTreeNodeTree(params).then(res => {
        if (res.code == 200) {
          if (row.type != 'tree') {
            var index = this.fieldTree.findIndex(item => {
              return item.value == row.value && item.filedKind == row.filedKind
            })
            if (index != -1) {
              this.$set(this.fieldTree[index], 'options', response.data.data)
              this.$set(this.fieldTree[index], 'check', [])
            }
          }
        }
      }).catch(err => {
        this.$set(row, 'option', [])
        this.$set(row, 'check', [])
      })
    },

    // 获取所有的统计栏位
    getAllCountColumns() {
      let params = {
        projectId: this.projectId,
        taskId: this.taskId,
      }
      this.$api.getAllCountColumns(params).then(res => {
        if (res.code == 200) {
          this.filedAll = []
          res.data.data.forEach(item => {
            if (item.filedKind == -1) {
              item.value = item.field
            }
          })
          var data = res.data.data
          this.handleFiled(data)
        }
      })
    },
    // 给数据添加ifHidden
    handleFiled(data) {
      for (var i = 0; i < data.length; i++) {
        data[i].check = []
        // 分类选择：获取树类型
        if ([7, 8, 9].includes(data[i].filedKind) || (data[i].filedKind == 0 && data[i].type == 'tree')) {
          this.fieldTree.push(data[i])
          //查统计todo统计接口
          this.esCountAnalysis(data[i])
          continue;
        }
        data[i].ifHidden = true
        if (data[i].filedKind != -1 && data[i].filedKind != 0) {
          continue;
        }
        // for (var j = 0; j < this.field.length; j++) {
        //   if (data[i].name == this.field[j].name && data[i].filedKind == this.field[j].filedKind) {
        //     data[i].ifHidden = false
        //     break;
        //   }
        // }
        for (var j = 0; j < this.showField.length; j++) {
          if (data[i].name == this.showField[j].name && data[i].filedKind == this.showField[j].filedKind) {
            data[i].ifHidden = false
            this.field.push(data[i])
            this.getSelect(data[i])
            //查统计todo统计接口
           this.esCountAnalysis(data[i])
            break;
          }
        }
        //获取非树(不包括数字、文本)
        if (data[i].filedKind == 0 && (data[i].type == 'String' || data[i].type == 'Integer')) {

        } else {
          this.filedAll.push(data[i])
        }

      }
      this.$store.commit('SET_SYSTEM_FIELD',this.filedAll)
    },

    // 获取显示的统计栏位
    async getShowCountColumns() {
      let params = {
        projectId: this.projectId,
        taskId: this.taskId,
      }
      await this.$api.getShowCountColumns(params).then(res => {
        if (res.code == 200) {
          //filedKind-1专利著录 0自定义字段 7产品 8产品类别 9技术分类
          // res.data.data.forEach(item => {
          //   this.$set(item, 'check', [])
          //   if (item.filedKind == -1) {
          //     item.value = item.field
          //   }
          // })
          var data = res.data.data
          // 查询筛选：获取非树类型
          // this.field = data.filter(item => {
          //   if (item.filedKind == -1 || (item.filedKind == 0 && item.type != 'tree')) {
          //     return item
          //   }
          // })
          this.showField = data.filter(item => {
            if (item.filedKind == -1 || (item.filedKind == 0 && item.type != 'tree')) {
              return item
            }
          })
          // this.field.forEach(item => {
          //   this.getSelect(item)
          // })
          
        }
      })
    },
    // 设置ipc、cpc、loc、upc选择默认值
    getSelect(data) {
      switch (data.value) {
        case 'MC':
          this.$set(data, 'select', 'IC')
          break;
        case 'CPC':
          this.$set(data, 'select', 'CPC')
          break;
        case 'UPC':
          this.$set(data, 'select', 'UPC')
          break;
        case 'LOC':
          this.$set(data, 'select', 'LOC')
          break;

        default:
          break;
      }
    },
    // 过滤组件传的值
    getFieldList(val) {
      this.filedAll = val
      this.field = this.filedAll.filter(item => {
        return item.ifHidden == false
      })
    },

    // 更多过滤项
    handleMore() {
      var data = JSON.parse(JSON.stringify(this.filedAll))
      this.$refs.fieldsVue.open(data)
    },
    //确认检索
    sure() {
      let field = JSON.parse(JSON.stringify(this.field))
      let fieldTree = JSON.parse(JSON.stringify(this.fieldTree))
      let arr = field.concat(fieldTree)
      this.$emit('ifHaveChild', this.ifHaveChild)
      this.$emit('customTab', arr)
    },
    // 加载更多
    handleLoading(val) {
      val.topN += 10
      this.getOptions(val)
    },
  }
}
</script>

<style lang="scss">
.patent-tree-filter {
  height: 100%;

  .patent-tree-filter-main {
    height: 100%;
    padding: 10px 0;

    .no-data {
      text-align: center;
      color: #6b6868;
    }
  }

  .change-show-type {
    font-size: 13px;

    .change-show-type-info {
      color: #6b6868;
      padding-left: 10px;
    }

    .el-form-item__label {
      padding: 0 !important;
      line-height: 20px;
    }

    .el-form-item__content {
      height: 30px;
      line-height: 30px;
    }
  }
}

.patent-query-filter-search {
  display: flex;
}

.patent-query-filter-search-input {
  margin-right: 5px;
}

.patent-query-filter-search-bottom {
  text-align: center;
  margin-top: 10px;
}

.year-data-picker {
  width: 200px;
  display: flex;
  justify-content: space-between;

  .el-input__prefix {
    display: none;
  }

  .el-input__inner {
    padding: 10px;
    text-align: center;
  }
}

.year-data-input {
  width: 100px;
}

.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;
  }
}

.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 {}

  .b {
    text-align: center;
    width: 30px;
  }

  .c {
    padding-left: 5px;
  }
}

.query-read-status_is-active {
  background: #409EFF !important;
  color: #ffffff !important;
}
</style>