<template>
  <div class="patent-tree-filter">
    <el-container>
      <el-header class="change-show-type" v-show="treeList.length">
        <el-form label-position="top">
          <el-form-item label="开启不关联模式">
            <el-switch v-model="switchType" @change="onChange2"></el-switch>
            <span class="change-show-type-info">描述：主分类不包含子分类</span>
          </el-form-item>
        </el-form>
      </el-header>
      <el-main class="patent-tree-filter-main">
        <template v-if="treeList.length">
          <div v-if="refresh">
            <el-collapse v-model="activeNames" @change="handleChange">
              <el-collapse-item v-for="item in treeList" :title="item.name" :name="item.id">
                <el-tree
                    @check-change="onChange"
                    :ref="item.id"
                    :data="item.option"
                    show-checkbox
                    node-key="id"
                    check-strictly
                    default-expand-all
                >
                  <div class="custom-filter-tree-node" slot-scope="{ node, data }">
                    <span class="name">{{ data.name }}</span>
                    <span class="total">({{ getCount(item.id, data.id) }})</span>
                  </div>
                </el-tree>
              </el-collapse-item>
            </el-collapse>
          </div>
        </template>
        <template v-else>
          <div class="no-data">暂无数据</div>
        </template>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { patentQueryMixins } from "../mixins";
import { getTreeLastChildren, getTreeDataList } from "@/utils";

export default {
  mixins: [patentQueryMixins],
  data() {
    return {
      treeList: [],
      activeNames: [],
      hasSource: [],
      sourceQuery: {},
      queryParams: {
        projectId: 0,
        folder: null
      },
      sourceData: {},
      switchType: false,
      refresh: true
    }
  },
  watch: {
    closeFieldDrawer() {
      this.getPatentQueryTree()
    },
    submitIndexSetting() {
      this.activeNames = []
      this.hasSource = []
    }
  },
  mounted() {
  },
  methods: {
    getCount(key, node) {
      if (!this.sourceData[key]) {
        return 0;
      }
      const data = this.sourceData[key].find(item => parseInt(item.value) === node)
      if (data) {
        return data.count
      }
      return 0
    },
    loadData() {
      this.queryParams.projectId = this.projectId
      this.queryParams.folder = this.folder
      this.getPatentQueryTree()
      // console.log(this.sourceData)
    },
    reset() {
      this.treeList.map(item => {
        this.$set(this.sourceQuery, item.id, {
          projectId: this.queryParams.projectId,
          folder: this.queryParams.folder,
          key: item.id,
          loading: false,
          checked: [],
          type: item.type
        })
        this.handleChange([item.id])
      })
    },
    getPatentQueryTree() {
      this.$api.getProjectFieldTree({ projectId: this.queryParams.projectId }).then(response => {
        this.treeList = response.data
        this.$nextTick(() => {
          const data = this.queryData.filter(item => item.type === 'tree')
          for (let val of data) {
            const keys = val.key.split('-')
            this.switchType = keys[1] === '1'
            this.$refs[keys[0]][0].setCheckedKeys(val.data.map(item => item.value))
          }
          this.reset()
        })
      })
    },
    getPatentQueryTreeSource(key) {
      let data = JSON.parse(JSON.stringify(this.params))
      data.field.filter(item => item.type === '6').map(item => item.value = [])
      let params = {
        projectId: this.sourceQuery[key].projectId,
        folder: this.queryParams.folder,
        key: this.sourceQuery[key].key + '-' + (this.switchType ? '1' : '0'),
        type: this.sourceQuery[key].type,
        current: 1,
        size: 9999,
        queryParams: data
      }
      this.sourceQuery[key].loading = true
      this.$api.getPatentQuerySourceList(params).then(response => {
        this.$set(this.sourceData, key, response.data.records)
        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.getPatentQueryTreeSource(val)
      }
    },
    onChange(node, checked) {
      const refs = this.$refs
      const { fieldId, id } = node
      let data = []
      for (let key in refs) {
        let val = []
        const keys = refs[key][0].getCheckedKeys()
        const treeNodes = getTreeDataList(this.treeList.find(item => item.id === parseInt(key)).option || [], [])
        const selected = treeNodes.filter(item => keys.indexOf(item.id) !== -1)
        selected.map(item => {
          val.push(item.id)
          if (!this.switchType) {
            val.push(...getTreeDataList([item], []).map(item => item.id))
          }
        })
        const key2 = key + '-' + (this.switchType ? '1' : '0')
        data.push({
          key: key2,
          type: '6',
          value: val
        })
        this.updateQueryData(parseInt(key), key2, keys, treeNodes)
      }
      this.$emit('on-change', data)
      // this.activeNames = [fieldId]
      // this.hasSource = [fieldId]
      // this.sourceData = {}
      // this.getPatentQueryTreeSource(fieldId)
    },
    updateQueryData(id, key, selected, data) {
      const index = this.queryData.map(item => item.key).indexOf(key)
      const tree = this.treeList.find(item => item.id === id)
      const value = {
        data: data.filter(item => selected.indexOf(item.id) !== -1).map(item => {
          return {
            label: item.name,
            value: item.id,
          }
        }),
        type: 'tree',
        key: key,
        name: tree.name || '',
        tree: tree.option
      }
      if (index === -1) {
        this.queryData.push(value)
      } else {
        this.$set(this.queryData, index, value)
      }
    },
    getChildrenNode(treeList) {

    },
    onChange2() {
      this.hasSource = []
      this.activeNames = []
      this.sourceData = {}
      this.reset()
      this.refresh = false
      this.$emit('on-change', [])
      this.$nextTick(() => {
        this.refresh = true
      })
      this.$store.commit('SET_PATENT_QUERY_DATA', this.queryData.filter(data => data.type !== 'tree'))
      // for (let key in this.$refs) {
      //   this.getPatentQueryTreeSource(key)
      // }
      // this.onChange()
    },
    refreshTreeSelected(keys, id) {
      try {
        this.$nextTick(() => {
          this.$refs[keys[0]][0].setChecked(id, false)
        })
      } catch (e) {
        // console.error(e)
      }
    }
  }
}
</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;
    }
  }
}
</style>