<template>
  <div class="patent-tree-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' : readStatus[key].value == returnData.read }" @click="handleReadQuery(readStatus[key].value)">
          <span class="a">(<span class="b">{{ item }}</span>)</span>
          <span class="c">{{ readStatus[key].lable }}</span>
        </div>
      </el-header> -->
      <el-main class="patent-tree-filter-main">
        <!-- <template v-if="field"> -->
          <div v-if="data.length>0">
             <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] && item.type!=2">
                <div class="patent-query-filter-search">
                  <div class="patent-query-filter-search-input">
                    <el-input v-if="(item.type!=1&&item.type!=6)" v-model="sourceQuery[item.id].label"  size="small" placeholder="请输入查询内容"></el-input>
                    <div v-else-if="(item.type!=6)" 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 v-if="item.type!=6"  @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.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-tree
                    v-else
                    @check-change="onChange1"
                    :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>
          </div>
         <div v-else style="text-align:center">
          暂无数据
         </div>
      
        <!-- </template> -->
        
        <!-- <template v-else> -->
        <!-- <template > -->
          <!-- <div class="no-data">暂无数据</div>
        </template> -->
      </el-main>
    </el-container>
  </div>
</template>

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

export default {
  mixins: [patentQueryMixins],
  props:["reportId","taskId"],
  data() {
    return {
      activeNames: [],
      hasSource: [],
      sourceQuery: [],
      queryParams: {
        reportId: this.reportId,
        folder: null,
        fieldId: "",
        // type:6,
        taskId: this.taskId,
        current: 1,
        size: 10,
        total: 0,
      },
      sourceData: [],
      // switchType: false,
      onChanges: [],
      // selected: {},
      field: [],//数据
      visible: false,
      form: [],
      data: [],
      loading: false,
      // btnLoading: false,
      // btnLoading2: false,
      readList: {
       
      },
      returnData: {
        taskStatus: '',
        filedOptions: [],
        read:"3",
      },
      keyId: "",
      readStatus: {
        all: {
          lable: "全部",
          value:"3"
        },
        read:  {
          lable: "已读",
          value:"1"
        },
        noRead:  {
          lable: "未读",
          value:"0"
        },
      },  
      taskStatus:"",
    }
  },
  watch: {
    
    closeFieldDrawer() {
      this.getPatentQueryField()
    },
    // submitIndexSetting() {
    //   this.refreshSourceData()
    // }
  },
  mounted() {
    // this.getPatentQueryTreeSource()
  },
  methods: {
    async loadData() {
      await this.getPatentQueryField(false, true)
      // this.taskReTaskStateCount()
    },
    getCount(id, node) {
      // console.log(this.sourceData,id,node);
      if (!this.sourceData[id]) {
        return 0;
      }
      const data = this.sourceData[id].find(item => parseInt(item.value) === node)
      if (data) {
        return data.count
      }
      return 0
    },
    //模糊查询，每个面板中查询自定义字段的选项
    handleSearch(item) {
      this.sourceData[item.id] = []
      // this.sourceQuery[item.key].checked = []
      this.sourceQuery[item.id].current = 1
      this.getPatentQueryFieldSource(item.id)
    },
    PushValue(data) {
      console.log(data);
      data.forEach(items => {
      //   let a=this.sourceQuery[items.fieldId].checked.findIndex(item => {
      //     return item==items.id
      // })
      //   console.log(data,a);
      //   if (a!=-1) {
      //     this.sourceQuery[items.fieldId].checked.splice(a,1)
      //   } else {
      //     this.sourceQuery[items.fieldId].checked.push(items.id)
         
      // }
      this.sourceQuery[items.fieldId].checked.push(items.id)
      if (items.children) {
            this.PushValue(items.children)
          }
      })
     
    },
    DeleteValue(data){
      data.forEach(items => {
        let a=this.sourceQuery[items.fieldId].checked.findIndex(item => {
          return item==items.id
        })
        if (a!=-1) {
          this.sourceQuery[items.fieldId].checked.splice(a,1)
        }
      if (items.children) {
            this.DeleteValue(items.children)
          }
      })
    },
    //勾选后进行筛选
    onChange1(node, checked) {
      console.log(node, checked);
      if (checked) {
        this.sourceQuery[node.fieldId].checked.push(node.id)
        if (node.children) {
          this.PushValue(node.children)
        }
        
      } else {
        let a=this.sourceQuery[node.fieldId].checked.findIndex(item => {
          return item==node.id
        })
        if (a!=-1) {
          this.sourceQuery[node.fieldId].checked.splice(a,1)
        }
        if (node.children) {
          this.DeleteValue(node.children)
        }
      }
      this.onChange()
      // let field=[]
      // field.push({
      //   key: node.id,
      //   type:node.type,
      // })
      // this.$emit("onChange-one",field)
      
    },
    onChange(id) {
      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
      //   })
      // }
       let k = this.sourceQuery.filter(item => {
        return item.checked.length>0
       })
      k.forEach(item => {
        field.push({
          key: item.type==6?item.key+"-0":item.key,
          type: item.type,
          classId: item.classId,
          value:item.checked,
        })
      });
      // const res = new Map()
      console.log(this.field);
      let a=this.field[0].projectId
      // 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
      console.log(field);
      this.$emit('onChange', {field,a})
      // let field = []
      // let Change=[]
      // console.log(this.sourceQuery);
      // let k = this.sourceQuery.filter(item => {
      //   return item.checked.length>0
      // })
      
      // k.forEach(item => {
      //   for (let i = 0; i < item.checked.length; i++){
      //     Change.push({
      //       projectId: this.data[0].projectId,
      //       field: {
      //           fieldId: item.key,
      //           key:item.checked[i],
      //         }
      //     })
      //     //  field.push({
      //     //   fieldId: item.key,
      //     //   key:item.checked[i]
      //     // })
      //   }
       
      // })
      // console.log(Change);
      // console.log(this.sourceData);
      // console.log(this.data[0].projectId);
      // // "projectId": 0,
     
      
      // this.$emit("onChange",Change)
    }, 
    //全选,点击勾选全部的自定义选项并查找相关专利
    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,
          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.postfieldFromPAS(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.id
      this.sourceQuery[key].checked = []
      this.onChange(key)
    },
    //加载更多
    handleLoadMore(item) {
      console.log(item);
      this.sourceQuery[item.id].current = this.sourceQuery[item.id].current + 1
      this.getPatentQueryFieldSource(item.id)
    },
    //打开面板
    handleChange(data) {
      const val = data[data.length - 1];
      if (val && this.hasSource.indexOf(val) === -1) {
        this.hasSource.push(val)
        this.getPatentQueryFieldSource(val)
      }
    },
    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,
        key:this.sourceQuery[key].type==6?key+"-0":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.postfieldFromPAS(params).then(response => {
        const records = response.data.records
        console.log(records);
        let temp = this.sourceData[key]
        if (!temp || refresh) {
          temp = records
        } else {
          temp.push(...records)
        }
        
        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
      })
    },
   
    // 初始化获取
    async getPatentQueryField(refresh, loadForm) {
      let params = {
        reportId: this.reportId,
        // taskId:this.taskId,
      }
      //获取用户的自定义字段
      await this.$api.getfieldFromPAS(params).then(res => {
        this.data = res.data
        console.log(this.data);
        // this.initFieldData(this.data)
        //   if (loadForm) {
        //     this.initFieldQueryForm()
        //   }

        if(this.data.length>0){
          let dataA = this.data.filter(item => item.type != 6)
        // 树类型
        let tree = {
          projectId: dataA[0].projectId,
        }
        this.$api.getPatentQueryTree(tree).then(res => {
          for (let i = 0; i < res.data.length; i++) {
            dataA.push(res.data[i])
          }
          this.initFieldData(dataA)
          if (loadForm) {
            this.initFieldQueryForm()
          }
        })
        }
        
      })
    },
    initFieldData(data) {
      console.log(data)
      this.field = data
      this.form = JSON.parse(JSON.stringify(data))
    },

    initFieldQueryForm() {
      console.log(this.form);
      this.form.map(item => {
        const temp = this.sourceQuery[item.id]
        if (!temp) {
          this.$set(this.sourceQuery, item.id, {
            projectId: item.projectId,
            folder: this.queryParams.folder,
            key: item.id,
            current: 1,
            size: 999999,
            order: 'desc',
            label: '',
            loading: false,
            checked: [],
            classId: '1',
            type: item.type,
            isEnd: false,
            datePicker: ['', '']
          })
        }
        // this.handleChange([item.id])
      })
    },
  
      
    

  }
}
</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>