<template>
  <div class="patent-tree-filter">
    <el-container>
      <el-main class="patent-tree-filter-main">
        <!-- <template v-if="field"> -->
          <el-collapse v-model="activeNames" @change="handleChange"  >
            <!-- v-if="sourceQuery[item.key]" -->
              <el-collapse-item v-for="item in field" :title="item.name" :name="item.id" v-if="sourceQuery[item.id]" >
                <div class="patent-query-filter-search">
                  <div class="patent-query-filter-search-input">
                    <el-input v-if="(item.type!=1)" v-model="sourceQuery[item.id].name"  size="small" placeholder="请输入查询内容"></el-input>
                    <div v-else class="year-data-picker">
                      <el-date-picker  clear-icon size="small" v-model="sourceQuery[item.id].datePicker[0]"  type="year" value-format="yyyy"></el-date-picker>
                      <span style="margin: 5px;">至</span>
                      <el-date-picker clear-icon size="small" v-model="sourceQuery[item.id].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-model="sourceQuery[item.key].checked" @change="onChange(item.key)"> -->
                <!-- v-moudel勾选 -->
             <el-checkbox-group v-if="item.type!=6" v-model="sourceQuery[item.id].checked"  @change="onChange(item.id)">
                <div class="source-checkbox">
                  <el-checkbox v-for="source in sourceData[item.id]" :label="source.key">
                    <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-tree
                    v-else
                    @check-change="onChange(item.id)"
                    :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> 

              <div class="patent-query-filter-search-bottom">
                <el-button type="success" size="small" @click="handleSelectAll(item)" >全选</el-button>
                <el-button type="danger" size="small" @click="handleSelectCancel(item)">取消</el-button>
                <el-button v-if="!sourceQuery[item.id].isEnd" type="primary" size="small" @click="handleLoadMore(item)"
                  :loading="sourceQuery[item.id].loading">加载更多</el-button>
                <span v-else></span>
              </div>
            </el-collapse-item>
          </el-collapse>
      
        <!-- </template> -->
        
        <!-- <template v-else> -->
        <!-- <template > -->
          <!-- <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],
  props:["reportId","taskId"],
  data() {
    return {
      treeList: [],
      activeNames: [],
      hasSource: [],
      sourceQuery: [],
      queryParams: {
        reportId: this.reportId,
        folder: null,
        fieldId: "",
        // type:6,
        taskId: this.taskId,
        current: 1,
        size: 10,
        total: 0,
      },
      sourceData: [],
      switchType: false,
      // refresh: true,
      // defaultProps: {
      //   children: 'children',
      //   label: 'name'
      // },
      onChanges: [],
      selected: {},
      field: [],//数据
      visible: false,
      form: [],
      data: [],
      loading: false,
      btnLoading: false,
      btnLoading2: false,
      returnData: {
        read: 'all',
        field: [],
        id: ''
      },
      keyId:null,
    }
  },
  watch: {
    // closeFieldDrawer() {
    //   this.getPatentQueryTree()
    // },
    // submitIndexSetting() {
    //   this.activeNames = []
    //   // this.hasSource = []
    // },
    
    closeFieldDrawer() {
      this.getPatentQueryField()
    },
    // submitIndexSetting() {
    //   this.refreshSourceData()
    // }
  },
  mounted() {
    // this.getPatentQueryTreeSource()
  },
  methods: {
    async loadData() {
      await this.getPatentQueryField(false, true)
    },
    getCount(id, node) {
      if (!this.sourceData[id]) {
        return 0;
      }
      const data = this.sourceData[id].find(item => parseInt(item.id) === node)
      if (data) {
        return data.count
      }
      return 0
    },
    //模糊查询，每个面板中查询自定义字段的选项
    handleSearch(item) {
      this.sourceData[item.id] = []
      this.sourceQuery[item.id].checked = []
      this.sourceQuery[item.id].current = 1
      // console.log(item);
      let sourceQueryName = this.sourceQuery[item.id].name
      this.$api.getPatentField({ filedId: item.id, name: sourceQueryName }).then(res => {
        console.log("查询成功", res);
        res.data.map(item => {
          item.label = item.name
          item.key = item.id
          return item
        })
        // this.sourceData[item.id] = res.data
        this.$set(this.sourceData,item.id,res.data)
        console.log(this.sourceData,item.id,res.data);
      })
      
      // this.getPatentQueryFieldSource(item.id)
    },
    //勾选框
    // onChanges(key) {
    //   console.log(id);
    // },
    onChange(id) {
      let field = []
      // for (let name in this.sourceQuery) {
      //     console.log(this.sourceQuery[name]);
      console.log(this.sourceQuery);
      let k = this.sourceQuery.filter(item => {
        return item.checked.length>0
      })
      console.log(k);
      k.forEach(item => {
        for (let i = 0; i < item.checked.length; i++){
           field.push({
            fieldId: item.key,
            key:item.checked[i]
          })
        }
       
      })
      // // for (let i of this.sourceQuery[id].checked) {
      // //   this.keyId = i
      // //   console.log(this.sourceQuery[id].checked);
      // // }
      // console.log(this.keyId);
      //     field.push({
      //       key: this.keyId,
      //       fieldId: id,
      //       // classId: this.sourceQuery[name].classId,
      //       type: this.sourceQuery[id].type,
      //     })
      //   // }
      // // }
      console.log(field);
      this.$emit("onChange",field)
      // 左侧字段勾选调用
      // this.$api.PatentQueryFieldSourceVO(params).then(res => {
      //   console.log(res);
      //   this.$emit("onChange",res.data)
      // })
      // 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)
    }, 
    //全选,点击勾选全部的自定义选项并查找相关专利
    handleSelectAll(item) {//全选
      console.log(item);
      const key = item.id
      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,
        fieldId: key,
        reportId: this.reportId,
        type: this.sourceQuery[key].type,
        startDate: this.sourceQuery[key].datePicker[0],
        endDate: this.sourceQuery[key].datePicker[1],
      }
      this.sourceQuery[key].loading = true
       // 查询源接口(返回的数据是自定义选项)
      this.$api.sourceQueryPatentField(params).then(response => {
        console.log(response.data);
        const records = response.data
        this.sourceQuery[key].checked = records.map(item => item.key)
        this.onChange(key)
        this.sourceQuery[key].loading = false
      }).catch(error => {
        this.sourceQuery[key].loading = false
      })
    },
    //取消
    handleSelectCancel(item) { //取消
      const key = item.id
      this.sourceQuery[key].checked = []
      this.onChange(key)
    },
    //加载更多
    handleLoadMore(item){
      this.sourceQuery[item.id].current = this.sourceQuery[item.id].current + 1
      this.getPatentQueryFieldSource(item.id)
    },
    initFieldQueryForm() {
      this.form.map(item => {
        const temp = this.sourceQuery[item.id]
        if (!temp) {
          this.$set(this.sourceQuery, item.id, {
            reportId: this.reportId,
            // folder: this.queryParams.folder,
            key: item.id,
            current: 1,
            size: 10,
            // order: 'desc',
            label: '',
            loading: false,
            checked: [],
            // classId: '1',
            type: item.type,
            isEnd: false,
            datePicker: ['', '']
          })
        }
      })
    },
    // 初始化获取
    async getPatentQueryField(refresh, loadForm) {
      let params = {
        reportId: this.reportId,
        // taskId:this.taskId,
      }
      //获取用户的自定义字段
      await this.$api.listPatentField(params).then(res => {
        this.data = res.data
        this.data.forEach((item) => {
          if (item.type == 6) {
            let paramr = {
              fieldId:item.id,
              type :item.type,
              reportId :this.reportId,
            }
            this.$api.listPatentFieldOption(paramr).then(resA => {
              // console.log(resA.data);
              // let dataA=resA.data.filter(item => {
              //     return item.type!=2
              // })
              // console.log(dataA);
              this.$set(item,"option",resA.data)
            })
          }
        })
        
      })
      //获取用户的自定义字段后调用initFieldData将数据给到field
      this.initFieldData(this.data)
      if (loadForm) {
        this.initFieldQueryForm()
      }
      //???
      if (refresh) {
        this.visible = false
      }
      // this.reset()
    },
    //将自定义字段全部数据给field
    initFieldData(data) {
      console.log("initFieldData",data);
      this.field = data
      this.form = JSON.parse(JSON.stringify(data))
    },
    // 请求自定义选项列表
    getPatentQueryFieldSource(id, refresh = false) {//(key, refresh = false)
      // console.log(this.params);
      // let data = JSON.parse(JSON.stringify(this.params))
      let value = {
        fieldId: id,
        // projectId: this.sourceQuery[id].projectId,
        // folder: this.sourceQuery[key].folder,
        // key: this.isClassNumber(key) ? (key + '-' + this.sourceQuery[key].classId) : this.sourceQuery[key].key,
        current: this.sourceQuery[id].current,
        size: this.sourceQuery[id].size,
        // order: this.sourceQuery[id].order,
        label: this.sourceQuery[id].label,
        type: this.sourceQuery[id].type,
        startDate: this.sourceQuery[id].datePicker[0],
        endDate: this.sourceQuery[id].datePicker[1],
        refresh: false,
      }
      this.$api.sourceQueryPatentField(value).then(response => {
        console.log(response.data);
        if (response.code == 200) {
          console.log("每一项自定义字段数据中的值", response.data);
          
          const records = response.data
          console.log(records);
          let temp = this.sourceData[id]
          if (!temp || refresh) {
            temp = records
          } else {
            temp.push(...records)
          }
        // if (this.isClassNumber(id)) {
        //   this.classTemp.push(...temp)
        // }
        // this.sourceQuery[id].isEnd = temp.length >= response.data.total
        this.sourceQuery[id].isEnd = temp.length >= response.data.length
        this.$set(this.sourceData, id, temp)
        // this.sourceQuery[id].loading = false
          // this.sourceData = res.data
          // console.log(this.sourceData);
        }
      })
    },
    // 每一行事件,每点击一次调用一次接口，传入自定义字段id
    handleChange(data) {
      console.log("每一项自定义字段数据", data);
      const val = data[data.length - 1];
      if (val && this.hasSource.indexOf(val) === -1) {
        this.hasSource.push(val)
        this.getPatentQueryFieldSource(val)
      }
    },




    // reset() {
    //   this.field.map(item => {
    //     this.$set(this.sourceQuery, item.id, {
    //       // projectId: this.queryParams.projectId,
    //       // folder: this.queryParams.folder,
    //       fieldId: item.id,
    //       key: item.id,
    //       loading: false,
    //       checked: [],
    //       type: item.type,
    //     })
    //     // this.handleChange([item.id])
    //   })
    // },

    // 获取树数据来源
    // getPatentQueryTree(key) {
    //   let a = {
    //     reportId: this.reportId,
    //     fieldId: this.field[key].id,
    //     type:this.field[key].type,
    //   }
    //   this.$api.listPatentFieldOption(a).then(response => {
    //     console.log(response);
    //     if (response.code == 200) {
    //       this.$set(this.field[key],"option",response.data)
    //     }
    //   })
    // },
    //专利查询获取自定义字段,将数据给到field
    // getPatentQueryTreeSource(key) {
    //   this.selected = {}
    //   let params = {
    //     reportId: this.reportId,
    //     taskId:this.taskId,
    //   }
    //   this.$api.listPatentField(params).then(response => {
    //     // console.log(response);
    //     // // this.field=response.data
    //     // console.log(this.field);
    //     // for (var value of response.data) {
    //     //   switch (value.type) {
    //     //     case 0:
    //     //     case 1:
    //     //     case 2:
    //     //       var selected = []
    //     //         selected.push({
    //     //           label: '',
    //     //           value: -1,
    //     //         })
    //     //       this.$set(this.selected, value.id, selected)
    //     //       break
    //     //     case 3:
    //     //     case 4:
    //     //       this.$set(this.selected, value.id, null)
    //     //       break
    //     //     case 5:
    //     //     case 6: 
    //     //       this.$set(this.selected, value.id, [])
    //     //       break
    //     //   }
    //     //  }
        
    //     this.field = response.data
    //     for (let i = 0; i < this.field.length; i++){
    //       // console.log(this.field[i].option);
    //       // this.sourceData.push(this.field[i].option)
    //        this.getPatentQueryTree(i);
    //     }
        
    //   }).catch(error => {
    //     // this.sourceQuery[key].loading = false
    //   })
    // },
  }
}
</script>

<style lang="scss">
// .patent-tree-filter{
//   margin: 0;
// }
// .el-main{
//   padding: 0;
//   width: 200px;
// }
// .el-input__inner{
//   width: 200px;
// }
.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;
    }
  }
</style>