<template>
  <div class="patent-tree-filter">
    <el-container>
      <el-header class="patent-query-filter-header" v-if="isHidden">
        <!-- <template v-if="readList.length>0"> -->
        <div class="query-read-status" style="margin: 0px 5px 0px 5px;" 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>
      <!-- </template>
      <template v-else>
        <div style="margin: 0 auto;"  >
          暂无数据
        </div>
      </template> -->
        <!-- <div class="query-read-status" style="margin: 0px 5px 0px 5px;" 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.length>0">
          <el-collapse v-model="activeNames" @change="handleChange"  style="margin: 0px 5px 0px 5px;">
            <!-- 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].name"  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" placeholder="请选择时间"></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" placeholder="请选择时间"></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.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="onChangeTree"
                    :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" v-if="item.type!=6">
                <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 "@/views/task/components/mixins";
import { getTreeLastChildren, getTreeDataList } from "@/utils";

export default {
  mixins: [patentQueryMixins],
  props:["reportId","taskId","isHidden"],
  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.key) === node)
      if (data) {
        return data.count
      }
      return 0
    },
    //模糊查询，每个面板中查询自定义字段的选项
    handleSearch(item) {
      console.log(item, this.sourceData, this.sourceQuery);
      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
      let a = {
        fieldId: item.id,
        name: sourceQueryName,
      }
      this.$api.getPatentField(a).then(res => {
        console.log("查询成功", res);
        res.data.map(item => {
          item.label = item.name
          // item.key = item.id
          return item
        })
        this.$set(this.sourceData,item.id,res.data)
      })
      
    },
    // 树类型勾选后进行筛选
    onChangeTree(a, b) {
      console.log(a,b);
      if (b) {
        this.sourceQuery[a.fieldId].checked.push(a.id);
        if (a.children) {
          this.onTree(a.children)
        }
      } else {
        console.log(this.sourceQuery[a.fieldId].checked);
        let aId=this.sourceQuery[a.fieldId].checked.findIndex(item => {
          return item==a.id
        })
        if (aId!=-1) {
          this.sourceQuery[a.fieldId].checked.splice(aId,1)
        }
        if (a.children) {
          this.onTree2(a.children)
        }
      }
      this.onChange();
    },
    onTree2(data) {
      console.log(data,"进来");
      for (let i = 0; i < data.length; i++){
        let aId=this.sourceQuery[data[i].fieldId].checked.findIndex(item => {
          return item==data[i].id
        })
        console.log(aId);
        if (aId!=-1) {
          this.sourceQuery[data[i].fieldId].checked.splice(aId, 1)
          console.log(this.sourceQuery[data[i].fieldId].checked);
        }
        if (this.sourceQuery[data[i].fieldId].checked.length>0) {
          console.log("进来子节点");
          if (data[i].children) {
            this.onTree2(data[i].children)
          } 
        }
      }
    },
    onTree(data) { 
      console.log(data);
      data.forEach(item => {
          this.sourceQuery[item.fieldId].checked.push(item.id)
          if (item.children) {
            this.onTree(item.children)
          }
      })
    },
    //勾选后进行筛选
    onChange(id) {
      let field = []
      console.log(this.sourceQuery);
      let k = this.sourceQuery.filter(item => {
        return item.checked.length>0
      })
      console.log(k,id);
      k.forEach(item => {
        for (let i = 0; i < item.checked.length; i++){
           field.push({
            fieldId: item.key,
            key:item.checked[i]
          })
        }
       
      })
      console.log(field);
      
      this.$emit("onChange",field)
    }, 
    //全选,点击勾选全部的自定义选项并查找相关专利
    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,
        taskId:this.taskId,
        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: 9999,
            // order: 'desc',
            label: '',
            loading: false,
            checked: [],
            // classId: '1',
            type: item.type,
            isEnd: false,
            datePicker: ['', '']
          })
        }
        console.log(this.sourceQuery);
      })
      this.handleChange([this.form[0].id])
    },

    // 初始化获取
    async getPatentQueryField(refresh, loadForm) {
      let params = {
        reportId: this.reportId,
        // taskId:this.taskId,
      }
      //获取用户的自定义字段
      await this.$api.listPatentField(params).then(res => {
       if (res.code==200&&res.data.length>0) {
        this.data = res.data
        this.activeNames.push(this.data[0].id)
        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 => {
              this.$set(item,"option",resA.data)
            })
          }

        })
       }
        
      })
      //获取用户的自定义字段后调用initFieldData将数据给到field
      if (this.data.length>0) {
        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,
        taskId:this.taskId,
        // 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);
          // if (response.data.type==1) {
          //   response.data
          // }
          const records = response.data
          console.log(response.data);
          let temp = this.sourceData[id]
          
          if (!temp || refresh) {
            temp = records
          } else {
            temp.push(...records)
          }
          console.log(temp);
        this.sourceQuery[id].isEnd = temp.length >= response.data.length
        this.$set(this.sourceData, id, temp)
        }
      })
    },
    // 每一行事件,每点击一次调用一次接口，传入自定义字段id
    handleChange(data) {
      // console.log("每一项自定义字段数据", this.data);
      const val = data[data.length - 1];
      if (val && this.hasSource.indexOf(val) === -1) {
        this.hasSource.push(val)
        this.getPatentQueryFieldSource(val)
      }
    },
    // 自定义头部事件(全部/已读/未读)
    handleReadQuery(type) {
      console.log(type);
      //all  read   unread
      this.taskStatus = type
      this.returnData.read = type
      this.refreshSourceData()
      this.$emit('onTaskStatus', this.taskStatus)
    },
    refreshSourceData() {
      this.activeNames = []
      this.hasSource = []
      this.sourceData = {}
      for (let key in this.sourceQuery) {
        this.sourceQuery[key].current = 1
        this.sourceQuery[key].label = ''
      }
    },
    // readList: {
    //     3: '全部',
    //     1: '已读',
    //     0: '未读',
    //   },
    taskReTaskStateCount() {
      var a ={
        reportId:this.reportId
      }
      if(this.taskId){
        a.taskId = this.taskId
        console.log(this.taskId);
        this.$api.taskReTaskStateCount(a).then(res => {
          console.log(res);
          this.readList=res.data
        })
      }else {
        this.$api.ReStateCount(a).then(res => {
          console.log(res);
          this.readList=res.data
        })
      }
      
    }

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